File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1172.2.118.2.5: download - view: text, annotated - select for diffs
Sun Jul 19 15:12:04 2020 UTC (3 years, 11 months ago) by raeburn
Branches: version_2_11_3_msu
- For 2.11.3 (modified)
  Include changes in 1.1419, 1.1420, 1.1421, 1.1422

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1172.2.118.2.5 2020/07/19 15:12:04 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 LONCAPA qw(:DEFAULT :match);
   99: use LONCAPA::Configuration;
  100: use LONCAPA::lonmetadata;
  101: use LONCAPA::Lond;
  102: use LONCAPA::transliterate;
  103: 
  104: use File::Copy;
  105: 
  106: my $readit;
  107: my $max_connection_retries = 20;     # Or some such value.
  108: 
  109: require Exporter;
  110: 
  111: our @ISA = qw (Exporter);
  112: our @EXPORT = qw(%env);
  113: 
  114: # ------------------------------------ Logging (parameters, docs, slots, roles)
  115: {
  116:     my $logid;
  117:     sub write_log {
  118: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
  119:         if ($context eq 'course') {
  120:             if (($cnum eq '') || ($cdom eq '')) {
  121:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  122:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  123:             }
  124:         }
  125: 	$logid ++;
  126:         my $now = time();
  127: 	my $id=$now.'00000'.$$.'00000'.$logid;
  128:         my $logentry = {
  129:                          $id => {
  130:                                   'exe_uname' => $env{'user.name'},
  131:                                   'exe_udom'  => $env{'user.domain'},
  132:                                   'exe_time'  => $now,
  133:                                   'exe_ip'    => $ENV{'REMOTE_ADDR'},
  134:                                   'delflag'   => $delflag,
  135:                                   'logentry'  => $storehash,
  136:                                   'uname'     => $uname,
  137:                                   'udom'      => $udom,
  138:                                 }
  139:                        };
  140:         return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
  141:     }
  142: }
  143: 
  144: sub logtouch {
  145:     my $execdir=$perlvar{'lonDaemons'};
  146:     unless (-e "$execdir/logs/lonnet.log") {	
  147: 	open(my $fh,">>","$execdir/logs/lonnet.log");
  148: 	close $fh;
  149:     }
  150:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  151:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  152: }
  153: 
  154: sub logthis {
  155:     my $message=shift;
  156:     my $execdir=$perlvar{'lonDaemons'};
  157:     my $now=time;
  158:     my $local=localtime($now);
  159:     if (open(my $fh,">>","$execdir/logs/lonnet.log")) {
  160: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
  161: 	print $fh $logstring;
  162: 	close($fh);
  163:     }
  164:     return 1;
  165: }
  166: 
  167: sub logperm {
  168:     my $message=shift;
  169:     my $execdir=$perlvar{'lonDaemons'};
  170:     my $now=time;
  171:     my $local=localtime($now);
  172:     if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
  173: 	print $fh "$now:$message:$local\n";
  174: 	close($fh);
  175:     }
  176:     return 1;
  177: }
  178: 
  179: sub create_connection {
  180:     my ($hostname,$lonid) = @_;
  181:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  182: 				     Type    => SOCK_STREAM,
  183: 				     Timeout => 10);
  184:     return 0 if (!$client);
  185:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
  186:     my $result = <$client>;
  187:     chomp($result);
  188:     return 1 if ($result eq 'done');
  189:     return 0;
  190: }
  191: 
  192: sub get_server_timezone {
  193:     my ($cnum,$cdom) = @_;
  194:     my $home=&homeserver($cnum,$cdom);
  195:     if ($home ne 'no_host') {
  196:         my $cachetime = 24*3600;
  197:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
  198:         if (defined($cached)) {
  199:             return $timezone;
  200:         } else {
  201:             my $timezone = &reply('servertimezone',$home);
  202:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
  203:         }
  204:     }
  205: }
  206: 
  207: sub get_server_distarch {
  208:     my ($lonhost,$ignore_cache) = @_;
  209:     if (defined($lonhost)) {
  210:         if (!defined(&hostname($lonhost))) {
  211:             return;
  212:         }
  213:         my $cachetime = 12*3600;
  214:         if (!$ignore_cache) {
  215:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
  216:             if (defined($cached)) {
  217:                 return $distarch;
  218:             }
  219:         }
  220:         my $rep = &reply('serverdistarch',$lonhost);
  221:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
  222:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
  223:                 $rep eq '') {
  224:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
  225:         }
  226:     }
  227:     return;
  228: }
  229: 
  230: sub get_server_loncaparev {
  231:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
  232:     if (defined($lonhost)) {
  233:         if (!defined(&hostname($lonhost))) {
  234:             undef($lonhost);
  235:         }
  236:     }
  237:     if (!defined($lonhost)) {
  238:         if (defined(&domain($dom,'primary'))) {
  239:             $lonhost=&domain($dom,'primary');
  240:             if ($lonhost eq 'no_host') {
  241:                 undef($lonhost);
  242:             }
  243:         }
  244:     }
  245:     if (defined($lonhost)) {
  246:         my $cachetime = 12*3600;
  247:         if (!$ignore_cache) {
  248:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
  249:             if (defined($cached)) {
  250:                 return $loncaparev;
  251:             }
  252:         }
  253:         my ($answer,$loncaparev);
  254:         my @ids=&current_machine_ids();
  255:         if (grep(/^\Q$lonhost\E$/,@ids)) {
  256:             $answer = $perlvar{'lonVersion'};
  257:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  258:                 $loncaparev = $1;
  259:             }
  260:         } else {
  261:             $answer = &reply('serverloncaparev',$lonhost);
  262:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
  263:                 if ($caller eq 'loncron') {
  264:                     my $ua=new LWP::UserAgent;
  265:                     $ua->timeout(4);
  266:                     my $hostname = &hostname($lonhost);
  267:                     my $protocol = $protocol{$lonhost};
  268:                     $protocol = 'http' if ($protocol ne 'https');
  269:                     my $url = $protocol.'://'.$hostname.'/adm/about.html';
  270:                     my $request=new HTTP::Request('GET',$url);
  271:                     my $response=$ua->request($request);
  272:                     unless ($response->is_error()) {
  273:                         my $content = $response->content;
  274:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
  275:                             $loncaparev = $1;
  276:                         }
  277:                     }
  278:                 } else {
  279:                     $loncaparev = $loncaparevs{$lonhost};
  280:                 }
  281:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  282:                 $loncaparev = $1;
  283:             }
  284:         }
  285:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
  286:     }
  287: }
  288: 
  289: sub get_server_homeID {
  290:     my ($hostname,$ignore_cache,$caller) = @_;
  291:     unless ($ignore_cache) {
  292:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
  293:         if (defined($cached)) {
  294:             return $serverhomeID;
  295:         }
  296:     }
  297:     my $cachetime = 12*3600;
  298:     my $serverhomeID;
  299:     if ($caller eq 'loncron') { 
  300:         my @machine_ids = &machine_ids($hostname);
  301:         foreach my $id (@machine_ids) {
  302:             my $response = &reply('serverhomeID',$id);
  303:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
  304:                 $serverhomeID = $response;
  305:                 last;
  306:             }
  307:         }
  308:         if ($serverhomeID eq '') {
  309:             $serverhomeID = $machine_ids[-1];
  310:         }
  311:     } else {
  312:         $serverhomeID = $serverhomeIDs{$hostname};
  313:     }
  314:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
  315: }
  316: 
  317: sub get_remote_globals {
  318:     my ($lonhost,$whathash,$ignore_cache) = @_;
  319:     my ($result,%returnhash,%whatneeded);
  320:     if (ref($whathash) eq 'HASH') {
  321:         foreach my $what (sort(keys(%{$whathash}))) {
  322:             my $hashid = $lonhost.'-'.$what;
  323:             my ($response,$cached);
  324:             unless ($ignore_cache) {
  325:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
  326:             }
  327:             if (defined($cached)) {
  328:                 $returnhash{$what} = $response;
  329:             } else {
  330:                 $whatneeded{$what} = 1;
  331:             }
  332:         }
  333:         if (keys(%whatneeded) == 0) {
  334:             $result = 'ok';
  335:         } else {
  336:             my $requested = &freeze_escape(\%whatneeded);
  337:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
  338:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  339:                 ($rep eq 'unknown_cmd')) {
  340:                 $result = $rep;
  341:             } else {
  342:                 $result = 'ok';
  343:                 my @pairs=split(/\&/,$rep);
  344:                 foreach my $item (@pairs) {
  345:                     my ($key,$value)=split(/=/,$item,2);
  346:                     my $what = &unescape($key);
  347:                     my $hashid = $lonhost.'-'.$what;
  348:                     $returnhash{$what}=&thaw_unescape($value);
  349:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
  350:                 }
  351:             }
  352:         }
  353:     }
  354:     return ($result,\%returnhash);
  355: }
  356: 
  357: sub remote_devalidate_cache {
  358:     my ($lonhost,$cachekeys) = @_;
  359:     my $items;
  360:     return unless (ref($cachekeys) eq 'ARRAY');
  361:     my $cachestr = join('&',@{$cachekeys});
  362:     return &reply('devalidatecache:'.&escape($cachestr),$lonhost);
  363: }
  364: 
  365: # -------------------------------------------------- Non-critical communication
  366: sub subreply {
  367:     my ($cmd,$server)=@_;
  368:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  369:     #
  370:     #  With loncnew process trimming, there's a timing hole between lonc server
  371:     #  process exit and the master server picking up the listen on the AF_UNIX
  372:     #  socket.  In that time interval, a lock file will exist:
  373: 
  374:     my $lockfile=$peerfile.".lock";
  375:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  376: 	sleep(0.1);
  377:     }
  378:     # At this point, either a loncnew parent is listening or an old lonc
  379:     # or loncnew child is listening so we can connect or everything's dead.
  380:     #
  381:     #   We'll give the connection a few tries before abandoning it.  If
  382:     #   connection is not possible, we'll con_lost back to the client.
  383:     #   
  384:     my $client;
  385:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  386: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  387: 				      Type    => SOCK_STREAM,
  388: 				      Timeout => 10);
  389: 	if ($client) {
  390: 	    last;		# Connected!
  391: 	} else {
  392: 	    &create_connection(&hostname($server),$server);
  393: 	}
  394:         sleep(0.1);		# Try again later if failed connection.
  395:     }
  396:     my $answer;
  397:     if ($client) {
  398: 	print $client "sethost:$server:$cmd\n";
  399: 	$answer=<$client>;
  400: 	if (!$answer) { $answer="con_lost"; }
  401: 	chomp($answer);
  402:     } else {
  403: 	$answer = 'con_lost';	# Failed connection.
  404:     }
  405:     return $answer;
  406: }
  407: 
  408: sub reply {
  409:     my ($cmd,$server)=@_;
  410:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  411:     my $answer=subreply($cmd,$server);
  412:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  413:         my $logged = $cmd;
  414:         if ($cmd =~ /^encrypt:([^:]+):/) {
  415:             my $subcmd = $1;
  416:             if (($subcmd eq 'auth') || ($subcmd eq 'passwd') ||
  417:                 ($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
  418:                 ($subcmd eq 'putdom') || ($subcmd eq 'autoexportgrades')) {
  419:                 (undef,undef,my @rest) = split(/:/,$cmd);
  420:                 if (($subcmd eq 'auth') || ($subcmd eq 'putdom')) {
  421:                     splice(@rest,2,1,'Hidden');
  422:                 } elsif ($subcmd eq 'passwd') {
  423:                     splice(@rest,2,2,('Hidden','Hidden'));
  424:                 } elsif (($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
  425:                          ($subcmd eq 'autoexportgrades')) {
  426:                     splice(@rest,3,1,'Hidden');
  427:                 }
  428:                 $logged = join(':',('encrypt:'.$subcmd,@rest));
  429:             }
  430:         }
  431:         &logthis("<font color=\"blue\">WARNING:".
  432:                  " $logged to $server returned $answer</font>");
  433:     }
  434:     return $answer;
  435: }
  436: 
  437: # ----------------------------------------------------------- Send USR1 to lonc
  438: 
  439: sub reconlonc {
  440:     my ($lonid) = @_;
  441:     if ($lonid) {
  442:         my $hostname = &hostname($lonid);
  443: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  444: 	if ($hostname && -e $peerfile) {
  445: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  446: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  447: 					     Type    => SOCK_STREAM,
  448: 					     Timeout => 10);
  449: 	    if ($client) {
  450: 		print $client ("reset_retries\n");
  451: 		my $answer=<$client>;
  452: 		#reset just this one.
  453: 	    }
  454: 	}
  455: 	return;
  456:     }
  457: 
  458:     &logthis("Trying to reconnect lonc");
  459:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  460:     if (open(my $fh,"<",$loncfile)) {
  461: 	my $loncpid=<$fh>;
  462:         chomp($loncpid);
  463:         if (kill 0 => $loncpid) {
  464: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  465:             kill USR1 => $loncpid;
  466:             sleep 1;
  467:          } else {
  468: 	    &logthis(
  469:                "<font color=\"blue\">WARNING:".
  470:                " lonc at pid $loncpid not responding, giving up</font>");
  471:         }
  472:     } else {
  473: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  474:     }
  475: }
  476: 
  477: # ------------------------------------------------------ Critical communication
  478: 
  479: sub critical {
  480:     my ($cmd,$server)=@_;
  481:     unless (&hostname($server)) {
  482:         &logthis("<font color=\"blue\">WARNING:".
  483:                " Critical message to unknown server ($server)</font>");
  484:         return 'no_such_host';
  485:     }
  486:     my $answer=reply($cmd,$server);
  487:     if ($answer eq 'con_lost') {
  488: 	&reconlonc($server);
  489: 	my $answer=reply($cmd,$server);
  490:         if ($answer eq 'con_lost') {
  491:             my $now=time;
  492:             my $middlename=$cmd;
  493:             $middlename=substr($middlename,0,16);
  494:             $middlename=~s/\W//g;
  495:             my $dfilename=
  496:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  497:             $dumpcount++;
  498:             {
  499: 		my $dfh;
  500: 		if (open($dfh,">",$dfilename)) {
  501: 		    print $dfh "$cmd\n"; 
  502: 		    close($dfh);
  503: 		}
  504:             }
  505:             sleep 1;
  506:             my $wcmd='';
  507:             {
  508: 		my $dfh;
  509: 		if (open($dfh,"<",$dfilename)) {
  510: 		    $wcmd=<$dfh>; 
  511: 		    close($dfh);
  512: 		}
  513:             }
  514:             chomp($wcmd);
  515:             if ($wcmd eq $cmd) {
  516: 		&logthis("<font color=\"blue\">WARNING: ".
  517:                          "Connection buffer $dfilename: $cmd</font>");
  518:                 &logperm("D:$server:$cmd");
  519: 	        return 'con_delayed';
  520:             } else {
  521:                 &logthis("<font color=\"red\">CRITICAL:"
  522:                         ." Critical connection failed: $server $cmd</font>");
  523:                 &logperm("F:$server:$cmd");
  524:                 return 'con_failed';
  525:             }
  526:         }
  527:     }
  528:     return $answer;
  529: }
  530: 
  531: # ------------------------------------------- check if return value is an error
  532: 
  533: sub error {
  534:     my ($result) = @_;
  535:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  536: 	if ($2 == 2) { return undef; }
  537: 	return $1;
  538:     }
  539:     return undef;
  540: }
  541: 
  542: sub convert_and_load_session_env {
  543:     my ($lonidsdir,$handle)=@_;
  544:     my @profile;
  545:     {
  546: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  547: 	if (!$opened) {
  548: 	    return 0;
  549: 	}
  550: 	flock($idf,LOCK_SH);
  551: 	@profile=<$idf>;
  552: 	close($idf);
  553:     }
  554:     my %temp_env;
  555:     foreach my $line (@profile) {
  556: 	if ($line !~ m/=/) {
  557: 	    return 0;
  558: 	}
  559: 	chomp($line);
  560: 	my ($envname,$envvalue)=split(/=/,$line,2);
  561: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  562:     }
  563:     unlink("$lonidsdir/$handle.id");
  564:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  565: 	    0640)) {
  566: 	%disk_env = %temp_env;
  567: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  568: 	untie(%disk_env);
  569:     }
  570:     return 1;
  571: }
  572: 
  573: # ------------------------------------------- Transfer profile into environment
  574: my $env_loaded;
  575: sub transfer_profile_to_env {
  576:     my ($lonidsdir,$handle,$force_transfer) = @_;
  577:     if (!$force_transfer && $env_loaded) { return; } 
  578: 
  579:     if (!defined($lonidsdir)) {
  580: 	$lonidsdir = $perlvar{'lonIDsDir'};
  581:     }
  582:     if (!defined($handle)) {
  583:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  584:     }
  585: 
  586:     my $convert;
  587:     {
  588:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  589: 	if (!$opened) {
  590: 	    return;
  591: 	}
  592: 	flock($idf,LOCK_SH);
  593: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  594: 		&GDBM_READER(),0640)) {
  595: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  596: 	    untie(%disk_env);
  597: 	} else {
  598: 	    $convert = 1;
  599: 	}
  600:     }
  601:     if ($convert) {
  602: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  603: 	    &logthis("Failed to load session, or convert session.");
  604: 	}
  605:     }
  606: 
  607:     my %remove;
  608:     while ( my $envname = each(%env) ) {
  609:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  610:             if ($time < time-300) {
  611:                 $remove{$key}++;
  612:             }
  613:         }
  614:     }
  615: 
  616:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  617:     $env_loaded=1;
  618:     foreach my $expired_key (keys(%remove)) {
  619:         &delenv($expired_key);
  620:     }
  621: }
  622: 
  623: # ---------------------------------------------------- Check for valid session 
  624: sub check_for_valid_session {
  625:     my ($r,$name,$userhashref,$domref) = @_;
  626:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  627:     my ($lonidsdir,$linkname,$pubname,$secure,$lonid);
  628:     if ($name eq 'lonDAV') {
  629:         $lonidsdir=$r->dir_config('lonDAVsessDir');
  630:     } else {
  631:         $lonidsdir=$r->dir_config('lonIDsDir');
  632:         if ($name eq '') {
  633:             $name = 'lonID';
  634:         }
  635:     }
  636:     if ($name eq 'lonID') {
  637:         $secure = 'lonSID';
  638:         $linkname = 'lonLinkID';
  639:         $pubname = 'lonPubID';
  640:         if (exists($cookies{$secure})) {
  641:             $lonid=$cookies{$secure};
  642:         } elsif (exists($cookies{$name})) {
  643:             $lonid=$cookies{$name};
  644:         } elsif ((exists($cookies{$linkname})) && ($ENV{'SERVER_PORT'} != 443)) {
  645:             $lonid=$cookies{$linkname};
  646:         } elsif (exists($cookies{$pubname})) {
  647:             $lonid=$cookies{$pubname};
  648:         }
  649:     } else {
  650:         $lonid=$cookies{$name};
  651:     }
  652:     return undef if (!$lonid);
  653: 
  654:     my $handle=&LONCAPA::clean_handle($lonid->value);
  655:     if (-l "$lonidsdir/$handle.id") {
  656:         my $link = readlink("$lonidsdir/$handle.id");
  657:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
  658:             $handle = $1;
  659:         }
  660:     }
  661:     if (!-e "$lonidsdir/$handle.id") {
  662:         if ((ref($domref)) && ($name eq 'lonID') &&
  663:             ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
  664:             my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
  665:             if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
  666:                 $$domref = $possudom;
  667:             }
  668:         }
  669:         return undef;
  670:     }
  671: 
  672:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  673:     return undef if (!$opened);
  674: 
  675:     flock($idf,LOCK_SH);
  676:     my %disk_env;
  677:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  678: 	    &GDBM_READER(),0640)) {
  679: 	return undef;	
  680:     }
  681: 
  682:     if (!defined($disk_env{'user.name'})
  683: 	|| !defined($disk_env{'user.domain'})) {
  684:         untie(%disk_env);
  685: 	return undef;
  686:     }
  687: 
  688:     if (ref($userhashref) eq 'HASH') {
  689:         $userhashref->{'name'} = $disk_env{'user.name'};
  690:         $userhashref->{'domain'} = $disk_env{'user.domain'};
  691:     }
  692:     untie(%disk_env);
  693: 
  694:     return $handle;
  695: }
  696: 
  697: sub timed_flock {
  698:     my ($file,$lock_type) = @_;
  699:     my $failed=0;
  700:     eval {
  701: 	local $SIG{__DIE__}='DEFAULT';
  702: 	local $SIG{ALRM}=sub {
  703: 	    $failed=1;
  704: 	    die("failed lock");
  705: 	};
  706: 	alarm(13);
  707: 	flock($file,$lock_type);
  708: 	alarm(0);
  709:     };
  710:     if ($failed) {
  711: 	return undef;
  712:     } else {
  713: 	return 1;
  714:     }
  715: }
  716: 
  717: sub get_sessionfile_vars {
  718:     my ($handle,$lonidsdir,$storearr) = @_;
  719:     my %returnhash;
  720:     unless (ref($storearr) eq 'ARRAY') {
  721:         return %returnhash;
  722:     }
  723:     if (-l "$lonidsdir/$handle.id") {
  724:         my $link = readlink("$lonidsdir/$handle.id");
  725:         if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
  726:             $handle = $1;
  727:         }
  728:     }
  729:     if ((-e "$lonidsdir/$handle.id") &&
  730:         ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
  731:         my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
  732:         if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
  733:             if (open(my $idf,'+<',"$lonidsdir/$handle.id")) {
  734:                 flock($idf,LOCK_SH);
  735:                 if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  736:                         &GDBM_READER(),0640)) {
  737:                     foreach my $item (@{$storearr}) {
  738:                         $returnhash{$item} = $disk_env{$item};
  739:                     }
  740:                     untie(%disk_env);
  741:                 }
  742:             }
  743:         }
  744:     }
  745:     return %returnhash;
  746: }
  747: 
  748: # ---------------------------------------------------------- Append Environment
  749: 
  750: sub appenv {
  751:     my ($newenv,$roles) = @_;
  752:     if (ref($newenv) eq 'HASH') {
  753:         foreach my $key (keys(%{$newenv})) {
  754:             my $refused = 0;
  755: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  756:                 $refused = 1;
  757:                 if (ref($roles) eq 'ARRAY') {
  758:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
  759:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  760:                         $refused = 0;
  761:                     }
  762:                 }
  763:             }
  764:             if ($refused) {
  765:                 &logthis("<font color=\"blue\">WARNING: ".
  766:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  767:                          .'</font>');
  768: 	        delete($newenv->{$key});
  769:             } else {
  770:                 $env{$key}=$newenv->{$key};
  771:             }
  772:         }
  773:         my $lonids = $perlvar{'lonIDsDir'};
  774:         if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
  775:             my $opened = open(my $env_file,'+<',$env{'user.environment'});
  776:             if ($opened
  777: 	        && &timed_flock($env_file,LOCK_EX)
  778: 	        &&
  779: 	        tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  780: 	            (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  781: 	        while (my ($key,$value) = each(%{$newenv})) {
  782: 	            $disk_env{$key} = $value;
  783: 	        }
  784: 	        untie(%disk_env);
  785:             }
  786:         }
  787:     }
  788:     return 'ok';
  789: }
  790: # ----------------------------------------------------- Delete from Environment
  791: 
  792: sub delenv {
  793:     my ($delthis,$regexp,$roles) = @_;
  794:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
  795:         my $refused = 1;
  796:         if (ref($roles) eq 'ARRAY') {
  797:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
  798:             if (grep(/^\Q$role\E$/,@{$roles})) {
  799:                 $refused = 0;
  800:             }
  801:         }
  802:         if ($refused) {
  803:             &logthis("<font color=\"blue\">WARNING: ".
  804:                      "Attempt to delete from environment ".$delthis);
  805:             return 'error';
  806:         }
  807:     }
  808:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  809:     if ($opened
  810: 	&& &timed_flock($env_file,LOCK_EX)
  811: 	&&
  812: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  813: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  814: 	foreach my $key (keys(%disk_env)) {
  815: 	    if ($regexp) {
  816:                 if ($key=~/^$delthis/) {
  817:                     delete($env{$key});
  818:                     delete($disk_env{$key});
  819:                 } 
  820:             } else {
  821:                 if ($key=~/^\Q$delthis\E/) {
  822: 		    delete($env{$key});
  823: 		    delete($disk_env{$key});
  824: 	        }
  825:             }
  826: 	}
  827: 	untie(%disk_env);
  828:     }
  829:     return 'ok';
  830: }
  831: 
  832: sub get_env_multiple {
  833:     my ($name) = @_;
  834:     my @values;
  835:     if (defined($env{$name})) {
  836:         # exists is it an array
  837:         if (ref($env{$name})) {
  838:             @values=@{ $env{$name} };
  839:         } else {
  840:             $values[0]=$env{$name};
  841:         }
  842:     }
  843:     return(@values);
  844: }
  845: 
  846: # ------------------------------------------------------------------- Locking
  847: 
  848: sub set_lock {
  849:     my ($text)=@_;
  850:     $locknum++;
  851:     my $id=$$.'-'.$locknum;
  852:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  853:              'session.lock.'.$id => $text});
  854:     return $id;
  855: }
  856: 
  857: sub get_locks {
  858:     my $num=0;
  859:     my %texts=();
  860:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  861:        if ($lock=~/\w/) {
  862:           $num++;
  863:           $texts{$lock}=$env{'session.lock.'.$lock};
  864:        }
  865:    }
  866:    return ($num,%texts);
  867: }
  868: 
  869: sub remove_lock {
  870:     my ($id)=@_;
  871:     my $newlocks='';
  872:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  873:        if (($lock=~/\w/) && ($lock ne $id)) {
  874:           $newlocks.=','.$lock;
  875:        }
  876:     }
  877:     &appenv({'session.locks' => $newlocks});
  878:     &delenv('session.lock.'.$id);
  879: }
  880: 
  881: sub remove_all_locks {
  882:     my $activelocks=$env{'session.locks'};
  883:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  884:        if ($lock=~/\w/) {
  885:           &remove_lock($lock);
  886:        }
  887:     }
  888: }
  889: 
  890: 
  891: # ------------------------------------------ Find out current server userload
  892: sub userload {
  893:     my $numusers=0;
  894:     {
  895: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  896: 	my $filename;
  897: 	my $curtime=time;
  898: 	while ($filename=readdir(LONIDS)) {
  899: 	    next if ($filename eq '.' || $filename eq '..');
  900: 	    next if ($filename =~ /publicuser_\d+\.id/);
  901:             next if ($filename =~ /^[a-f0-9]+_linked\.id$/);
  902: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  903: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  904: 	}
  905: 	closedir(LONIDS);
  906:     }
  907:     my $userloadpercent=0;
  908:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  909:     if ($maxuserload) {
  910: 	$userloadpercent=100*$numusers/$maxuserload;
  911:     }
  912:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  913:     return $userloadpercent;
  914: }
  915: 
  916: # ------------------------------ Find server with least workload from spare.tab
  917: 
  918: sub spareserver {
  919:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
  920:     my $spare_server;
  921:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  922:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  923:                                                      :  $userloadpercent;
  924:     my ($uint_dom,$remotesessions);
  925:     if (($udom ne '') && (&domain($udom) ne '')) {
  926:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
  927:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
  928:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
  929:         $remotesessions = $udomdefaults{'remotesessions'};
  930:     }
  931:     my $spareshash = &this_host_spares($udom);
  932:     if (ref($spareshash) eq 'HASH') {
  933:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  934:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  935:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
  936:                                              $try_server));
  937: 	        ($spare_server, $lowest_load) =
  938: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
  939:             }
  940:         }
  941: 
  942:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
  943: 
  944:         if (!$found_server) {
  945:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
  946: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
  947:                     next unless (&spare_can_host($udom,$uint_dom,
  948:                                                  $remotesessions,$try_server));
  949: 	            ($spare_server, $lowest_load) =
  950: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
  951:                 }
  952: 	    }
  953:         }
  954:     }
  955: 
  956:     if (!$want_server_name) {
  957:         if (defined($spare_server)) {
  958:             my $hostname = &hostname($spare_server);
  959:             if (defined($hostname)) {
  960:                 my $protocol = 'http';
  961:                 if ($protocol{$spare_server} eq 'https') {
  962:                     $protocol = $protocol{$spare_server};
  963:                 }
  964: 	        $spare_server = $protocol.'://'.$hostname;
  965:             }
  966:         }
  967:     }
  968:     return $spare_server;
  969: }
  970: 
  971: sub compare_server_load {
  972:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
  973: 
  974:     if ($required) {
  975:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
  976:         my $remoterev = &get_server_loncaparev(undef,$try_server);
  977:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
  978:         if (($major eq '' && $minor eq '') ||
  979:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
  980:             return ($spare_server,$lowest_load);
  981:         }
  982:     }
  983: 
  984:     my $loadans     = &reply('load',    $try_server);
  985:     my $userloadans = &reply('userload',$try_server);
  986: 
  987:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  988: 	return ($spare_server, $lowest_load); #didn't get a number from the server
  989:     }
  990: 
  991:     my $load;
  992:     if ($loadans =~ /\d/) {
  993: 	if ($userloadans =~ /\d/) {
  994: 	    #both are numbers, pick the bigger one
  995: 	    $load = ($loadans > $userloadans) ? $loadans 
  996: 		                              : $userloadans;
  997: 	} else {
  998: 	    $load = $loadans;
  999: 	}
 1000:     } else {
 1001: 	$load = $userloadans;
 1002:     }
 1003: 
 1004:     if (($load =~ /\d/) && ($load < $lowest_load)) {
 1005: 	$spare_server = $try_server;
 1006: 	$lowest_load  = $load;
 1007:     }
 1008:     return ($spare_server,$lowest_load);
 1009: }
 1010: 
 1011: # --------------------------- ask offload servers if user already has a session
 1012: sub find_existing_session {
 1013:     my ($udom,$uname) = @_;
 1014:     my $spareshash = &this_host_spares($udom);
 1015:     if (ref($spareshash) eq 'HASH') {
 1016:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
 1017:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
 1018:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
 1019:             }
 1020:         }
 1021:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
 1022:             foreach my $try_server (@{ $spareshash->{'default'} }) {
 1023:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
 1024:             }
 1025:         }
 1026:     }
 1027:     return;
 1028: }
 1029: 
 1030: # check if user's browser sent load balancer cookie and server still has session
 1031: # and is not overloaded.
 1032: sub check_for_balancer_cookie {
 1033:     my ($r,$update_mtime) = @_;
 1034:     my ($otherserver,$cookie);
 1035:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
 1036:     if (exists($cookies{'balanceID'})) {
 1037:         my $balid = $cookies{'balanceID'};
 1038:         $cookie=&LONCAPA::clean_handle($balid->value);
 1039:         my $balancedir=$r->dir_config('lonBalanceDir');
 1040:         if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
 1041:             if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
 1042:                 my ($possudom,$possuname) = ($1,$2);
 1043:                 my $has_session = 0;
 1044:                 if ((&domain($possudom) ne '') &&
 1045:                     (&homeserver($possuname,$possudom) ne 'no_host')) {
 1046:                     my $try_server;
 1047:                     my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
 1048:                     if ($opened) {
 1049:                         flock($idf,LOCK_SH);
 1050:                         while (my $line = <$idf>) {
 1051:                             chomp($line);
 1052:                             if (&hostname($line) ne '') {
 1053:                                 $try_server = $line;
 1054:                                 last;
 1055:                             }
 1056:                         }
 1057:                         close($idf);
 1058:                         if (($try_server) &&
 1059:                             (&has_user_session($try_server,$possudom,$possuname))) {
 1060:                             my $lowest_load = 30000;
 1061:                             ($otherserver,$lowest_load) =
 1062:                                 &compare_server_load($try_server,undef,$lowest_load);
 1063:                             if ($otherserver ne '' && $lowest_load < 100) {
 1064:                                 $has_session = 1;
 1065:                             } else {
 1066:                                 undef($otherserver);
 1067:                             }
 1068:                         }
 1069:                     }
 1070:                 }
 1071:                 if ($has_session) {
 1072:                     if ($update_mtime) {
 1073:                         my $atime = my $mtime = time;
 1074:                         utime($atime,$mtime,"$balancedir/$cookie.id");
 1075:                     }
 1076:                 } else {
 1077:                     unlink("$balancedir/$cookie.id");
 1078:                 }
 1079:             }
 1080:         }
 1081:     }
 1082:     return ($otherserver,$cookie);
 1083: }
 1084: 
 1085: sub delbalcookie {
 1086:     my ($cookie,$balancer) =@_;
 1087:     if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
 1088:         my ($udom,$uname) = ($1,$2);
 1089:         my $uprimary_id = &domain($udom,'primary');
 1090:         my $uintdom = &internet_dom($uprimary_id);
 1091:         my $intdom = &internet_dom($balancer);
 1092:         my $serverhomedom = &host_domain($balancer);
 1093:         if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1094:             return &reply("delbalcookie:$cookie",$balancer);
 1095:         }
 1096:     }
 1097: }
 1098: 
 1099: # -------------------------------- ask if server already has a session for user
 1100: sub has_user_session {
 1101:     my ($lonid,$udom,$uname) = @_;
 1102:     my $result = &reply(join(':','userhassession',
 1103: 			     map {&escape($_)} ($udom,$uname)),$lonid);
 1104:     return 1 if ($result eq 'ok');
 1105: 
 1106:     return 0;
 1107: }
 1108: 
 1109: # --------- determine least loaded server in a user's domain which allows login
 1110: 
 1111: sub choose_server {
 1112:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
 1113:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
 1114:     my %servers = &get_servers($udom);
 1115:     my $lowest_load = 30000;
 1116:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
 1117:     if ($skiploadbal) {
 1118:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
 1119:         unless (defined($cached)) {
 1120:             my $cachetime = 60*60*24;
 1121:             my %domconfig =
 1122:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1123:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1124:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
 1125:                                            $cachetime);
 1126:             }
 1127:         }
 1128:     }
 1129:     foreach my $lonhost (keys(%servers)) {
 1130:         my $loginvia;
 1131:         if ($skiploadbal) {
 1132:             if (ref($balancers) eq 'HASH') {
 1133:                 next if (exists($balancers->{$lonhost}));
 1134:             }
 1135:         }
 1136:         if ($checkloginvia) {
 1137:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
 1138:             if ($loginvia) {
 1139:                 my ($server,$path) = split(/:/,$loginvia);
 1140:                 ($login_host, $lowest_load) =
 1141:                     &compare_server_load($server, $login_host, $lowest_load, $required);
 1142:                 if ($login_host eq $server) {
 1143:                     $portal_path = $path;
 1144:                     $isredirect = 1;
 1145:                 }
 1146:             } else {
 1147:                 ($login_host, $lowest_load) =
 1148:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1149:                 if ($login_host eq $lonhost) {
 1150:                     $portal_path = '';
 1151:                     $isredirect = ''; 
 1152:                 }
 1153:             }
 1154:         } else {
 1155:             ($login_host, $lowest_load) =
 1156:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1157:         }
 1158:     }
 1159:     if ($login_host ne '') {
 1160:         $hostname = &hostname($login_host);
 1161:     }
 1162:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
 1163: }
 1164: 
 1165: sub get_course_sessions {
 1166:     my ($cnum,$cdom,$lastactivity) = @_;
 1167:     my %servers = &internet_dom_servers($cdom);
 1168:     my %returnhash;
 1169:     foreach my $server (sort(keys(%servers))) {
 1170:         my $rep = &reply("coursesessions:$cdom:$cnum:$lastactivity",$server);
 1171:         my @pairs=split(/\&/,$rep);
 1172:         unless (($rep eq 'unknown_cmd') || ($rep =~ /^error/)) {
 1173:             foreach my $item (@pairs) {
 1174:                 my ($key,$value)=split(/=/,$item,2);
 1175:                 $key = &unescape($key);
 1176:                 next if ($key =~ /^error: 2 /);
 1177:                 if (exists($returnhash{$key})) {
 1178:                     next if ($value < $returnhash{$key});
 1179:                 }
 1180:                 $returnhash{$key}=$value;
 1181:             }
 1182:         }
 1183:     }
 1184:     return %returnhash;
 1185: }
 1186: 
 1187: # --------------------------------------------- Try to change a user's password
 1188: 
 1189: sub changepass {
 1190:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
 1191:     $currentpass = &escape($currentpass);
 1192:     $newpass     = &escape($newpass);
 1193:     my $lonhost = $perlvar{'lonHostID'};
 1194:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
 1195: 		       $server);
 1196:     if (! $answer) {
 1197: 	&logthis("No reply on password change request to $server ".
 1198: 		 "by $uname in domain $udom.");
 1199:     } elsif ($answer =~ "^ok") {
 1200:         &logthis("$uname in $udom successfully changed their password ".
 1201: 		 "on $server.");
 1202:     } elsif ($answer =~ "^pwchange_failure") {
 1203: 	&logthis("$uname in $udom was unable to change their password ".
 1204: 		 "on $server.  The action was blocked by either lcpasswd ".
 1205: 		 "or pwchange");
 1206:     } elsif ($answer =~ "^non_authorized") {
 1207:         &logthis("$uname in $udom did not get their password correct when ".
 1208: 		 "attempting to change it on $server.");
 1209:     } elsif ($answer =~ "^auth_mode_error") {
 1210:         &logthis("$uname in $udom attempted to change their password despite ".
 1211: 		 "not being locally or internally authenticated on $server.");
 1212:     } elsif ($answer =~ "^unknown_user") {
 1213:         &logthis("$uname in $udom attempted to change their password ".
 1214: 		 "on $server but were unable to because $server is not ".
 1215: 		 "their home server.");
 1216:     } elsif ($answer =~ "^refused") {
 1217: 	&logthis("$server refused to change $uname in $udom password because ".
 1218: 		 "it was sent an unencrypted request to change the password.");
 1219:     } elsif ($answer =~ "invalid_client") {
 1220:         &logthis("$server refused to change $uname in $udom password because ".
 1221:                  "it was a reset by e-mail originating from an invalid server.");
 1222:     } elsif ($answer =~ "^prioruse") {
 1223:        &logthis("$server refused to change $uname in $udom password because ".
 1224:                 "the password had been used before");
 1225:     }
 1226:     return $answer;
 1227: }
 1228: 
 1229: # ----------------------- Try to determine user's current authentication scheme
 1230: 
 1231: sub queryauthenticate {
 1232:     my ($uname,$udom)=@_;
 1233:     my $uhome=&homeserver($uname,$udom);
 1234:     if (!$uhome) {
 1235: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
 1236: 	return 'no_host';
 1237:     }
 1238:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
 1239:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
 1240: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1241:     }
 1242:     return $answer;
 1243: }
 1244: 
 1245: # --------- Try to authenticate user from domain's lib servers (first this one)
 1246: 
 1247: sub authenticate {
 1248:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
 1249:     $upass=&escape($upass);
 1250:     $uname= &LONCAPA::clean_username($uname);
 1251:     my $uhome=&homeserver($uname,$udom,1);
 1252:     my $newhome;
 1253:     if ((!$uhome) || ($uhome eq 'no_host')) {
 1254: # Maybe the machine was offline and only re-appeared again recently?
 1255:         &reconlonc();
 1256: # One more
 1257: 	$uhome=&homeserver($uname,$udom,1);
 1258:         if (($uhome eq 'no_host') && $checkdefauth) {
 1259:             if (defined(&domain($udom,'primary'))) {
 1260:                 $newhome=&domain($udom,'primary');
 1261:             }
 1262:             if ($newhome ne '') {
 1263:                 $uhome = $newhome;
 1264:             }
 1265:         }
 1266: 	if ((!$uhome) || ($uhome eq 'no_host')) {
 1267: 	    &logthis("User $uname at $udom is unknown in authenticate");
 1268: 	    return 'no_host';
 1269:         }
 1270:     }
 1271:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
 1272:     if ($answer eq 'authorized') {
 1273:         if ($newhome) {
 1274:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
 1275:             return 'no_account_on_host'; 
 1276:         } else {
 1277:             &logthis("User $uname at $udom authorized by $uhome");
 1278:             return $uhome;
 1279:         }
 1280:     }
 1281:     if ($answer eq 'non_authorized') {
 1282: 	&logthis("User $uname at $udom rejected by $uhome");
 1283: 	return 'no_host'; 
 1284:     }
 1285:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1286:     return 'no_host';
 1287: }
 1288: 
 1289: sub can_host_session {
 1290:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
 1291:     my $canhost = 1;
 1292:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
 1293:     if (ref($remotesessions) eq 'HASH') {
 1294:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
 1295:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
 1296:                 $canhost = 0;
 1297:             } else {
 1298:                 $canhost = 1;
 1299:             }
 1300:         }
 1301:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
 1302:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
 1303:                 $canhost = 1;
 1304:             } else {
 1305:                 $canhost = 0;
 1306:             }
 1307:         }
 1308:         if ($canhost) {
 1309:             if ($remotesessions->{'version'} ne '') {
 1310:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
 1311:                 if ($reqmajor ne '' && $reqminor ne '') {
 1312:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
 1313:                         my $major = $1;
 1314:                         my $minor = $2;
 1315:                         if (($major < $reqmajor ) ||
 1316:                             (($major == $reqmajor) && ($minor < $reqminor))) {
 1317:                             $canhost = 0;
 1318:                         }
 1319:                     } else {
 1320:                         $canhost = 0;
 1321:                     }
 1322:                 }
 1323:             }
 1324:         }
 1325:     }
 1326:     if ($canhost) {
 1327:         if (ref($hostedsessions) eq 'HASH') {
 1328:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1329:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 1330:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
 1331:                 if (($uint_dom ne '') && 
 1332:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
 1333:                     $canhost = 0;
 1334:                 } else {
 1335:                     $canhost = 1;
 1336:                 }
 1337:             }
 1338:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
 1339:                 if (($uint_dom ne '') && 
 1340:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
 1341:                     $canhost = 1;
 1342:                 } else {
 1343:                     $canhost = 0;
 1344:                 }
 1345:             }
 1346:         }
 1347:     }
 1348:     return $canhost;
 1349: }
 1350: 
 1351: sub spare_can_host {
 1352:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
 1353:     my $canhost=1;
 1354:     my $try_server_hostname = &hostname($try_server);
 1355:     my $serverhomeID = &get_server_homeID($try_server_hostname);
 1356:     my $serverhomedom = &host_domain($serverhomeID);
 1357:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
 1358:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
 1359:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
 1360:             $canhost = 0;
 1361:         }
 1362:     }
 1363:     if (($canhost) && ($uint_dom)) {
 1364:         my @intdoms;
 1365:         my $internet_names = &get_internet_names($try_server);
 1366:         if (ref($internet_names) eq 'ARRAY') {
 1367:             @intdoms = @{$internet_names};
 1368:         }
 1369:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1370:             my $remoterev = &get_server_loncaparev(undef,$try_server);
 1371:             $canhost = &can_host_session($udom,$try_server,$remoterev,
 1372:                                          $remotesessions,
 1373:                                          $defdomdefaults{'hostedsessions'});
 1374:         }
 1375:     }
 1376:     return $canhost;
 1377: }
 1378: 
 1379: sub this_host_spares {
 1380:     my ($dom) = @_;
 1381:     my ($dom_in_use,$lonhost_in_use,$result);
 1382:     my @hosts = &current_machine_ids();
 1383:     foreach my $lonhost (@hosts) {
 1384:         if (&host_domain($lonhost) eq $dom) {
 1385:             $dom_in_use = $dom;
 1386:             $lonhost_in_use = $lonhost;
 1387:             last;
 1388:         }
 1389:     }
 1390:     if ($dom_in_use ne '') {
 1391:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1392:     }
 1393:     if (ref($result) ne 'HASH') {
 1394:         $lonhost_in_use = $perlvar{'lonHostID'};
 1395:         $dom_in_use = &host_domain($lonhost_in_use);
 1396:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1397:         if (ref($result) ne 'HASH') {
 1398:             $result = \%spareid;
 1399:         }
 1400:     }
 1401:     return $result;
 1402: }
 1403: 
 1404: sub spares_for_offload  {
 1405:     my ($dom_in_use,$lonhost_in_use) = @_;
 1406:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
 1407:     if (defined($cached)) {
 1408:         return $result;
 1409:     } else {
 1410:         my $cachetime = 60*60*24;
 1411:         my %domconfig =
 1412:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
 1413:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1414:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
 1415:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
 1416:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
 1417:                 }
 1418:             }
 1419:         }
 1420:     }
 1421:     return;
 1422: }
 1423: 
 1424: sub get_lonbalancer_config {
 1425:     my ($servers) = @_;
 1426:     my ($currbalancer,$currtargets);
 1427:     if (ref($servers) eq 'HASH') {
 1428:         foreach my $server (keys(%{$servers})) {
 1429:             my %what = (
 1430:                          spareid => 1,
 1431:                          perlvar => 1,
 1432:                        );
 1433:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
 1434:             if ($result eq 'ok') {
 1435:                 if (ref($returnhash) eq 'HASH') {
 1436:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
 1437:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
 1438:                             $currbalancer = $server;
 1439:                             $currtargets = {};
 1440:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
 1441:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
 1442:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
 1443:                                 }
 1444:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
 1445:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
 1446:                                 }
 1447:                             }
 1448:                             last;
 1449:                         }
 1450:                     }
 1451:                 }
 1452:             }
 1453:         }
 1454:     }
 1455:     return ($currbalancer,$currtargets);
 1456: }
 1457: 
 1458: sub check_loadbalancing {
 1459:     my ($uname,$udom,$caller) = @_;
 1460:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
 1461:         $rule_in_effect,$offloadto,$otherserver,$setcookie);
 1462:     my $lonhost = $perlvar{'lonHostID'};
 1463:     my @hosts = &current_machine_ids();
 1464:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1465:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
 1466:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
 1467:     my $serverhomedom = &host_domain($lonhost);
 1468:     my $domneedscache; 
 1469:     my $cachetime = 60*60*24;
 1470: 
 1471:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1472:         $dom_in_use = $udom;
 1473:         $homeintdom = 1;
 1474:     } else {
 1475:         $dom_in_use = $serverhomedom;
 1476:     }
 1477:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
 1478:     unless (defined($cached)) {
 1479:         my %domconfig =
 1480:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
 1481:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1482:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1483:         } else {
 1484:             $domneedscache = $dom_in_use;
 1485:         }
 1486:     }
 1487:     if (ref($result) eq 'HASH') {
 1488:         ($is_balancer,$currtargets,$currrules,$setcookie) =
 1489:             &check_balancer_result($result,@hosts);
 1490:         if ($is_balancer) {
 1491:             if (ref($currrules) eq 'HASH') {
 1492:                 if ($homeintdom) {
 1493:                     if ($uname ne '') {
 1494:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
 1495:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
 1496:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
 1497:                                 $rule_in_effect = $currrules->{'_LC_author'};
 1498:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
 1499:                                 $rule_in_effect = $currrules->{'_LC_adv'}
 1500:                             }
 1501:                         }
 1502:                         if ($rule_in_effect eq '') {
 1503:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
 1504:                             if ($userenv{'inststatus'} ne '') {
 1505:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
 1506:                                 my ($othertitle,$usertypes,$types) =
 1507:                                     &Apache::loncommon::sorted_inst_types($udom);
 1508:                                 if (ref($types) eq 'ARRAY') {
 1509:                                     foreach my $type (@{$types}) {
 1510:                                         if (grep(/^\Q$type\E$/,@statuses)) {
 1511:                                             if (exists($currrules->{$type})) {
 1512:                                                 $rule_in_effect = $currrules->{$type};
 1513:                                             }
 1514:                                         }
 1515:                                     }
 1516:                                 }
 1517:                             } else {
 1518:                                 if (exists($currrules->{'default'})) {
 1519:                                     $rule_in_effect = $currrules->{'default'};
 1520:                                 }
 1521:                             }
 1522:                         }
 1523:                     } else {
 1524:                         if (exists($currrules->{'default'})) {
 1525:                             $rule_in_effect = $currrules->{'default'};
 1526:                         }
 1527:                     }
 1528:                 } else {
 1529:                     if ($currrules->{'_LC_external'} ne '') {
 1530:                         $rule_in_effect = $currrules->{'_LC_external'};
 1531:                     }
 1532:                 }
 1533:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1534:                                                        $uname,$udom);
 1535:             }
 1536:         }
 1537:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
 1538:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
 1539:         unless (defined($cached)) {
 1540:             my %domconfig =
 1541:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
 1542:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1543:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
 1544:             } else {
 1545:                 $domneedscache = $serverhomedom;
 1546:             }
 1547:         }
 1548:         if (ref($result) eq 'HASH') {
 1549:             ($is_balancer,$currtargets,$currrules,$setcookie) =
 1550:                 &check_balancer_result($result,@hosts);
 1551:             if ($is_balancer) {
 1552:                 if (ref($currrules) eq 'HASH') {
 1553:                     if ($currrules->{'_LC_internetdom'} ne '') {
 1554:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
 1555:                     }
 1556:                 }
 1557:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1558:                                                        $uname,$udom);
 1559:             }
 1560:         } else {
 1561:             if ($perlvar{'lonBalancer'} eq 'yes') {
 1562:                 $is_balancer = 1;
 1563:                 $offloadto = &this_host_spares($dom_in_use);
 1564:             }
 1565:             unless (defined($cached)) {
 1566:                 $domneedscache = $serverhomedom;
 1567:             }
 1568:         }
 1569:     } else {
 1570:         if ($perlvar{'lonBalancer'} eq 'yes') {
 1571:             $is_balancer = 1;
 1572:             $offloadto = &this_host_spares($dom_in_use);
 1573:         }
 1574:         unless (defined($cached)) {
 1575:             $domneedscache = $serverhomedom;
 1576:         }
 1577:     }
 1578:     if ($domneedscache) {
 1579:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
 1580:     }
 1581:     if ($is_balancer) {
 1582:         my $lowest_load = 30000;
 1583:         if (ref($offloadto) eq 'HASH') {
 1584:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
 1585:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
 1586:                     ($otherserver,$lowest_load) =
 1587:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1588:                 }
 1589:             }
 1590:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
 1591: 
 1592:             if (!$found_server) {
 1593:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
 1594:                     foreach my $try_server (@{$offloadto->{'default'}}) {
 1595:                         ($otherserver,$lowest_load) =
 1596:                             &compare_server_load($try_server,$otherserver,$lowest_load);
 1597:                     }
 1598:                 }
 1599:             }
 1600:         } elsif (ref($offloadto) eq 'ARRAY') {
 1601:             if (@{$offloadto} == 1) {
 1602:                 $otherserver = $offloadto->[0];
 1603:             } elsif (@{$offloadto} > 1) {
 1604:                 foreach my $try_server (@{$offloadto}) {
 1605:                     ($otherserver,$lowest_load) =
 1606:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1607:                 }
 1608:             }
 1609:         }
 1610:         unless ($caller eq 'login') {
 1611:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
 1612:                 $is_balancer = 0;
 1613:                 if ($uname ne '' && $udom ne '') {
 1614:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
 1615:                         &appenv({'user.loadbalexempt'     => $lonhost,
 1616:                                  'user.loadbalcheck.time' => time});
 1617:                     }
 1618:                 }
 1619:             }
 1620:         }
 1621:         unless ($homeintdom) {
 1622:             undef($setcookie);
 1623:         }
 1624:     }
 1625:     return ($is_balancer,$otherserver,$setcookie);
 1626: }
 1627: 
 1628: sub check_balancer_result {
 1629:     my ($result,@hosts) = @_;
 1630:     my ($is_balancer,$currtargets,$currrules,$setcookie);
 1631:     if (ref($result) eq 'HASH') {
 1632:         if ($result->{'lonhost'} ne '') {
 1633:             my $currbalancer = $result->{'lonhost'};
 1634:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
 1635:                 $is_balancer = 1;
 1636:                 $currtargets = $result->{'targets'};
 1637:                 $currrules = $result->{'rules'};
 1638:             }
 1639:         } else {
 1640:             foreach my $key (keys(%{$result})) {
 1641:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
 1642:                     (ref($result->{$key}) eq 'HASH')) {
 1643:                     $is_balancer = 1;
 1644:                     $currrules = $result->{$key}{'rules'};
 1645:                     $currtargets = $result->{$key}{'targets'};
 1646:                     $setcookie = $result->{$key}{'cookie'};
 1647:                     last;
 1648:                 }
 1649:             }
 1650:         }
 1651:     }
 1652:     return ($is_balancer,$currtargets,$currrules,$setcookie);
 1653: }
 1654: 
 1655: sub get_loadbalancer_targets {
 1656:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
 1657:     my $offloadto;
 1658:     if ($rule_in_effect eq 'none') {
 1659:         return [$perlvar{'lonHostID'}];
 1660:     } elsif ($rule_in_effect eq '') {
 1661:         $offloadto = $currtargets;
 1662:     } else {
 1663:         if ($rule_in_effect eq 'homeserver') {
 1664:             my $homeserver = &homeserver($uname,$udom);
 1665:             if ($homeserver ne 'no_host') {
 1666:                 $offloadto = [$homeserver];
 1667:             }
 1668:         } elsif ($rule_in_effect eq 'externalbalancer') {
 1669:             my %domconfig =
 1670:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1671:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1672:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
 1673:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
 1674:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
 1675:                     }
 1676:                 }
 1677:             } else {
 1678:                 my %servers = &internet_dom_servers($udom);
 1679:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
 1680:                 if (&hostname($remotebalancer) ne '') {
 1681:                     $offloadto = [$remotebalancer];
 1682:                 }
 1683:             }
 1684:         } elsif (&hostname($rule_in_effect) ne '') {
 1685:             $offloadto = [$rule_in_effect];
 1686:         }
 1687:     }
 1688:     return $offloadto;
 1689: }
 1690: 
 1691: sub internet_dom_servers {
 1692:     my ($dom) = @_;
 1693:     my (%uniqservers,%servers);
 1694:     my $primaryserver = &hostname(&domain($dom,'primary'));
 1695:     my @machinedoms = &machine_domains($primaryserver);
 1696:     foreach my $mdom (@machinedoms) {
 1697:         my %currservers = %servers;
 1698:         my %server = &get_servers($mdom);
 1699:         %servers = (%currservers,%server);
 1700:     }
 1701:     my %by_hostname;
 1702:     foreach my $id (keys(%servers)) {
 1703:         push(@{$by_hostname{$servers{$id}}},$id);
 1704:     }
 1705:     foreach my $hostname (sort(keys(%by_hostname))) {
 1706:         if (@{$by_hostname{$hostname}} > 1) {
 1707:             my $match = 0;
 1708:             foreach my $id (@{$by_hostname{$hostname}}) {
 1709:                 if (&host_domain($id) eq $dom) {
 1710:                     $uniqservers{$id} = $hostname;
 1711:                     $match = 1;
 1712:                 }
 1713:             }
 1714:             unless ($match) {
 1715:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1716:             }
 1717:         } else {
 1718:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1719:         }
 1720:     }
 1721:     return %uniqservers;
 1722: }
 1723: 
 1724: # ---------------------- Find the homebase for a user from domain's lib servers
 1725: 
 1726: my %homecache;
 1727: sub homeserver {
 1728:     my ($uname,$udom,$ignoreBadCache)=@_;
 1729:     my $index="$uname:$udom";
 1730: 
 1731:     if (exists($homecache{$index})) { return $homecache{$index}; }
 1732: 
 1733:     my %servers = &get_servers($udom,'library');
 1734:     foreach my $tryserver (keys(%servers)) {
 1735:         next if ($ignoreBadCache ne 'true' && 
 1736: 		 exists($badServerCache{$tryserver}));
 1737: 
 1738: 	my $answer=reply("home:$udom:$uname",$tryserver);
 1739: 	if ($answer eq 'found') {
 1740: 	    delete($badServerCache{$tryserver}); 
 1741: 	    return $homecache{$index}=$tryserver;
 1742: 	} elsif ($answer eq 'no_host') {
 1743: 	    $badServerCache{$tryserver}=1;
 1744: 	}
 1745:     }    
 1746:     return 'no_host';
 1747: }
 1748: 
 1749: # ------------------------------------- Find the usernames behind a list of IDs
 1750: 
 1751: sub idget {
 1752:     my ($udom,@ids)=@_;
 1753:     my %returnhash=();
 1754:     
 1755:     my %servers = &get_servers($udom,'library');
 1756:     foreach my $tryserver (keys(%servers)) {
 1757: 	my $idlist=join('&', map { &escape($_); } @ids);
 1758: 	$idlist=~tr/A-Z/a-z/; 
 1759: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
 1760: 	my @answer=();
 1761: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
 1762: 	    @answer=split(/\&/,$reply);
 1763: 	}                    ;
 1764: 	my $i;
 1765: 	for ($i=0;$i<=$#ids;$i++) {
 1766: 	    if ($answer[$i]) {
 1767: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
 1768: 	    } 
 1769: 	}
 1770:     } 
 1771:     return %returnhash;
 1772: }
 1773: 
 1774: # ------------------------------------- Find the IDs behind a list of usernames
 1775: 
 1776: sub idrget {
 1777:     my ($udom,@unames)=@_;
 1778:     my %returnhash=();
 1779:     foreach my $uname (@unames) {
 1780:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
 1781:     }
 1782:     return %returnhash;
 1783: }
 1784: 
 1785: # ------------------------------- Store away a list of names and associated IDs
 1786: 
 1787: sub idput {
 1788:     my ($udom,%ids)=@_;
 1789:     my %servers=();
 1790:     foreach my $uname (keys(%ids)) {
 1791: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
 1792:         my $uhom=&homeserver($uname,$udom);
 1793:         if ($uhom ne 'no_host') {
 1794:             my $id=&escape($ids{$uname});
 1795:             $id=~tr/A-Z/a-z/;
 1796:             my $esc_unam=&escape($uname);
 1797: 	    if ($servers{$uhom}) {
 1798: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
 1799:             } else {
 1800:                 $servers{$uhom}=$id.'='.$esc_unam;
 1801:             }
 1802:         }
 1803:     }
 1804:     foreach my $server (keys(%servers)) {
 1805:         &critical('idput:'.$udom.':'.$servers{$server},$server);
 1806:     }
 1807: }
 1808: 
 1809: # ---------------------------------------- Delete unwanted IDs from ids.db file
 1810: 
 1811: sub iddel {
 1812:     my ($udom,$idshashref,$uhome)=@_;
 1813:     my %result=();
 1814:     unless (ref($idshashref) eq 'HASH') {
 1815:         return %result;
 1816:     }
 1817:     my %servers=();
 1818:     while (my ($id,$uname) = each(%{$idshashref})) {
 1819:         my $uhom;
 1820:         if ($uhome) {
 1821:             $uhom = $uhome;
 1822:         } else {
 1823:             $uhom=&homeserver($uname,$udom);
 1824:         }
 1825:         if ($uhom ne 'no_host') {
 1826:             if ($servers{$uhom}) {
 1827:                 $servers{$uhom}.='&'.&escape($id);
 1828:             } else {
 1829:                 $servers{$uhom}=&escape($id);
 1830:             }
 1831:         }
 1832:     }
 1833:     foreach my $server (keys(%servers)) {
 1834:         $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
 1835:     }
 1836:     return %result;
 1837: }
 1838: 
 1839: # ------------------------------dump from db file owned by domainconfig user
 1840: sub dump_dom {
 1841:     my ($namespace, $udom, $regexp) = @_;
 1842: 
 1843:     $udom ||= $env{'user.domain'};
 1844: 
 1845:     return () unless $udom;
 1846: 
 1847:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
 1848: }
 1849: 
 1850: # ------------------------------------------ get items from domain db files   
 1851: 
 1852: sub get_dom {
 1853:     my ($namespace,$storearr,$udom,$uhome)=@_;
 1854:     return if ($udom eq 'public');
 1855:     my $items='';
 1856:     foreach my $item (@$storearr) {
 1857:         $items.=&escape($item).'&';
 1858:     }
 1859:     $items=~s/\&$//;
 1860:     if (!$udom) {
 1861:         $udom=$env{'user.domain'};
 1862:         return if ($udom eq 'public');
 1863:         if (defined(&domain($udom,'primary'))) {
 1864:             $uhome=&domain($udom,'primary');
 1865:         } else {
 1866:             undef($uhome);
 1867:         }
 1868:     } else {
 1869:         if (!$uhome) {
 1870:             if (defined(&domain($udom,'primary'))) {
 1871:                 $uhome=&domain($udom,'primary');
 1872:             }
 1873:         }
 1874:     }
 1875:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1876:         my $rep;
 1877:         if ($namespace =~ /^enc/) {
 1878:             $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
 1879:         } else {
 1880:             $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 1881:         }
 1882:         my %returnhash;
 1883:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 1884:             return %returnhash;
 1885:         }
 1886:         my @pairs=split(/\&/,$rep);
 1887:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 1888:             return @pairs;
 1889:         }
 1890:         my $i=0;
 1891:         foreach my $item (@$storearr) {
 1892:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 1893:             $i++;
 1894:         }
 1895:         return %returnhash;
 1896:     } else {
 1897:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 1898:     }
 1899: }
 1900: 
 1901: # -------------------------------------------- put items in domain db files 
 1902: 
 1903: sub put_dom {
 1904:     my ($namespace,$storehash,$udom,$uhome)=@_;
 1905:     if (!$udom) {
 1906:         $udom=$env{'user.domain'};
 1907:         if (defined(&domain($udom,'primary'))) {
 1908:             $uhome=&domain($udom,'primary');
 1909:         } else {
 1910:             undef($uhome);
 1911:         }
 1912:     } else {
 1913:         if (!$uhome) {
 1914:             if (defined(&domain($udom,'primary'))) {
 1915:                 $uhome=&domain($udom,'primary');
 1916:             }
 1917:         }
 1918:     } 
 1919:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1920:         my $items='';
 1921:         foreach my $item (keys(%$storehash)) {
 1922:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 1923:         }
 1924:         $items=~s/\&$//;
 1925:         if ($namespace =~ /^enc/) {
 1926:             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
 1927:         } else {
 1928:             return &reply("putdom:$udom:$namespace:$items",$uhome);
 1929:         }
 1930:     } else {
 1931:         &logthis("put_dom failed - no homeserver and/or domain");
 1932:     }
 1933: }
 1934: 
 1935: # --------------------- newput for items in db file owned by domainconfig user
 1936: sub newput_dom {
 1937:     my ($namespace,$storehash,$udom) = @_;
 1938:     my $result;
 1939:     if (!$udom) {
 1940:         $udom=$env{'user.domain'};
 1941:     }
 1942:     if ($udom) {
 1943:         my $uname = &get_domainconfiguser($udom);
 1944:         $result = &newput($namespace,$storehash,$udom,$uname);
 1945:     }
 1946:     return $result;
 1947: }
 1948: 
 1949: # --------------------- delete for items in db file owned by domainconfig user
 1950: sub del_dom {
 1951:     my ($namespace,$storearr,$udom)=@_;
 1952:     if (ref($storearr) eq 'ARRAY') {
 1953:         if (!$udom) {
 1954:             $udom=$env{'user.domain'};
 1955:         }
 1956:         if ($udom) {
 1957:             my $uname = &get_domainconfiguser($udom); 
 1958:             return &del($namespace,$storearr,$udom,$uname);
 1959:         }
 1960:     }
 1961: }
 1962: 
 1963: # ----------------------------------construct domainconfig user for a domain 
 1964: sub get_domainconfiguser {
 1965:     my ($udom) = @_;
 1966:     return $udom.'-domainconfig';
 1967: }
 1968: 
 1969: sub retrieve_inst_usertypes {
 1970:     my ($udom) = @_;
 1971:     my (%returnhash,@order);
 1972:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 1973:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 1974:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 1975:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
 1976:     } else {
 1977:         if (defined(&domain($udom,'primary'))) {
 1978:             my $uhome=&domain($udom,'primary');
 1979:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 1980:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 1981:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
 1982:                 return (\%returnhash,\@order);
 1983:             }
 1984:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 1985:             my @pairs=split(/\&/,$hashitems);
 1986:             foreach my $item (@pairs) {
 1987:                 my ($key,$value)=split(/=/,$item,2);
 1988:                 $key = &unescape($key);
 1989:                 next if ($key =~ /^error: 2 /);
 1990:                 $returnhash{$key}=&thaw_unescape($value);
 1991:             }
 1992:             my @esc_order = split(/\&/,$orderitems);
 1993:             foreach my $item (@esc_order) {
 1994:                 push(@order,&unescape($item));
 1995:             }
 1996:         } else {
 1997:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
 1998:         }
 1999:         return (\%returnhash,\@order);
 2000:     }
 2001: }
 2002: 
 2003: sub is_domainimage {
 2004:     my ($url) = @_;
 2005:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
 2006:         if (&domain($1) ne '') {
 2007:             return '1';
 2008:         }
 2009:     }
 2010:     return;
 2011: }
 2012: 
 2013: sub inst_directory_query {
 2014:     my ($srch) = @_;
 2015:     my $udom = $srch->{'srchdomain'};
 2016:     my %results;
 2017:     my $homeserver = &domain($udom,'primary');
 2018:     my $outcome;
 2019:     if ($homeserver ne '') {
 2020:         unless ($homeserver eq $perlvar{'lonHostID'}) {
 2021:             if ($srch->{'srchby'} eq 'email') {
 2022:                 my $lcrev = &get_server_loncaparev($udom,$homeserver);
 2023:                 my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.(\d+)[\w.\-]+\'?$/);
 2024:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
 2025:                     (($major == 2) && ($minor < 11)) ||
 2026:                     (($major == 2) && ($minor == 11) && ($subver < 3))) {
 2027:                     return;
 2028:                 }
 2029:             }
 2030:         }
 2031: 	my $queryid=&reply("querysend:instdirsearch:".
 2032: 			   &escape($srch->{'srchby'}).':'.
 2033: 			   &escape($srch->{'srchterm'}).':'.
 2034: 			   &escape($srch->{'srchtype'}),$homeserver);
 2035: 	my $host=&hostname($homeserver);
 2036: 	if ($queryid !~/^\Q$host\E\_/) {
 2037: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
 2038: 	    return;
 2039: 	}
 2040: 	my $response = &get_query_reply($queryid);
 2041: 	my $maxtries = 5;
 2042: 	my $tries = 1;
 2043: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2044: 	    $response = &get_query_reply($queryid);
 2045: 	    $tries ++;
 2046: 	}
 2047: 
 2048:         if (!&error($response) && $response ne 'refused') {
 2049:             if ($response eq 'unavailable') {
 2050:                 $outcome = $response;
 2051:             } else {
 2052:                 $outcome = 'ok';
 2053:                 my @matches = split(/\n/,$response);
 2054:                 foreach my $match (@matches) {
 2055:                     my ($key,$value) = split(/=/,$match);
 2056:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 2057:                 }
 2058:             }
 2059:         }
 2060:     }
 2061:     return ($outcome,%results);
 2062: }
 2063: 
 2064: sub usersearch {
 2065:     my ($srch) = @_;
 2066:     my $dom = $srch->{'srchdomain'};
 2067:     my %results;
 2068:     my %libserv = &all_library();
 2069:     my $query = 'usersearch';
 2070:     foreach my $tryserver (keys(%libserv)) {
 2071:         if (&host_domain($tryserver) eq $dom) {
 2072:             unless ($tryserver eq $perlvar{'lonHostID'}) {
 2073:                 if ($srch->{'srchby'} eq 'email') {
 2074:                     my $lcrev = &get_server_loncaparev($dom,$tryserver);
 2075:                     my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.(\d+)[\w.\-]+\'?$/);
 2076:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
 2077:                              (($major == 2) && ($minor < 11)) ||
 2078:                              (($major == 2) && ($minor == 11) && ($subver < 3)));
 2079:                 }
 2080:             }
 2081:             my $host=&hostname($tryserver);
 2082:             my $queryid=
 2083:                 &reply("querysend:".&escape($query).':'.
 2084:                        &escape($srch->{'srchby'}).':'.
 2085:                        &escape($srch->{'srchtype'}).':'.
 2086:                        &escape($srch->{'srchterm'}),$tryserver);
 2087:             if ($queryid !~/^\Q$host\E\_/) {
 2088:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 2089:                 next;
 2090:             }
 2091:             my $reply = &get_query_reply($queryid);
 2092:             my $maxtries = 1;
 2093:             my $tries = 1;
 2094:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 2095:                 $reply = &get_query_reply($queryid);
 2096:                 $tries ++;
 2097:             }
 2098:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 2099:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 2100:             } else {
 2101:                 my @matches;
 2102:                 if ($reply =~ /\n/) {
 2103:                     @matches = split(/\n/,$reply);
 2104:                 } else {
 2105:                     @matches = split(/\&/,$reply);
 2106:                 }
 2107:                 foreach my $match (@matches) {
 2108:                     my ($uname,$udom,%userhash);
 2109:                     foreach my $entry (split(/:/,$match)) {
 2110:                         my ($key,$value) =
 2111:                             map {&unescape($_);} split(/=/,$entry);
 2112:                         $userhash{$key} = $value;
 2113:                         if ($key eq 'username') {
 2114:                             $uname = $value;
 2115:                         } elsif ($key eq 'domain') {
 2116:                             $udom = $value;
 2117:                         }
 2118:                     }
 2119:                     $results{$uname.':'.$udom} = \%userhash;
 2120:                 }
 2121:             }
 2122:         }
 2123:     }
 2124:     return %results;
 2125: }
 2126: 
 2127: sub get_instuser {
 2128:     my ($udom,$uname,$id) = @_;
 2129:     my $homeserver = &domain($udom,'primary');
 2130:     my ($outcome,%results);
 2131:     if ($homeserver ne '') {
 2132:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 2133:                            &escape($id).':'.&escape($udom),$homeserver);
 2134:         my $host=&hostname($homeserver);
 2135:         if ($queryid !~/^\Q$host\E\_/) {
 2136:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 2137:             return;
 2138:         }
 2139:         my $response = &get_query_reply($queryid);
 2140:         my $maxtries = 5;
 2141:         my $tries = 1;
 2142:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2143:             $response = &get_query_reply($queryid);
 2144:             $tries ++;
 2145:         }
 2146:         if (!&error($response) && $response ne 'refused') {
 2147:             if ($response eq 'unavailable') {
 2148:                 $outcome = $response;
 2149:             } else {
 2150:                 $outcome = 'ok';
 2151:                 my @matches = split(/\n/,$response);
 2152:                 foreach my $match (@matches) {
 2153:                     my ($key,$value) = split(/=/,$match);
 2154:                     $results{&unescape($key)} = &thaw_unescape($value);
 2155:                 }
 2156:             }
 2157:         }
 2158:     }
 2159:     my %userinfo;
 2160:     if (ref($results{$uname}) eq 'HASH') {
 2161:         %userinfo = %{$results{$uname}};
 2162:     } 
 2163:     return ($outcome,%userinfo);
 2164: }
 2165: 
 2166: sub get_multiple_instusers {
 2167:     my ($udom,$users,$caller) = @_;
 2168:     my ($outcome,$results);
 2169:     if (ref($users) eq 'HASH') {
 2170:         my $count = keys(%{$users});
 2171:         my $requested = &freeze_escape($users);
 2172:         my $homeserver = &domain($udom,'primary');
 2173:         if ($homeserver ne '') {
 2174:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
 2175:             my $host=&hostname($homeserver);
 2176:             if ($queryid !~/^\Q$host\E\_/) {
 2177:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
 2178:                          ' for host: '.$homeserver.'in domain '.$udom);
 2179:                 return ($outcome,$results);
 2180:             }
 2181:             my $response = &get_query_reply($queryid);
 2182:             my $maxtries = 5;
 2183:             if ($count > 100) {
 2184:                 $maxtries = 1+int($count/20);
 2185:             }
 2186:             my $tries = 1;
 2187:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
 2188:                 $response = &get_query_reply($queryid);
 2189:                 $tries ++;
 2190:             }
 2191:             if ($response eq '') {
 2192:                 $results = {};
 2193:                 foreach my $key (keys(%{$users})) {
 2194:                     my ($uname,$id);
 2195:                     if ($caller eq 'id') {
 2196:                         $id = $key;
 2197:                     } else {
 2198:                         $uname = $key;
 2199:                     }
 2200:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
 2201:                     $outcome = $resp;
 2202:                     if ($resp eq 'ok') {
 2203:                         %{$results} = (%{$results}, %info);
 2204:                     } else {
 2205:                         last;
 2206:                     }
 2207:                 }
 2208:             } elsif(!&error($response) && ($response ne 'refused')) {
 2209:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
 2210:                     $outcome = $response;
 2211:                 } else {
 2212:                     ($outcome,my $userdata) = split(/=/,$response,2);
 2213:                     if ($outcome eq 'ok') {
 2214:                         $results = &thaw_unescape($userdata);
 2215:                     }
 2216:                 }
 2217:             }
 2218:         }
 2219:     }
 2220:     return ($outcome,$results);
 2221: }
 2222: 
 2223: sub inst_rulecheck {
 2224:     my ($udom,$uname,$id,$item,$rules) = @_;
 2225:     my %returnhash;
 2226:     if ($udom ne '') {
 2227:         if (ref($rules) eq 'ARRAY') {
 2228:             @{$rules} = map {&escape($_);} (@{$rules});
 2229:             my $rulestr = join(':',@{$rules});
 2230:             my $homeserver=&domain($udom,'primary');
 2231:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2232:                 my $response;
 2233:                 if ($item eq 'username') {                
 2234:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 2235:                                               ':'.&escape($uname).':'.$rulestr,
 2236:                                               $homeserver));
 2237:                 } elsif ($item eq 'id') {
 2238:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 2239:                                               ':'.&escape($id).':'.$rulestr,
 2240:                                               $homeserver));
 2241:                 } elsif ($item eq 'selfcreate') {
 2242:                     $response=&unescape(&reply('instselfcreatecheck:'.
 2243:                                                &escape($udom).':'.&escape($uname).
 2244:                                               ':'.$rulestr,$homeserver));
 2245:                 }
 2246:                 if ($response ne 'refused') {
 2247:                     my @pairs=split(/\&/,$response);
 2248:                     foreach my $item (@pairs) {
 2249:                         my ($key,$value)=split(/=/,$item,2);
 2250:                         $key = &unescape($key);
 2251:                         next if ($key =~ /^error: 2 /);
 2252:                         $returnhash{$key}=&thaw_unescape($value);
 2253:                     }
 2254:                 }
 2255:             }
 2256:         }
 2257:     }
 2258:     return %returnhash;
 2259: }
 2260: 
 2261: sub inst_userrules {
 2262:     my ($udom,$check) = @_;
 2263:     my (%ruleshash,@ruleorder);
 2264:     if ($udom ne '') {
 2265:         my $homeserver=&domain($udom,'primary');
 2266:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2267:             my $response;
 2268:             if ($check eq 'id') {
 2269:                 $response=&reply('instidrules:'.&escape($udom),
 2270:                                  $homeserver);
 2271:             } elsif ($check eq 'email') {
 2272:                 $response=&reply('instemailrules:'.&escape($udom),
 2273:                                  $homeserver);
 2274:             } else {
 2275:                 $response=&reply('instuserrules:'.&escape($udom),
 2276:                                  $homeserver);
 2277:             }
 2278:             if (($response ne 'refused') && ($response ne 'error') && 
 2279:                 ($response ne 'unknown_cmd') && 
 2280:                 ($response ne 'no_such_host')) {
 2281:                 my ($hashitems,$orderitems) = split(/:/,$response);
 2282:                 my @pairs=split(/\&/,$hashitems);
 2283:                 foreach my $item (@pairs) {
 2284:                     my ($key,$value)=split(/=/,$item,2);
 2285:                     $key = &unescape($key);
 2286:                     next if ($key =~ /^error: 2 /);
 2287:                     $ruleshash{$key}=&thaw_unescape($value);
 2288:                 }
 2289:                 my @esc_order = split(/\&/,$orderitems);
 2290:                 foreach my $item (@esc_order) {
 2291:                     push(@ruleorder,&unescape($item));
 2292:                 }
 2293:             }
 2294:         }
 2295:     }
 2296:     return (\%ruleshash,\@ruleorder);
 2297: }
 2298: 
 2299: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 2300: 
 2301: sub get_domain_defaults {
 2302:     my ($domain,$ignore_cache) = @_;
 2303:     return if (($domain eq '') || ($domain eq 'public'));
 2304:     my $cachetime = 60*60*24;
 2305:     unless ($ignore_cache) {
 2306:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 2307:         if (defined($cached)) {
 2308:             if (ref($result) eq 'HASH') {
 2309:                 return %{$result};
 2310:             }
 2311:         }
 2312:     }
 2313:     my %domdefaults;
 2314:     my %domconfig =
 2315:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 2316:                                   'requestcourses','inststatus',
 2317:                                   'coursedefaults','usersessions',
 2318:                                   'requestauthor','selfenrollment',
 2319:                                   'coursecategories','autoenroll',
 2320:                                   'helpsettings'],$domain);
 2321:     my @coursetypes = ('official','unofficial','community','textbook');
 2322:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 2323:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 2324:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 2325:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 2326:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 2327:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 2328:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
 2329:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
 2330:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
 2331:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
 2332:     } else {
 2333:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 2334:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 2335:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 2336:     }
 2337:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 2338:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 2339:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 2340:         } else {
 2341:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 2342:         }
 2343:         my @usertools = ('aboutme','blog','webdav','portfolio');
 2344:         foreach my $item (@usertools) {
 2345:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 2346:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 2347:             }
 2348:         }
 2349:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
 2350:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
 2351:         }
 2352:     }
 2353:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 2354:         foreach my $item ('official','unofficial','community','textbook') {
 2355:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 2356:         }
 2357:     }
 2358:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
 2359:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
 2360:     }
 2361:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 2362:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
 2363:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 2364:         }
 2365:     }
 2366:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 2367:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
 2368:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
 2369:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
 2370:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
 2371:         }
 2372:         foreach my $type (@coursetypes) {
 2373:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
 2374:                 unless ($type eq 'community') {
 2375:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
 2376:                 }
 2377:             }
 2378:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
 2379:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
 2380:             }
 2381:             if ($domdefaults{'postsubmit'} eq 'on') {
 2382:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
 2383:                     $domdefaults{$type.'postsubtimeout'} =
 2384:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
 2385:                 }
 2386:             }
 2387:         }
 2388:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
 2389:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
 2390:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
 2391:                 if (@clonecodes) {
 2392:                     $domdefaults{'canclone'} = join('+',@clonecodes);
 2393:                 }
 2394:             }
 2395:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
 2396:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
 2397:         }
 2398:         if ($domconfig{'coursedefaults'}{'texengine'}) {
 2399:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
 2400:         }
 2401:     }
 2402:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 2403:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 2404:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 2405:         }
 2406:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 2407:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 2408:         }
 2409:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
 2410:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
 2411:         }
 2412:     }
 2413:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
 2414:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
 2415:             my @settings = ('types','registered','enroll_dates','access_dates','section',
 2416:                             'approval','limit');
 2417:             foreach my $type (@coursetypes) {
 2418:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
 2419:                     my @mgrdc = ();
 2420:                     foreach my $item (@settings) {
 2421:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
 2422:                             push(@mgrdc,$item);
 2423:                         }
 2424:                     }
 2425:                     if (@mgrdc) {
 2426:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
 2427:                     }
 2428:                 }
 2429:             }
 2430:         }
 2431:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
 2432:             foreach my $type (@coursetypes) {
 2433:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
 2434:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
 2435:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
 2436:                     }
 2437:                 }
 2438:             }
 2439:         }
 2440:     }
 2441:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 2442:         $domdefaults{'catauth'} = 'std';
 2443:         $domdefaults{'catunauth'} = 'std';
 2444:         if ($domconfig{'coursecategories'}{'auth'}) {
 2445:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
 2446:         }
 2447:         if ($domconfig{'coursecategories'}{'unauth'}) {
 2448:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
 2449:         }
 2450:     }
 2451:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 2452:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
 2453:     }
 2454:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
 2455:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
 2456:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
 2457:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
 2458:         }
 2459:     }
 2460:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
 2461:     return %domdefaults;
 2462: }
 2463: 
 2464: sub get_dom_cats {
 2465:     my ($dom) = @_;
 2466:     return unless (&domain($dom));
 2467:     my ($cats,$cached)=&is_cached_new('cats',$dom);
 2468:     unless (defined($cached)) {
 2469:         my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
 2470:         if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 2471:             if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
 2472:                 %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
 2473:             } else {
 2474:                 $cats = {};
 2475:             }
 2476:         } else {
 2477:             $cats = {};
 2478:         }
 2479:         &Apache::lonnet::do_cache_new('cats',$dom,$cats,3600);
 2480:     }
 2481:     return $cats;
 2482: }
 2483: 
 2484: sub get_dom_instcats {
 2485:     my ($dom) = @_;
 2486:     return unless (&domain($dom));
 2487:     my ($instcats,$cached)=&is_cached_new('instcats',$dom);
 2488:     unless (defined($cached)) {
 2489:         my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
 2490:         my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
 2491:         if ($totcodes > 0) {
 2492:             my $caller = 'global';
 2493:             if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
 2494:                                       \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
 2495:                 $instcats = {
 2496:                                 codes => \%codes,
 2497:                                 codetitles => \@codetitles,
 2498:                                 cat_titles => \%cat_titles,
 2499:                                 cat_order => \%cat_order,
 2500:                             };
 2501:                 &do_cache_new('instcats',$dom,$instcats,3600);
 2502:             }
 2503:         }
 2504:     }
 2505:     return $instcats;
 2506: }
 2507: 
 2508: sub retrieve_instcodes {
 2509:     my ($coursecodes,$dom) = @_;
 2510:     my $totcodes;
 2511:     my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
 2512:     foreach my $course (keys(%courses)) {
 2513:         if (ref($courses{$course}) eq 'HASH') {
 2514:             if ($courses{$course}{'inst_code'} ne '') {
 2515:                 $$coursecodes{$course} = $courses{$course}{'inst_code'};
 2516:                 $totcodes ++;
 2517:             }
 2518:         }
 2519:     }
 2520:     return $totcodes;
 2521: }
 2522: 
 2523: # --------------------------------------------- Get domain config for passwords
 2524: 
 2525: sub get_passwdconf {
 2526:     my ($dom) = @_;
 2527:     my (%passwdconf,$gotconf,$lookup);
 2528:     my ($result,$cached)=&is_cached_new('passwdconf',$dom);
 2529:     if (defined($cached)) {
 2530:         if (ref($result) eq 'HASH') {
 2531:             %passwdconf = %{$result};
 2532:             $gotconf = 1;
 2533:         }
 2534:     }
 2535:     unless ($gotconf) {
 2536:         my %domconfig = &get_dom('configuration',['passwords'],$dom);
 2537:         if (ref($domconfig{'passwords'}) eq 'HASH') {
 2538:             %passwdconf = %{$domconfig{'passwords'}};
 2539:         }
 2540:         my $cachetime = 24*60*60;
 2541:         &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
 2542:     }
 2543:     return %passwdconf;
 2544: }
 2545: 
 2546: sub course_portal_url {
 2547:     my ($cnum,$cdom) = @_;
 2548:     my $chome = &homeserver($cnum,$cdom);
 2549:     my $hostname = &hostname($chome);
 2550:     my $protocol = $protocol{$chome};
 2551:     $protocol = 'http' if ($protocol ne 'https');
 2552:     my %domdefaults = &get_domain_defaults($cdom);
 2553:     my $firsturl;
 2554:     if ($domdefaults{'portal_def'}) {
 2555:         $firsturl = $domdefaults{'portal_def'};
 2556:     } else {
 2557:         $firsturl = $protocol.'://'.$hostname;
 2558:     }
 2559:     return $firsturl;
 2560: }
 2561: 
 2562: # --------------------------------------------------- Assign a key to a student
 2563: 
 2564: sub assign_access_key {
 2565: #
 2566: # a valid key looks like uname:udom#comments
 2567: # comments are being appended
 2568: #
 2569:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 2570:     $kdom=
 2571:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 2572:     $knum=
 2573:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 2574:     $cdom=
 2575:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2576:     $cnum=
 2577:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2578:     $udom=$env{'user.name'} unless (defined($udom));
 2579:     $uname=$env{'user.domain'} unless (defined($uname));
 2580:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 2581:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 2582:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 2583:                                                   # assigned to this person
 2584:                                                   # - this should not happen,
 2585:                                                   # unless something went wrong
 2586:                                                   # the first time around
 2587: # ready to assign
 2588:         $logentry=$1.'; '.$logentry;
 2589:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 2590:                                                  $kdom,$knum) eq 'ok') {
 2591: # key now belongs to user
 2592: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 2593:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 2594:                 &appenv({'environment.'.$envkey => $ckey});
 2595:                 return 'ok';
 2596:             } else {
 2597:                 return 
 2598:   'error: Count not permanently assign key, will need to be re-entered later.';
 2599: 	    }
 2600:         } else {
 2601:             return 'error: Could not assign key, try again later.';
 2602:         }
 2603:     } elsif (!$existing{$ckey}) {
 2604: # the key does not exist
 2605: 	return 'error: The key does not exist';
 2606:     } else {
 2607: # the key is somebody else's
 2608: 	return 'error: The key is already in use';
 2609:     }
 2610: }
 2611: 
 2612: # ------------------------------------------ put an additional comment on a key
 2613: 
 2614: sub comment_access_key {
 2615: #
 2616: # a valid key looks like uname:udom#comments
 2617: # comments are being appended
 2618: #
 2619:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 2620:     $cdom=
 2621:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2622:     $cnum=
 2623:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2624:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2625:     if ($existing{$ckey}) {
 2626:         $existing{$ckey}.='; '.$logentry;
 2627: # ready to assign
 2628:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 2629:                                                  $cdom,$cnum) eq 'ok') {
 2630: 	    return 'ok';
 2631:         } else {
 2632: 	    return 'error: Count not store comment.';
 2633:         }
 2634:     } else {
 2635: # the key does not exist
 2636: 	return 'error: The key does not exist';
 2637:     }
 2638: }
 2639: 
 2640: # ------------------------------------------------------ Generate a set of keys
 2641: 
 2642: sub generate_access_keys {
 2643:     my ($number,$cdom,$cnum,$logentry)=@_;
 2644:     $cdom=
 2645:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2646:     $cnum=
 2647:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2648:     unless (&allowed('mky',$cdom)) { return 0; }
 2649:     unless (($cdom) && ($cnum)) { return 0; }
 2650:     if ($number>10000) { return 0; }
 2651:     sleep(2); # make sure don't get same seed twice
 2652:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 2653:     my $total=0;
 2654:     for (my $i=1;$i<=$number;$i++) {
 2655:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 2656:                   sprintf("%lx",int(100000*rand)).'-'.
 2657:                   sprintf("%lx",int(100000*rand));
 2658:        $newkey=~s/1/g/g; # folks mix up 1 and l
 2659:        $newkey=~s/0/h/g; # and also 0 and O
 2660:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 2661:        if ($existing{$newkey}) {
 2662:            $i--;
 2663:        } else {
 2664: 	  if (&put('accesskeys',
 2665:               { $newkey => '# generated '.localtime().
 2666:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 2667:                            '; '.$logentry },
 2668: 		   $cdom,$cnum) eq 'ok') {
 2669:               $total++;
 2670: 	  }
 2671:        }
 2672:     }
 2673:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 2674:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 2675:     return $total;
 2676: }
 2677: 
 2678: # ------------------------------------------------------- Validate an accesskey
 2679: 
 2680: sub validate_access_key {
 2681:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 2682:     $cdom=
 2683:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2684:     $cnum=
 2685:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2686:     $udom=$env{'user.domain'} unless (defined($udom));
 2687:     $uname=$env{'user.name'} unless (defined($uname));
 2688:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2689:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 2690: }
 2691: 
 2692: # ------------------------------------- Find the section of student in a course
 2693: sub devalidate_getsection_cache {
 2694:     my ($udom,$unam,$courseid)=@_;
 2695:     my $hashid="$udom:$unam:$courseid";
 2696:     &devalidate_cache_new('getsection',$hashid);
 2697: }
 2698: 
 2699: sub courseid_to_courseurl {
 2700:     my ($courseid) = @_;
 2701:     #already url style courseid
 2702:     return $courseid if ($courseid =~ m{^/});
 2703: 
 2704:     if (exists($env{'course.'.$courseid.'.num'})) {
 2705: 	my $cnum = $env{'course.'.$courseid.'.num'};
 2706: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 2707: 	return "/$cdom/$cnum";
 2708:     }
 2709: 
 2710:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 2711:     if (exists($courseinfo{'num'})) {
 2712: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 2713:     }
 2714: 
 2715:     return undef;
 2716: }
 2717: 
 2718: sub getsection {
 2719:     my ($udom,$unam,$courseid)=@_;
 2720:     my $cachetime=1800;
 2721: 
 2722:     my $hashid="$udom:$unam:$courseid";
 2723:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 2724:     if (defined($cached)) { return $result; }
 2725: 
 2726:     my %Pending; 
 2727:     my %Expired;
 2728:     #
 2729:     # Each role can either have not started yet (pending), be active, 
 2730:     #    or have expired.
 2731:     #
 2732:     # If there is an active role, we are done.
 2733:     #
 2734:     # If there is more than one role which has not started yet, 
 2735:     #     choose the one which will start sooner
 2736:     # If there is one role which has not started yet, return it.
 2737:     #
 2738:     # If there is more than one expired role, choose the one which ended last.
 2739:     # If there is a role which has expired, return it.
 2740:     #
 2741:     $courseid = &courseid_to_courseurl($courseid);
 2742:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 2743:     foreach my $key (keys(%roleshash)) {
 2744:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 2745:         my $section=$1;
 2746:         if ($key eq $courseid.'_st') { $section=''; }
 2747:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 2748:         my $now=time;
 2749:         if (defined($end) && $end && ($now > $end)) {
 2750:             $Expired{$end}=$section;
 2751:             next;
 2752:         }
 2753:         if (defined($start) && $start && ($now < $start)) {
 2754:             $Pending{$start}=$section;
 2755:             next;
 2756:         }
 2757:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 2758:     }
 2759:     #
 2760:     # Presumedly there will be few matching roles from the above
 2761:     # loop and the sorting time will be negligible.
 2762:     if (scalar(keys(%Pending))) {
 2763:         my ($time) = sort {$a <=> $b} keys(%Pending);
 2764:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 2765:     } 
 2766:     if (scalar(keys(%Expired))) {
 2767:         my @sorted = sort {$a <=> $b} keys(%Expired);
 2768:         my $time = pop(@sorted);
 2769:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 2770:     }
 2771:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 2772: }
 2773: 
 2774: sub save_cache {
 2775:     &purge_remembered();
 2776:     #&Apache::loncommon::validate_page();
 2777:     undef(%env);
 2778:     undef($env_loaded);
 2779: }
 2780: 
 2781: my $to_remember=-1;
 2782: my %remembered;
 2783: my %accessed;
 2784: my $kicks=0;
 2785: my $hits=0;
 2786: sub make_key {
 2787:     my ($name,$id) = @_;
 2788:     if (length($id) > 65 
 2789: 	&& length(&escape($id)) > 200) {
 2790: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 2791:     }
 2792:     return &escape($name.':'.$id);
 2793: }
 2794: 
 2795: sub devalidate_cache_new {
 2796:     my ($name,$id,$debug) = @_;
 2797:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 2798:     my $remembered_id=$name.':'.$id;
 2799:     $id=&make_key($name,$id);
 2800:     $memcache->delete($id);
 2801:     delete($remembered{$remembered_id});
 2802:     delete($accessed{$remembered_id});
 2803: }
 2804: 
 2805: sub is_cached_new {
 2806:     my ($name,$id,$debug) = @_;
 2807:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) for 
 2808:                                      # keys in %remembered hash, which persists for
 2809:                                      # duration of request (no restriction on key length).
 2810:     if (exists($remembered{$remembered_id})) {
 2811: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
 2812: 	$accessed{$remembered_id}=[&gettimeofday()];
 2813: 	$hits++;
 2814: 	return ($remembered{$remembered_id},1);
 2815:     }
 2816:     $id=&make_key($name,$id);
 2817:     my $value = $memcache->get($id);
 2818:     if (!(defined($value))) {
 2819: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 2820: 	return (undef,undef);
 2821:     }
 2822:     if ($value eq '__undef__') {
 2823: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 2824: 	$value=undef;
 2825:     }
 2826:     &make_room($remembered_id,$value,$debug);
 2827:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 2828:     return ($value,1);
 2829: }
 2830: 
 2831: sub do_cache_new {
 2832:     my ($name,$id,$value,$time,$debug) = @_;
 2833:     my $remembered_id=$name.':'.$id;
 2834:     $id=&make_key($name,$id);
 2835:     my $setvalue=$value;
 2836:     if (!defined($setvalue)) {
 2837: 	$setvalue='__undef__';
 2838:     }
 2839:     if (!defined($time) ) {
 2840: 	$time=600;
 2841:     }
 2842:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 2843:     my $result = $memcache->set($id,$setvalue,$time);
 2844:     if (! $result) {
 2845: 	&logthis("caching of id -> $id  failed");
 2846: 	$memcache->disconnect_all();
 2847:     }
 2848:     # need to make a copy of $value
 2849:     &make_room($remembered_id,$value,$debug);
 2850:     return $value;
 2851: }
 2852: 
 2853: sub make_room {
 2854:     my ($remembered_id,$value,$debug)=@_;
 2855: 
 2856:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
 2857:                                     : $value;
 2858:     if ($to_remember<0) { return; }
 2859:     $accessed{$remembered_id}=[&gettimeofday()];
 2860:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 2861:     my $to_kick;
 2862:     my $max_time=0;
 2863:     foreach my $other (keys(%accessed)) {
 2864: 	if (&tv_interval($accessed{$other}) > $max_time) {
 2865: 	    $to_kick=$other;
 2866: 	    $max_time=&tv_interval($accessed{$other});
 2867: 	}
 2868:     }
 2869:     delete($remembered{$to_kick});
 2870:     delete($accessed{$to_kick});
 2871:     $kicks++;
 2872:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 2873:     return;
 2874: }
 2875: 
 2876: sub purge_remembered {
 2877:     #&logthis("Tossing ".scalar(keys(%remembered)));
 2878:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 2879:     undef(%remembered);
 2880:     undef(%accessed);
 2881: }
 2882: # ------------------------------------- Read an entry from a user's environment
 2883: 
 2884: sub userenvironment {
 2885:     my ($udom,$unam,@what)=@_;
 2886:     my $items;
 2887:     foreach my $item (@what) {
 2888:         $items.=&escape($item).'&';
 2889:     }
 2890:     $items=~s/\&$//;
 2891:     my %returnhash=();
 2892:     my $uhome = &homeserver($unam,$udom);
 2893:     unless ($uhome eq 'no_host') {
 2894:         my @answer=split(/\&/, 
 2895:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 2896:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 2897:             return %returnhash;
 2898:         }
 2899:         my $i;
 2900:         for ($i=0;$i<=$#what;$i++) {
 2901: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 2902:         }
 2903:     }
 2904:     return %returnhash;
 2905: }
 2906: 
 2907: # ---------------------------------------------------------- Get a studentphoto
 2908: sub studentphoto {
 2909:     my ($udom,$unam,$ext) = @_;
 2910:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2911:     if (defined($env{'request.course.id'})) {
 2912:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 2913:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 2914:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 2915:             } else {
 2916:                 my ($result,$perm_reqd)=
 2917: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2918:                 if ($result eq 'ok') {
 2919:                     if (!($perm_reqd eq 'yes')) {
 2920:                         return(&retrievestudentphoto($udom,$unam,$ext));
 2921:                     }
 2922:                 }
 2923:             }
 2924:         }
 2925:     } else {
 2926:         my ($result,$perm_reqd) = 
 2927: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2928:         if ($result eq 'ok') {
 2929:             if (!($perm_reqd eq 'yes')) {
 2930:                 return(&retrievestudentphoto($udom,$unam,$ext));
 2931:             }
 2932:         }
 2933:     }
 2934:     return '/adm/lonKaputt/lonlogo_broken.gif';
 2935: }
 2936: 
 2937: sub retrievestudentphoto {
 2938:     my ($udom,$unam,$ext,$type) = @_;
 2939:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2940:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 2941:     if ($ret eq 'ok') {
 2942:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 2943:         if ($type eq 'thumbnail') {
 2944:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 2945:         }
 2946:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 2947:         return $tokenurl;
 2948:     } else {
 2949:         if ($type eq 'thumbnail') {
 2950:             return '/adm/lonKaputt/genericstudent_tn.gif';
 2951:         } else { 
 2952:             return '/adm/lonKaputt/lonlogo_broken.gif';
 2953:         }
 2954:     }
 2955: }
 2956: 
 2957: # -------------------------------------------------------------------- New chat
 2958: 
 2959: sub chatsend {
 2960:     my ($newentry,$anon,$group)=@_;
 2961:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 2962:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2963:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 2964:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 2965: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 2966: 		   &escape($newentry)).':'.$group,$chome);
 2967: }
 2968: 
 2969: # ------------------------------------------ Find current version of a resource
 2970: 
 2971: sub getversion {
 2972:     my $fname=&clutter(shift);
 2973:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
 2974:     return &currentversion(&filelocation('',$fname));
 2975: }
 2976: 
 2977: sub currentversion {
 2978:     my $fname=shift;
 2979:     my $author=$fname;
 2980:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2981:     my ($udom,$uname)=split(/\//,$author);
 2982:     my $home=&homeserver($uname,$udom);
 2983:     if ($home eq 'no_host') { 
 2984:         return -1; 
 2985:     }
 2986:     my $answer=&reply("currentversion:$fname",$home);
 2987:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 2988: 	return -1;
 2989:     }
 2990:     return $answer;
 2991: }
 2992: 
 2993: #
 2994: # Return special version number of resource if set by override, empty otherwise
 2995: #
 2996: sub usedversion {
 2997:     my $fname=shift;
 2998:     unless ($fname) { $fname=$env{'request.uri'}; }
 2999:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 3000:     if ($urlversion) { return $urlversion; }
 3001:     return '';
 3002: }
 3003: 
 3004: # ----------------------------- Subscribe to a resource, return URL if possible
 3005: 
 3006: sub subscribe {
 3007:     my $fname=shift;
 3008:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 3009:     $fname=~s/[\n\r]//g;
 3010:     my $author=$fname;
 3011:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3012:     my ($udom,$uname)=split(/\//,$author);
 3013:     my $home=homeserver($uname,$udom);
 3014:     if ($home eq 'no_host') {
 3015:         return 'not_found';
 3016:     }
 3017:     my $answer=reply("sub:$fname",$home);
 3018:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3019: 	$answer.=' by '.$home;
 3020:     }
 3021:     return $answer;
 3022: }
 3023:     
 3024: # -------------------------------------------------------------- Replicate file
 3025: 
 3026: sub repcopy {
 3027:     my $filename=shift;
 3028:     $filename=~s/\/+/\//g;
 3029:     my $londocroot = $perlvar{'lonDocRoot'};
 3030:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 3031:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
 3032:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 3033: 	$filename=~m{^/*(uploaded|editupload)/}) {
 3034: 	return &repcopy_userfile($filename);
 3035:     }
 3036:     $filename=~s/[\n\r]//g;
 3037:     my $transname="$filename.in.transfer";
 3038: # FIXME: this should flock
 3039:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 3040:     my $remoteurl=subscribe($filename);
 3041:     if ($remoteurl =~ /^con_lost by/) {
 3042: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3043:            return 'unavailable';
 3044:     } elsif ($remoteurl eq 'not_found') {
 3045: 	   #&logthis("Subscribe returned not_found: $filename");
 3046: 	   return 'not_found';
 3047:     } elsif ($remoteurl =~ /^rejected by/) {
 3048: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3049:            return 'forbidden';
 3050:     } elsif ($remoteurl eq 'directory') {
 3051:            return 'ok';
 3052:     } else {
 3053:         my $author=$filename;
 3054:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3055:         my ($udom,$uname)=split(/\//,$author);
 3056:         my $home=homeserver($uname,$udom);
 3057:         unless ($home eq $perlvar{'lonHostID'}) {
 3058:            my @parts=split(/\//,$filename);
 3059:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 3060:            if ($path ne "$londocroot/res") {
 3061:                &logthis("Malconfiguration for replication: $filename");
 3062: 	       return 'bad_request';
 3063:            }
 3064:            my $count;
 3065:            for ($count=5;$count<$#parts;$count++) {
 3066:                $path.="/$parts[$count]";
 3067:                if ((-e $path)!=1) {
 3068: 		   mkdir($path,0777);
 3069:                }
 3070:            }
 3071:            my $ua=new LWP::UserAgent;
 3072:            my $request=new HTTP::Request('GET',"$remoteurl");
 3073:            my $response=$ua->request($request,$transname);
 3074:            if ($response->is_error()) {
 3075: 	       unlink($transname);
 3076:                my $message=$response->status_line;
 3077:                &logthis("<font color=\"blue\">WARNING:"
 3078:                        ." LWP get: $message: $filename</font>");
 3079:                return 'unavailable';
 3080:            } else {
 3081: 	       if ($remoteurl!~/\.meta$/) {
 3082:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 3083:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 3084:                   if ($mresponse->is_error()) {
 3085: 		      unlink($filename.'.meta');
 3086:                       &logthis(
 3087:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 3088:                   }
 3089: 	       }
 3090:                rename($transname,$filename);
 3091:                return 'ok';
 3092:            }
 3093:        }
 3094:     }
 3095: }
 3096: 
 3097: # ------------------------------------------------- Unsubscribe from a resource
 3098: 
 3099: sub unsubscribe {
 3100:     my ($fname) = @_;
 3101:     my $answer;
 3102:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return $answer; }
 3103:     $fname=~s/[\n\r]//g;
 3104:     my $author=$fname;
 3105:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3106:     my ($udom,$uname)=split(/\//,$author);
 3107:     my $home=homeserver($uname,$udom);
 3108:     if ($home eq 'no_host') {
 3109:         $answer = 'no_host';
 3110:     } elsif (grep { $_ eq $home } &current_machine_ids()) {
 3111:         $answer = 'home';
 3112:     } else {
 3113:         my $defdom = $perlvar{'lonDefDomain'};
 3114:         if (&will_trust('content',$defdom,$udom)) {
 3115:             $answer = reply("unsub:$fname",$home);
 3116:         } else {
 3117:             $answer = 'untrusted';
 3118:         }
 3119:     }
 3120:     return $answer;
 3121: }
 3122: 
 3123: # ------------------------------------------------ Get server side include body
 3124: sub ssi_body {
 3125:     my ($filelink,%form)=@_;
 3126:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 3127:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 3128:     }
 3129:     my $output='';
 3130:     my $response;
 3131:     if ($filelink=~/^https?\:/) {
 3132:        ($output,$response)=&externalssi($filelink);
 3133:     } else {
 3134:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 3135:        $filelink .= 'inhibitmenu=yes';
 3136:        ($output,$response)=&ssi($filelink,%form);
 3137:     }
 3138:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 3139:     $output=~s/^.*?\<body[^\>]*\>//si;
 3140:     $output=~s/\<\/body\s*\>.*?$//si;
 3141:     if (wantarray) {
 3142:         return ($output, $response);
 3143:     } else {
 3144:         return $output;
 3145:     }
 3146: }
 3147: 
 3148: # --------------------------------------------------------- Server Side Include
 3149: 
 3150: sub absolute_url {
 3151:     my ($host_name) = @_;
 3152:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 3153:     if ($host_name eq '') {
 3154: 	$host_name = $ENV{'SERVER_NAME'};
 3155:     }
 3156:     return $protocol.$host_name;
 3157: }
 3158: 
 3159: #
 3160: #   Server side include.
 3161: # Parameters:
 3162: #  fn     Possibly encrypted resource name/id.
 3163: #  form   Hash that describes how the rendering should be done
 3164: #         and other things.
 3165: # Returns:
 3166: #   Scalar context: The content of the response.
 3167: #   Array context:  2 element list of the content and the full response object.
 3168: #     
 3169: sub ssi {
 3170: 
 3171:     my ($fn,%form)=@_;
 3172:     my ($request,$response);
 3173: 
 3174:     $form{'no_update_last_known'}=1;
 3175:     &Apache::lonenc::check_encrypt(\$fn);
 3176:     if (%form) {
 3177:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 3178:       $request->content(join('&',map {
 3179:             my $name = escape($_);
 3180:             "$name=" . ( ref($form{$_}) eq 'ARRAY'
 3181:             ? join("&$name=", map {escape($_) } @{$form{$_}})
 3182:             : &escape($form{$_}) );
 3183:         } keys(%form)));
 3184:     } else {
 3185:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 3186:     }
 3187: 
 3188:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 3189: 
 3190:     if (($env{'request.course.id'}) &&
 3191:         ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
 3192:         ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
 3193:         ($form{'grade_symb'} ne '') &&
 3194:         (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
 3195:                                  ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
 3196:         if (LWP::UserAgent->VERSION >= 5.834) {
 3197:             my $ua=new LWP::UserAgent;
 3198:             $ua->local_address('127.0.0.1');
 3199:             $response = $ua->request($request);
 3200:         } else {
 3201:             {
 3202:                 require LWP::Protocol::http;
 3203:                 local @LWP::Protocol::http::EXTRA_SOCK_OPTS = (LocalAddr => '127.0.0.1');
 3204:                 my $ua=new LWP::UserAgent;
 3205:                 $response = $ua->request($request);
 3206:                 @LWP::Protocol::http::EXTRA_SOCK_OPTS = ();
 3207:             }
 3208:         }
 3209:     } else {
 3210:         my $ua=new LWP::UserAgent;
 3211:         $response = $ua->request($request);
 3212:     }
 3213:     if (wantarray) {
 3214: 	return ($response->content, $response);
 3215:     } else {
 3216: 	return $response->content;
 3217:     }
 3218: }
 3219: 
 3220: sub externalssi {
 3221:     my ($url)=@_;
 3222:     my $ua=new LWP::UserAgent;
 3223:     my $request=new HTTP::Request('GET',$url);
 3224:     my $response=$ua->request($request);
 3225:     if (wantarray) {
 3226:         return ($response->content, $response);
 3227:     } else {
 3228:         return $response->content;
 3229:     }
 3230: }
 3231: 
 3232: # If the local copy of a replicated resource is outdated, trigger a
 3233: # connection from the homeserver to flush the delayed queue. If no update
 3234: # happens, remove local copies of outdated resource (and corresponding
 3235: # metadata file).
 3236: 
 3237: sub remove_stale_resfile {
 3238:     my ($url) = @_;
 3239:     my $removed;
 3240:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
 3241:         my $audom = $1;
 3242:         my $auname = $2;
 3243:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
 3244:             my $homeserver = &homeserver($auname,$audom);
 3245:             unless (($homeserver eq 'no_host') ||
 3246:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
 3247:                 my $fname = &filelocation('',$url);
 3248:                 if (-e $fname) {
 3249:                     my $hostname = &hostname($homeserver);
 3250:                     if ($hostname) {
 3251:                         my $protocol = $protocol{$homeserver};
 3252:                         $protocol = 'http' if ($protocol ne 'https');
 3253:                         my $uri = $protocol.'://'.$hostname.'/raw/'.&declutter($url);
 3254:                         my $ua=new LWP::UserAgent;
 3255:                         $ua->timeout(5);
 3256:                         my $request=new HTTP::Request('HEAD',$uri);
 3257:                         my $response=$ua->request($request);
 3258:                         if ($response->is_success()) {
 3259:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
 3260:                             my $locmodtime = (stat($fname))[9];
 3261:                             if ($locmodtime < $remmodtime) {
 3262:                                 my $stale;
 3263:                                 my $answer = &reply('pong',$homeserver);
 3264:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
 3265:                                     sleep(0.2);
 3266:                                     $locmodtime = (stat($fname))[9];
 3267:                                     if ($locmodtime < $remmodtime) {
 3268:                                         my $posstransfer = $fname.'.in.transfer';
 3269:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
 3270:                                             $removed = 1;
 3271:                                         } else {
 3272:                                             $stale = 1;
 3273:                                         }
 3274:                                     } else {
 3275:                                         $removed = 1;
 3276:                                     }
 3277:                                 } else {
 3278:                                     $stale = 1;
 3279:                                 }
 3280:                                 if ($stale) {
 3281:                                     if (unlink($fname)) {
 3282:                                         if ($uri!~/\.meta$/) {
 3283:                                             if (-e $fname.'.meta') {
 3284:                                                 unlink($fname.'.meta');
 3285:                                             }
 3286:                                         }
 3287:                                         my $unsubresult = &unsubscribe($fname);
 3288:                                         unless ($unsubresult eq 'ok') {
 3289:                                             &logthis("no unsub of $fname from $homeserver, reason: $unsubresult");
 3290:                                         }
 3291:                                         $removed = 1;
 3292:                                     }
 3293:                                 }
 3294:                             }
 3295:                         }
 3296:                     }
 3297:                 }
 3298:             }
 3299:         }
 3300:     }
 3301:     return $removed;
 3302: }
 3303: 
 3304: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 3305: 
 3306: sub allowuploaded {
 3307:     my ($srcurl,$url)=@_;
 3308:     $url=&clutter(&declutter($url));
 3309:     my $dir=$url;
 3310:     $dir=~s/\/[^\/]+$//;
 3311:     my %httpref=();
 3312:     my $httpurl=&hreflocation('',$url);
 3313:     $httpref{'httpref.'.$httpurl}=$srcurl;
 3314:     &Apache::lonnet::appenv(\%httpref);
 3315: }
 3316: 
 3317: #
 3318: # Determine if the current user should be able to edit a particular resource,
 3319: # when viewing in course context.
 3320: # (a) When viewing resource used to determine if "Edit" item is included in
 3321: #     Functions.
 3322: # (b) When displaying folder contents in course editor, used to determine if
 3323: #     "Edit" link will be displayed alongside resource.
 3324: #
 3325: #  input: six args -- filename (decluttered), course number, course domain,
 3326: #                   url, symb (if registered) and group (if this is a group
 3327: #                   item -- e.g., bulletin board, group page etc.).
 3328: #  output: array of five scalars --
 3329: #          $cfile -- url for file editing if editable on current server
 3330: #          $home -- homeserver of resource (i.e., for author if published,
 3331: #                                           or course if uploaded.).
 3332: #          $switchserver --  1 if server switch will be needed.
 3333: #          $forceedit -- 1 if icon/link should be to go to edit mode
 3334: #          $forceview -- 1 if icon/link should be to go to view mode
 3335: #
 3336: 
 3337: sub can_edit_resource {
 3338:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
 3339:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
 3340: #
 3341: # For aboutme pages user can only edit his/her own.
 3342: #
 3343:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
 3344:         my ($sdom,$sname) = ($1,$2);
 3345:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
 3346:             $home = $env{'user.home'};
 3347:             $cfile = $resurl;
 3348:             if ($env{'form.forceedit'}) {
 3349:                 $forceview = 1;
 3350:             } else {
 3351:                 $forceedit = 1;
 3352:             }
 3353:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3354:         } else {
 3355:             return;
 3356:         }
 3357:     }
 3358: 
 3359:     if ($env{'request.course.id'}) {
 3360:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
 3361:         if ($group ne '') {
 3362: # if this is a group homepage or group bulletin board, check group privs
 3363:             my $allowed = 0;
 3364:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
 3365:                 if ((&allowed('mdg',$env{'request.course.id'}.
 3366:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3367:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3368:                     $allowed = 1;
 3369:                 }
 3370:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
 3371:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3372:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3373:                     $allowed = 1;
 3374:                 }
 3375:             }
 3376:             if ($allowed) {
 3377:                 $home=&homeserver($cnum,$cdom);
 3378:                 if ($env{'form.forceedit'}) {
 3379:                     $forceview = 1;
 3380:                 } else {
 3381:                     $forceedit = 1;
 3382:                 }
 3383:                 $cfile = $resurl;
 3384:             } else {
 3385:                 return;
 3386:             }
 3387:         } else {
 3388:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
 3389:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
 3390:                     return;
 3391:                 }
 3392:             } elsif (!$crsedit) {
 3393: #
 3394: # No edit allowed where CC has switched to student role.
 3395: #
 3396:                 return;
 3397:             }
 3398:         }
 3399:     }
 3400: 
 3401:     if ($file ne '') {
 3402:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
 3403:             if (&is_course_upload($file,$cnum,$cdom)) {
 3404:                 $uploaded = 1;
 3405:                 $incourse = 1;
 3406:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
 3407:                     $cfile = &hreflocation('',$file);
 3408:                     if ($env{'form.forceedit'}) {
 3409:                         $forceview = 1;
 3410:                     } else {
 3411:                         $forceedit = 1;
 3412:                     }
 3413:                 }
 3414:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
 3415:                 $incourse = 1;
 3416:                 if ($env{'form.forceedit'}) {
 3417:                     $forceview = 1;
 3418:                 } else {
 3419:                     $forceedit = 1;
 3420:                 }
 3421:                 $cfile = $resurl;
 3422:             } elsif (($resurl ne '') && (&is_on_map($resurl))) {
 3423:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
 3424:                     $incourse = 1;
 3425:                     if ($env{'form.forceedit'}) {
 3426:                         $forceview = 1;
 3427:                     } else {
 3428:                         $forceedit = 1;
 3429:                     }
 3430:                     $cfile = $resurl;
 3431:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
 3432:                     $incourse = 1;
 3433:                     $cfile = $resurl.'/smpedit';
 3434:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
 3435:                     $incourse = 1;
 3436:                     if ($env{'form.forceedit'}) {
 3437:                         $forceview = 1;
 3438:                     } else {
 3439:                         $forceedit = 1;
 3440:                     }
 3441:                     $cfile = $resurl;
 3442:                 } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
 3443:                     my ($map,$id,$res) = &decode_symb($symb);
 3444:                     if ($map =~ /\.page$/) {
 3445:                         $incourse = 1;
 3446:                         if ($env{'form.forceedit'}) {
 3447:                             $forceview = 1;
 3448:                             $cfile = $map;
 3449:                         } else {
 3450:                             $forceedit = 1;
 3451:                             $cfile =  '/adm/wrapper'.$resurl;
 3452:                         }
 3453:                     }
 3454:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 3455:                     $incourse = 1;
 3456:                     if ($env{'form.forceedit'}) {
 3457:                         $forceview = 1;
 3458:                     } else {
 3459:                         $forceedit = 1;
 3460:                     }
 3461:                     $cfile = $resurl;
 3462:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3463:                     $incourse = 1;
 3464:                     if ($env{'form.forceedit'}) {
 3465:                         $forceview = 1;
 3466:                     } else {
 3467:                         $forceedit = 1;
 3468:                     }
 3469:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3470:                 }
 3471:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
 3472:                 my $template = '/res/lib/templates/simpleproblem.problem';
 3473:                 if (&is_on_map($template)) {
 3474:                     $incourse = 1;
 3475:                     $forceview = 1;
 3476:                     $cfile = $template;
 3477:                 }
 3478:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 3479:                 $incourse = 1;
 3480:                 if ($env{'form.forceedit'}) {
 3481:                     $forceview = 1;
 3482:                 } else {
 3483:                     $forceedit = 1;
 3484:                 }
 3485:                 $cfile = $resurl;
 3486:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 3487:                 $incourse = 1;
 3488:                 if ($env{'form.forceedit'}) {
 3489:                     $forceview = 1;
 3490:                 } else {
 3491:                     $forceedit = 1;
 3492:                 }
 3493:                 $cfile = $resurl;
 3494:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
 3495:                 $incourse = 1;
 3496:                 $forceview = 1;
 3497:                 if ($symb) {
 3498:                     my ($map,$id,$res)=&decode_symb($symb);
 3499:                     $env{'request.symb'} = $symb;
 3500:                     $cfile = &clutter($res);
 3501:                 } else {
 3502:                     $cfile = $env{'form.suppurl'};
 3503:                     my $escfile = &unescape($cfile);
 3504:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 3505:                         $cfile = '/adm/wrapper'.$escfile;
 3506:                     } else {
 3507:                         $escfile =~ s{^http://}{};
 3508:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
 3509:                     }
 3510:                 }
 3511:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3512:                 if ($env{'form.forceedit'}) {
 3513:                     $forceview = 1;
 3514:                 } else {
 3515:                     $forceedit = 1;
 3516:                 }
 3517:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3518:             }
 3519:         }
 3520:         if ($uploaded || $incourse) {
 3521:             $home=&homeserver($cnum,$cdom);
 3522:         } elsif ($file !~ m{/$}) {
 3523:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
 3524:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
 3525:             # Check that the user has permission to edit this resource
 3526:             my $setpriv = 1;
 3527:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
 3528:             if (defined($cfudom)) {
 3529:                 $home=&homeserver($cfuname,$cfudom);
 3530:                 $cfile=$file;
 3531:             }
 3532:         }
 3533:         if (($cfile ne '') && (!$incourse || $uploaded) &&
 3534:             (($home ne '') && ($home ne 'no_host'))) {
 3535:             my @ids=&current_machine_ids();
 3536:             unless (grep(/^\Q$home\E$/,@ids)) {
 3537:                 $switchserver=1;
 3538:             }
 3539:         }
 3540:     }
 3541:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3542: }
 3543: 
 3544: sub is_course_upload {
 3545:     my ($file,$cnum,$cdom) = @_;
 3546:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
 3547:     $uploadpath =~ s{^\/}{};
 3548:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
 3549:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
 3550:         return 1;
 3551:     }
 3552:     return;
 3553: }
 3554: 
 3555: sub in_course {
 3556:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
 3557:     if ($hideprivileged) {
 3558:         my $skipuser;
 3559:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
 3560:         my @possdoms = ($cdom);
 3561:         if ($coursehash{'checkforpriv'}) {
 3562:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 3563:         }
 3564:         if (&privileged($uname,$udom,\@possdoms)) {
 3565:             $skipuser = 1;
 3566:             if ($coursehash{'nothideprivileged'}) {
 3567:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3568:                     my $user;
 3569:                     if ($item =~ /:/) {
 3570:                         $user = $item;
 3571:                     } else {
 3572:                         $user = join(':',split(/[\@]/,$item));
 3573:                     }
 3574:                     if ($user eq $uname.':'.$udom) {
 3575:                         undef($skipuser);
 3576:                         last;
 3577:                     }
 3578:                 }
 3579:             }
 3580:             if ($skipuser) {
 3581:                 return 0;
 3582:             }
 3583:         }
 3584:     }
 3585:     $type ||= 'any';
 3586:     if (!defined($cdom) || !defined($cnum)) {
 3587:         my $cid  = $env{'request.course.id'};
 3588:         $cdom = $env{'course.'.$cid.'.domain'};
 3589:         $cnum = $env{'course.'.$cid.'.num'};
 3590:     }
 3591:     my $typesref;
 3592:     if (($type eq 'any') || ($type eq 'all')) {
 3593:         $typesref = ['active','previous','future'];
 3594:     } elsif ($type eq 'previous' || $type eq 'future') {
 3595:         $typesref = [$type];
 3596:     }
 3597:     my %roles = &get_my_roles($uname,$udom,'userroles',
 3598:                               $typesref,undef,[$cdom]);
 3599:     my ($tmp) = keys(%roles);
 3600:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
 3601:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
 3602:     if (@course_roles > 0) {
 3603:         return 1;
 3604:     }
 3605:     return 0;
 3606: }
 3607: 
 3608: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 3609: # input: action, courseID, current domain, intended
 3610: #        path to file, source of file, instruction to parse file for objects,
 3611: #        ref to hash for embedded objects,
 3612: #        ref to hash for codebase of java objects.
 3613: #        reference to scalar to accommodate mime type determined
 3614: #          from File::MMagic if $parser = parse.
 3615: #
 3616: # output: url to file (if action was uploaddoc), 
 3617: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 3618: #
 3619: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 3620: # course.
 3621: #
 3622: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3623: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 3624: #          course's home server.
 3625: #
 3626: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 3627: #          be copied from $source (current location) to 
 3628: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3629: #         and will then be copied to
 3630: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 3631: #         course's home server.
 3632: #
 3633: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3634: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 3635: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3636: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 3637: #         in course's home server.
 3638: #
 3639: 
 3640: sub process_coursefile {
 3641:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 3642:         $mimetype)=@_;
 3643:     my $fetchresult;
 3644:     my $home=&homeserver($docuname,$docudom);
 3645:     if ($action eq 'propagate') {
 3646:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3647: 			     $home);
 3648:     } else {
 3649:         my $fpath = '';
 3650:         my $fname = $file;
 3651:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3652:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3653:         my $filepath = &build_filepath($fpath);
 3654:         if ($action eq 'copy') {
 3655:             if ($source eq '') {
 3656:                 $fetchresult = 'no source file';
 3657:                 return $fetchresult;
 3658:             } else {
 3659:                 my $destination = $filepath.'/'.$fname;
 3660:                 rename($source,$destination);
 3661:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3662:                                  $home);
 3663:             }
 3664:         } elsif ($action eq 'uploaddoc') {
 3665:             open(my $fh,'>',$filepath.'/'.$fname);
 3666:             print $fh $env{'form.'.$source};
 3667:             close($fh);
 3668:             if ($parser eq 'parse') {
 3669:                 my $mm = new File::MMagic;
 3670:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 3671:                 if ($type eq 'text/html') {
 3672:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 3673:                     unless ($parse_result eq 'ok') {
 3674:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 3675:                     }
 3676:                 }
 3677:                 if (ref($mimetype)) {
 3678:                     $$mimetype = $type;
 3679:                 } 
 3680:             }
 3681:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3682:                                  $home);
 3683:             if ($fetchresult eq 'ok') {
 3684:                 return '/uploaded/'.$fpath.'/'.$fname;
 3685:             } else {
 3686:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3687:                         ' to host '.$home.': '.$fetchresult);
 3688:                 return '/adm/notfound.html';
 3689:             }
 3690:         }
 3691:     }
 3692:     unless ( $fetchresult eq 'ok') {
 3693:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3694:              ' to host '.$home.': '.$fetchresult);
 3695:     }
 3696:     return $fetchresult;
 3697: }
 3698: 
 3699: sub build_filepath {
 3700:     my ($fpath) = @_;
 3701:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 3702:     unless ($fpath eq '') {
 3703:         my @parts=split('/',$fpath);
 3704:         foreach my $part (@parts) {
 3705:             $filepath.= '/'.$part;
 3706:             if ((-e $filepath)!=1) {
 3707:                 mkdir($filepath,0777);
 3708:             }
 3709:         }
 3710:     }
 3711:     return $filepath;
 3712: }
 3713: 
 3714: sub store_edited_file {
 3715:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 3716:     my $file = $primary_url;
 3717:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 3718:     my $fpath = '';
 3719:     my $fname = $file;
 3720:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3721:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3722:     my $filepath = &build_filepath($fpath);
 3723:     open(my $fh,'>',$filepath.'/'.$fname);
 3724:     print $fh $content;
 3725:     close($fh);
 3726:     my $home=&homeserver($docuname,$docudom);
 3727:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3728: 			  $home);
 3729:     if ($$fetchresult eq 'ok') {
 3730:         return '/uploaded/'.$fpath.'/'.$fname;
 3731:     } else {
 3732:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3733: 		 ' to host '.$home.': '.$$fetchresult);
 3734:         return '/adm/notfound.html';
 3735:     }
 3736: }
 3737: 
 3738: sub clean_filename {
 3739:     my ($fname,$args)=@_;
 3740: # Replace Windows backslashes by forward slashes
 3741:     $fname=~s/\\/\//g;
 3742:     if (!$args->{'keep_path'}) {
 3743:         # Get rid of everything but the actual filename
 3744: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 3745:     }
 3746: # Replace spaces by underscores
 3747:     $fname=~s/\s+/\_/g;
 3748: # Transliterate non-ascii text to ascii
 3749:     my $lang = &Apache::lonlocal::current_language();
 3750:     $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
 3751: # Replace all other weird characters by nothing
 3752:     $fname=~s{[^/\w\.\-]}{}g;
 3753: # Replace all .\d. sequences with _\d. so they no longer look like version
 3754: # numbers
 3755:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 3756:     return $fname;
 3757: }
 3758: 
 3759: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 3760: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 3761: # image with the same aspect ratio as the original, but with dimensions which do 
 3762: # not exceed $resizewidth and $resizeheight.
 3763:  
 3764: sub resizeImage {
 3765:     my ($img_path,$resizewidth,$resizeheight) = @_;
 3766:     my $ima = Image::Magick->new;
 3767:     my $resized;
 3768:     if (-e $img_path) {
 3769:         $ima->Read($img_path);
 3770:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 3771:             my $width = $ima->Get('width');
 3772:             my $height = $ima->Get('height');
 3773:             if ($width > $resizewidth) {
 3774: 	        my $factor = $width/$resizewidth;
 3775:                 my $newheight = $height/$factor;
 3776:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 3777:                 $resized = 1;
 3778:             }
 3779:         }
 3780:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 3781:             my $width = $ima->Get('width');
 3782:             my $height = $ima->Get('height');
 3783:             if ($height > $resizeheight) {
 3784:                 my $factor = $height/$resizeheight;
 3785:                 my $newwidth = $width/$factor;
 3786:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 3787:                 $resized = 1;
 3788:             }
 3789:         }
 3790:         if ($resized) {
 3791:             $ima->Write($img_path);
 3792:         }
 3793:     }
 3794:     return;
 3795: }
 3796: 
 3797: # --------------- Take an uploaded file and put it into the userfiles directory
 3798: # input: $formname - the contents of the file are in $env{"form.$formname"}
 3799: #                    the desired filename is in $env{"form.$formname.filename"}
 3800: #        $context - possible values: coursedoc, existingfile, overwrite, 
 3801: #                                    canceloverwrite, scantron or ''. 
 3802: #                   if 'coursedoc': upload to the current course
 3803: #                   if 'existingfile': write file to tmp/overwrites directory 
 3804: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 3805: #                   $context is passed as argument to &finishuserfileupload
 3806: #        $subdir - directory in userfile to store the file into
 3807: #        $parser - instruction to parse file for objects ($parser = parse) or
 3808: #                  if context is 'scantron', $parser is hashref of csv column mapping
 3809: #                  (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3,
 3810: #                          Section => 4, CODE => 5, FirstQuestion => 9 }).
 3811: #        $allfiles - reference to hash for embedded objects
 3812: #        $codebase - reference to hash for codebase of java objects
 3813: #        $desuname - username for permanent storage of uploaded file
 3814: #        $dsetudom - domain for permanaent storage of uploaded file
 3815: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 3816: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 3817: #        $resizewidth - width (pixels) to which to resize uploaded image
 3818: #        $resizeheight - height (pixels) to which to resize uploaded image
 3819: #        $mimetype - reference to scalar to accommodate mime type determined
 3820: #                    from File::MMagic.
 3821: # 
 3822: # output: url of file in userspace, or error: <message> 
 3823: #             or /adm/notfound.html if failure to upload occurse
 3824: 
 3825: sub userfileupload {
 3826:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 3827:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 3828:     if (!defined($subdir)) { $subdir='unknown'; }
 3829:     my $fname=$env{'form.'.$formname.'.filename'};
 3830:     $fname=&clean_filename($fname);
 3831:     # See if there is anything left
 3832:     unless ($fname) { return 'error: no uploaded file'; }
 3833:     # If filename now begins with a . prepend unix timestamp _ milliseconds
 3834:     if ($fname =~ /^\./) {
 3835:         my ($s,$usec) = &gettimeofday();
 3836:         while (length($usec) < 6) {
 3837:             $usec = '0'.$usec;
 3838:         }
 3839:         $fname = $s.'_'.substr($usec,0,3).$fname;
 3840:     }
 3841:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 3842:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 3843:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 3844:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3845:         my $now = time;
 3846:         my $filepath;
 3847:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 3848:              $filepath = 'tmp/helprequests/'.$now;
 3849:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 3850:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 3851:                          '_'.$env{'user.domain'}.'/pending';
 3852:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3853:             my ($docuname,$docudom);
 3854:             if ($destudom =~ /^$match_domain$/) {
 3855:                 $docudom = $destudom;
 3856:             } else {
 3857:                 $docudom = $env{'user.domain'};
 3858:             }
 3859:             if ($destuname =~ /^$match_username$/) { 
 3860:                 $docuname = $destuname;
 3861:             } else {
 3862:                 $docuname = $env{'user.name'};
 3863:             }
 3864:             if (exists($env{'form.group'})) {
 3865:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3866:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3867:             }
 3868:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 3869:             if ($context eq 'canceloverwrite') {
 3870:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 3871:                 if (-e  $tempfile) {
 3872:                     my @info = stat($tempfile);
 3873:                     if ($info[9] eq $env{'form.timestamp'}) {
 3874:                         unlink($tempfile);
 3875:                     }
 3876:                 }
 3877:                 return;
 3878:             }
 3879:         }
 3880:         # Create the directory if not present
 3881:         my @parts=split(/\//,$filepath);
 3882:         my $fullpath = $perlvar{'lonDaemons'};
 3883:         for (my $i=0;$i<@parts;$i++) {
 3884:             $fullpath .= '/'.$parts[$i];
 3885:             if ((-e $fullpath)!=1) {
 3886:                 mkdir($fullpath,0777);
 3887:             }
 3888:         }
 3889:         open(my $fh,'>',$fullpath.'/'.$fname);
 3890:         print $fh $env{'form.'.$formname};
 3891:         close($fh);
 3892:         if ($context eq 'existingfile') {
 3893:             my @info = stat($fullpath.'/'.$fname);
 3894:             return ($fullpath.'/'.$fname,$info[9]);
 3895:         } else {
 3896:             return $fullpath.'/'.$fname;
 3897:         }
 3898:     }
 3899:     if ($subdir eq 'scantron') {
 3900:         $fname = 'scantron_orig_'.$fname;
 3901:     } else {
 3902:         $fname="$subdir/$fname";
 3903:     }
 3904:     if ($context eq 'coursedoc') {
 3905: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3906: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3907:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 3908:             return &finishuserfileupload($docuname,$docudom,
 3909: 					 $formname,$fname,$parser,$allfiles,
 3910: 					 $codebase,$thumbwidth,$thumbheight,
 3911:                                          $resizewidth,$resizeheight,$context,$mimetype);
 3912:         } else {
 3913:             if ($env{'form.folder'}) {
 3914:                 $fname=$env{'form.folder'}.'/'.$fname;
 3915:             }
 3916:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 3917: 				       $fname,$formname,$parser,
 3918: 				       $allfiles,$codebase,$mimetype);
 3919:         }
 3920:     } elsif (defined($destuname)) {
 3921:         my $docuname=$destuname;
 3922:         my $docudom=$destudom;
 3923: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3924: 				     $parser,$allfiles,$codebase,
 3925:                                      $thumbwidth,$thumbheight,
 3926:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3927:     } else {
 3928:         my $docuname=$env{'user.name'};
 3929:         my $docudom=$env{'user.domain'};
 3930:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
 3931:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3932:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3933:         }
 3934: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3935: 				     $parser,$allfiles,$codebase,
 3936:                                      $thumbwidth,$thumbheight,
 3937:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3938:     }
 3939: }
 3940: 
 3941: sub finishuserfileupload {
 3942:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 3943:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 3944:     my $path=$docudom.'/'.$docuname.'/';
 3945:     my $filepath=$perlvar{'lonDocRoot'};
 3946:   
 3947:     my ($fnamepath,$file,$fetchthumb);
 3948:     $file=$fname;
 3949:     if ($fname=~m|/|) {
 3950:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 3951: 	$path.=$fnamepath.'/';
 3952:     }
 3953:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 3954:     my $count;
 3955:     for ($count=4;$count<=$#parts;$count++) {
 3956:         $filepath.="/$parts[$count]";
 3957:         if ((-e $filepath)!=1) {
 3958: 	    mkdir($filepath,0777);
 3959:         }
 3960:     }
 3961: 
 3962: # Save the file
 3963:     {
 3964: 	if (!open(FH,'>',$filepath.'/'.$file)) {
 3965: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 3966: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 3967: 	    return '/adm/notfound.html';
 3968: 	}
 3969:         if ($context eq 'overwrite') {
 3970:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 3971:             my $target = $filepath.'/'.$file;
 3972:             if (-e $source) {
 3973:                 my @info = stat($source);
 3974:                 if ($info[9] eq $env{'form.timestamp'}) {   
 3975:                     unless (&File::Copy::move($source,$target)) {
 3976:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 3977:                         return "Moving from $source failed";
 3978:                     }
 3979:                 } else {
 3980:                     return "Temporary file: $source had unexpected date/time for last modification";
 3981:                 }
 3982:             } else {
 3983:                 return "Temporary file: $source missing";
 3984:             }
 3985:         } elsif (!print FH ($env{'form.'.$formname})) {
 3986: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 3987: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 3988: 	    return '/adm/notfound.html';
 3989: 	}
 3990: 	close(FH);
 3991:         if ($resizewidth && $resizeheight) {
 3992:             my $mm = new File::MMagic;
 3993:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 3994:             if ($mime_type =~ m{^image/}) {
 3995: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 3996:             }  
 3997: 	}
 3998:     }
 3999:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 4000:         if (ref($mimetype)) {
 4001:             if ($$mimetype eq '') {
 4002:                 my $mm = new File::MMagic;
 4003:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 4004:                 $$mimetype = $type;
 4005:             }
 4006:         }
 4007:     }
 4008:     if (($context ne 'scantron') && ($parser eq 'parse')) {
 4009:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 4010:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 4011:                                                        $allfiles,$codebase);
 4012:             unless ($parse_result eq 'ok') {
 4013:                 &logthis('Failed to parse '.$filepath.$file.
 4014: 	   	         ' for embedded media: '.$parse_result); 
 4015:             }
 4016:         }
 4017:     } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
 4018:         my $format = $env{'form.scantron_format'};
 4019:         &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
 4020:     }
 4021:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 4022:         my $input = $filepath.'/'.$file;
 4023:         my $output = $filepath.'/'.'tn-'.$file;
 4024:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 4025:         my @args = ('convert','-sample',$thumbsize,$input,$output);
 4026:         system({$args[0]} @args);
 4027:         if (-e $filepath.'/'.'tn-'.$file) {
 4028:             $fetchthumb  = 1; 
 4029:         }
 4030:     }
 4031:  
 4032: # Notify homeserver to grep it
 4033: #
 4034:     my $docuhome=&homeserver($docuname,$docudom);	
 4035:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 4036:     if ($fetchresult eq 'ok') {
 4037:         if ($fetchthumb) {
 4038:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 4039:             if ($thumbresult ne 'ok') {
 4040:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 4041:                          $docuhome.': '.$thumbresult);
 4042:             }
 4043:         }
 4044: #
 4045: # Return the URL to it
 4046:         return '/uploaded/'.$path.$file;
 4047:     } else {
 4048:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 4049: 		 ': '.$fetchresult);
 4050:         return '/adm/notfound.html';
 4051:     }
 4052: }
 4053: 
 4054: sub extract_embedded_items {
 4055:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 4056:     my @state = ();
 4057:     my (%lastids,%related,%shockwave,%flashvars);
 4058:     my %javafiles = (
 4059:                       codebase => '',
 4060:                       code => '',
 4061:                       archive => ''
 4062:                     );
 4063:     my %mediafiles = (
 4064:                       src => '',
 4065:                       movie => '',
 4066:                      );
 4067:     my $p;
 4068:     if ($content) {
 4069:         $p = HTML::LCParser->new($content);
 4070:     } else {
 4071:         $p = HTML::LCParser->new($fullpath);
 4072:     }
 4073:     while (my $t=$p->get_token()) {
 4074: 	if ($t->[0] eq 'S') {
 4075: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 4076: 	    push(@state, $tagname);
 4077:             if (lc($tagname) eq 'allow') {
 4078:                 &add_filetype($allfiles,$attr->{'src'},'src');
 4079:             }
 4080: 	    if (lc($tagname) eq 'img') {
 4081: 		&add_filetype($allfiles,$attr->{'src'},'src');
 4082: 	    }
 4083: 	    if (lc($tagname) eq 'a') {
 4084:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
 4085: 		    &add_filetype($allfiles,$attr->{'href'},'href');
 4086:                 }
 4087: 	    }
 4088:             if (lc($tagname) eq 'script') {
 4089:                 my $src;
 4090:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 4091:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 4092:                 } else {
 4093:                     if ($attr->{'src'} ne '') {
 4094:                         $src = $attr->{'src'};
 4095:                         &add_filetype($allfiles,$src,'src');
 4096:                     }
 4097:                 }
 4098:                 my $text = $p->get_trimmed_text();
 4099:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 4100:                     my @swfargs = split(/,/,$1);
 4101:                     foreach my $item (@swfargs) {
 4102:                         $item =~ s/["']//g;
 4103:                         $item =~ s/^\s+//;
 4104:                         $item =~ s/\s+$//;
 4105:                     }
 4106:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 4107:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 4108:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 4109:                         } else {
 4110:                             $related{$swfargs[0]} = [$swfargs[2]];
 4111:                         }
 4112:                     }
 4113:                 }
 4114:             }
 4115:             if (lc($tagname) eq 'link') {
 4116:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 4117:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4118:                 }
 4119:             }
 4120: 	    if (lc($tagname) eq 'object' ||
 4121: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 4122: 		foreach my $item (keys(%javafiles)) {
 4123: 		    $javafiles{$item} = '';
 4124: 		}
 4125:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 4126:                     $lastids{lc($tagname)} = $attr->{'id'};
 4127:                 }
 4128: 	    }
 4129: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 4130: 		my $name = lc($attr->{'name'});
 4131: 		foreach my $item (keys(%javafiles)) {
 4132: 		    if ($name eq $item) {
 4133: 			$javafiles{$item} = $attr->{'value'};
 4134: 			last;
 4135: 		    }
 4136: 		}
 4137:                 my $pathfrom;
 4138: 		foreach my $item (keys(%mediafiles)) {
 4139: 		    if ($name eq $item) {
 4140:                         $pathfrom = $attr->{'value'};
 4141:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 4142: 			&add_filetype($allfiles,$pathfrom,$name);
 4143: 			last;
 4144: 		    }
 4145: 		}
 4146:                 if ($name eq 'flashvars') {
 4147:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 4148:                 }
 4149:                 if ($pathfrom ne '') {
 4150:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 4151:                                          $pathfrom);
 4152:                 }
 4153: 	    }
 4154: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 4155: 		foreach my $item (keys(%javafiles)) {
 4156: 		    if ($attr->{$item}) {
 4157: 			$javafiles{$item} = $attr->{$item};
 4158: 			last;
 4159: 		    }
 4160: 		}
 4161: 		foreach my $item (keys(%mediafiles)) {
 4162: 		    if ($attr->{$item}) {
 4163: 			&add_filetype($allfiles,$attr->{$item},$item);
 4164: 			last;
 4165: 		    }
 4166: 		}
 4167:                 if (lc($tagname) eq 'embed') {
 4168:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 4169:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 4170:                                              $attr->{'src'});
 4171:                     }
 4172:                 }
 4173: 	    }
 4174:             if (lc($tagname) eq 'iframe') {
 4175:                 my $src = $attr->{'src'} ;
 4176:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
 4177:                     &add_filetype($allfiles,$src,'src');
 4178:                 } elsif ($src =~ m{^/}) {
 4179:                     if ($env{'request.course.id'}) {
 4180:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4181:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4182:                         my $url = &hreflocation('',$fullpath);
 4183:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
 4184:                             my $relpath = $1;
 4185:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
 4186:                                 &add_filetype($allfiles,$1,'src');
 4187:                             }
 4188:                         }
 4189:                     }
 4190:                 }
 4191:             }
 4192:             if ($t->[4] =~ m{/>$}) {
 4193:                 pop(@state);
 4194:             }
 4195: 	} elsif ($t->[0] eq 'E') {
 4196: 	    my ($tagname) = ($t->[1]);
 4197: 	    if ($javafiles{'codebase'} ne '') {
 4198: 		$javafiles{'codebase'} .= '/';
 4199: 	    }  
 4200: 	    if (lc($tagname) eq 'applet' ||
 4201: 		lc($tagname) eq 'object' ||
 4202: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 4203: 		) {
 4204: 		foreach my $item (keys(%javafiles)) {
 4205: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 4206: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 4207: 			&add_filetype($allfiles,$file,$item);
 4208: 		    }
 4209: 		}
 4210: 	    } 
 4211: 	    pop @state;
 4212: 	}
 4213:     }
 4214:     foreach my $id (sort(keys(%flashvars))) {
 4215:         if ($shockwave{$id} ne '') {
 4216:             my @pairs = split(/\&/,$flashvars{$id});
 4217:             foreach my $pair (@pairs) {
 4218:                 my ($key,$value) = split(/\=/,$pair);
 4219:                 if ($key eq 'thumb') {
 4220:                     &add_filetype($allfiles,$value,$key);
 4221:                 } elsif ($key eq 'content') {
 4222:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 4223:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 4224:                     if ($ext ne '') {
 4225:                         &add_filetype($allfiles,$path.$value,$ext);
 4226:                     }
 4227:                 }
 4228:             }
 4229:         }
 4230:     }
 4231:     return 'ok';
 4232: }
 4233: 
 4234: sub add_filetype {
 4235:     my ($allfiles,$file,$type)=@_;
 4236:     if (exists($allfiles->{$file})) {
 4237: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 4238: 	    push(@{$allfiles->{$file}}, &escape($type));
 4239: 	}
 4240:     } else {
 4241: 	@{$allfiles->{$file}} = (&escape($type));
 4242:     }
 4243: }
 4244: 
 4245: sub embedded_dependency {
 4246:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 4247:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 4248:         if (($identifier ne '') &&
 4249:             (ref($related->{$identifier}) eq 'ARRAY') &&
 4250:             ($pathfrom ne '')) {
 4251:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 4252:             foreach my $dep (@{$related->{$identifier}}) {
 4253:                 &add_filetype($allfiles,$path.$dep,'object');
 4254:             }
 4255:         }
 4256:     }
 4257:     return;
 4258: }
 4259: 
 4260: sub bubblesheet_converter {
 4261:     my ($cdom,$fullpath,$config,$format) = @_;
 4262:     if ((&domain($cdom) ne '') &&
 4263:         ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
 4264:         (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
 4265:         my (%csvcols,%csvoptions);
 4266:         if (ref($config->{'fields'}) eq 'HASH') {
 4267:             %csvcols = %{$config->{'fields'}};
 4268:         }
 4269:         if (ref($config->{'options'}) eq 'HASH') {
 4270:             %csvoptions = %{$config->{'options'}};
 4271:         }
 4272:         my %csvbynum = reverse(%csvcols);
 4273:         my %scantronconf = &get_scantron_config($format,$cdom);
 4274:         if (keys(%scantronconf)) {
 4275:             my %bynum = (
 4276:                           $scantronconf{CODEstart} => 'CODEstart',
 4277:                           $scantronconf{IDstart}   => 'IDstart',
 4278:                           $scantronconf{PaperID}   => 'PaperID',
 4279:                           $scantronconf{FirstName} => 'FirstName',
 4280:                           $scantronconf{LastName}  => 'LastName',
 4281:                           $scantronconf{Qstart}    => 'Qstart',
 4282:                         );
 4283:             my @ordered;
 4284:             foreach my $item (sort { $a <=> $b } keys(%bynum)) {
 4285:                 push(@ordered,$bynum{$item});
 4286:             }
 4287:             my %mapstart = (
 4288:                               CODEstart => 'CODE',
 4289:                               IDstart   => 'ID',
 4290:                               PaperID   => 'PaperID',
 4291:                               FirstName => 'FirstName',
 4292:                               LastName  => 'LastName',
 4293:                               Qstart    => 'FirstQuestion',
 4294:                            );
 4295:             my %maplength = (
 4296:                               CODEstart => 'CODElength',
 4297:                               IDstart   => 'IDlength',
 4298:                               PaperID   => 'PaperIDlength',
 4299:                               FirstName => 'FirstNamelength',
 4300:                               LastName  => 'LastNamelength',
 4301:             );
 4302:             if (open(my $fh,'<',$fullpath)) {
 4303:                 my $output;
 4304:                 my %lettdig = &letter_to_digits();
 4305:                 my %diglett = reverse(%lettdig);
 4306:                 my $numletts = scalar(keys(%lettdig));
 4307:                 my $num = 0;
 4308:                 while (my $line=<$fh>) {
 4309:                     $num ++;
 4310:                     next if (($num == 1) && ($csvoptions{'hdr'} == 1));
 4311:                     $line =~ s{[\r\n]+$}{};
 4312:                     my %found;
 4313:                     my @values = split(/,/,$line);
 4314:                     my ($qstart,$record);
 4315:                     for (my $i=0; $i<@values; $i++) {
 4316:                         if ((($qstart ne '') && ($i > $qstart)) ||
 4317:                             ($csvbynum{$i} eq 'FirstQuestion')) {
 4318:                             if ($values[$i] eq '') {
 4319:                                 $values[$i] = $scantronconf{'Qoff'};
 4320:                             } elsif ($scantronconf{'Qon'} eq 'number') {
 4321:                                 if ($values[$i] =~ /^[A-Ja-j]$/) {
 4322:                                     $values[$i] = $lettdig{uc($values[$i])};
 4323:                                 }
 4324:                             } elsif ($scantronconf{'Qon'} eq 'letter') {
 4325:                                 if ($values[$i] =~ /^[0-9]$/) {
 4326:                                     $values[$i] = $diglett{$values[$i]};
 4327:                                 }
 4328:                             } else {
 4329:                                 if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
 4330:                                     my $digit;
 4331:                                     if ($values[$i] =~ /^[A-Ja-j]$/) {
 4332:                                         $digit = $lettdig{uc($values[$i])}-1;
 4333:                                         if ($values[$i] eq 'J') {
 4334:                                             $digit += $numletts;
 4335:                                         }
 4336:                                     } elsif ($values[$i] =~ /^[0-9]$/) {
 4337:                                         $digit = $values[$i]-1;
 4338:                                         if ($values[$i] eq '0') {
 4339:                                             $digit += $numletts;
 4340:                                         }
 4341:                                     }
 4342:                                     my $qval='';
 4343:                                     for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
 4344:                                         if ($j == $digit) {
 4345:                                             $qval .= $scantronconf{'Qon'};
 4346:                                         } else {
 4347:                                             $qval .= $scantronconf{'Qoff'};
 4348:                                         }
 4349:                                     }
 4350:                                     $values[$i] = $qval;
 4351:                                 }
 4352:                             }
 4353:                             if (length($values[$i]) > $scantronconf{'Qlength'}) {
 4354:                                 $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
 4355:                             }
 4356:                             my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
 4357:                             if ($numblank > 0) {
 4358:                                  $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
 4359:                             }
 4360:                             if ($csvbynum{$i} eq 'FirstQuestion') {
 4361:                                 $qstart = $i;
 4362:                                 $found{$csvbynum{$i}} = $values[$i];
 4363:                             } else {
 4364:                                 $found{'FirstQuestion'} .= $values[$i];
 4365:                             }
 4366:                         } elsif (exists($csvbynum{$i})) {
 4367:                             if ($csvoptions{'rem'}) {
 4368:                                 $values[$i] =~ s/^\s+//;
 4369:                             }
 4370:                             if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
 4371:                                 while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
 4372:                                     $values[$i] = '0'.$values[$i];
 4373:                                 }
 4374:                             }
 4375:                             $found{$csvbynum{$i}} = $values[$i];
 4376:                         }
 4377:                     }
 4378:                     foreach my $item (@ordered) {
 4379:                         my $currlength = 1+length($record);
 4380:                         my $numspaces = $scantronconf{$item} - $currlength;
 4381:                         if ($numspaces > 0) {
 4382:                             $record .= (' ' x $numspaces);
 4383:                         }
 4384:                         if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
 4385:                             unless ($item eq 'Qstart') {
 4386:                                 if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
 4387:                                     $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
 4388:                                 }
 4389:                             }
 4390:                             $record .= $found{$mapstart{$item}};
 4391:                         }
 4392:                     }
 4393:                     $output .= "$record\n";
 4394:                 }
 4395:                 close($fh);
 4396:                 if ($output) {
 4397:                     if (open(my $fh,'>',$fullpath)) {
 4398:                         print $fh $output;
 4399:                         close($fh);
 4400:                     }
 4401:                 }
 4402:             }
 4403:         }
 4404:         return;
 4405:     }
 4406: }
 4407: 
 4408: sub letter_to_digits {
 4409:     my %lettdig = (
 4410:                     A => 1,
 4411:                     B => 2,
 4412:                     C => 3,
 4413:                     D => 4,
 4414:                     E => 5,
 4415:                     F => 6,
 4416:                     G => 7,
 4417:                     H => 8,
 4418:                     I => 9,
 4419:                     J => 0,
 4420:                   );
 4421:     return %lettdig;
 4422: }
 4423: 
 4424: sub get_scantron_config {
 4425:     my ($which,$cdom) = @_;
 4426:     my @lines = &get_scantronformat_file($cdom);
 4427:     my %config;
 4428:     #FIXME probably should move to XML it has already gotten a bit much now
 4429:     foreach my $line (@lines) {
 4430:         my ($name,$descrip)=split(/:/,$line);
 4431:         if ($name ne $which ) { next; }
 4432:         chomp($line);
 4433:         my @config=split(/:/,$line);
 4434:         $config{'name'}=$config[0];
 4435:         $config{'description'}=$config[1];
 4436:         $config{'CODElocation'}=$config[2];
 4437:         $config{'CODEstart'}=$config[3];
 4438:         $config{'CODElength'}=$config[4];
 4439:         $config{'IDstart'}=$config[5];
 4440:         $config{'IDlength'}=$config[6];
 4441:         $config{'Qstart'}=$config[7];
 4442:         $config{'Qlength'}=$config[8];
 4443:         $config{'Qoff'}=$config[9];
 4444:         $config{'Qon'}=$config[10];
 4445:         $config{'PaperID'}=$config[11];
 4446:         $config{'PaperIDlength'}=$config[12];
 4447:         $config{'FirstName'}=$config[13];
 4448:         $config{'FirstNamelength'}=$config[14];
 4449:         $config{'LastName'}=$config[15];
 4450:         $config{'LastNamelength'}=$config[16];
 4451:         $config{'BubblesPerRow'}=$config[17];
 4452:         last;
 4453:     }
 4454:     return %config;
 4455: }
 4456: 
 4457: sub get_scantronformat_file {
 4458:     my ($cdom) = @_;
 4459:     if ($cdom eq '') {
 4460:         $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
 4461:     }
 4462:     my %domconfig = &get_dom('configuration',['scantron'],$cdom);
 4463:     my $gottab = 0;
 4464:     my @lines;
 4465:     if (ref($domconfig{'scantron'}) eq 'HASH') {
 4466:         if ($domconfig{'scantron'}{'scantronformat'} ne '') {
 4467:             my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
 4468:             if ($formatfile ne '-1') {
 4469:                 @lines = split("\n",$formatfile,-1);
 4470:                 $gottab = 1;
 4471:             }
 4472:         }
 4473:     }
 4474:     if (!$gottab) {
 4475:         my $confname = $cdom.'-domainconfig';
 4476:         my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
 4477:         my $formatfile = &getfile($default);
 4478:         if ($formatfile ne '-1') {
 4479:             @lines = split("\n",$formatfile,-1);
 4480:             $gottab = 1;
 4481:         }
 4482:     }
 4483:     if (!$gottab) {
 4484:         my @domains = &current_machine_domains();
 4485:         if (grep(/^\Q$cdom\E$/,@domains)) {
 4486:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
 4487:                 @lines = <$fh>;
 4488:                 close($fh);
 4489:             }
 4490:         } else {
 4491:             if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
 4492:                 @lines = <$fh>;
 4493:                 close($fh);
 4494:             }
 4495:         }
 4496:     }
 4497:     return @lines;
 4498: }
 4499: 
 4500: sub removeuploadedurl {
 4501:     my ($url)=@_;	
 4502:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 4503:     return &removeuserfile($uname,$udom,$fname);
 4504: }
 4505: 
 4506: sub removeuserfile {
 4507:     my ($docuname,$docudom,$fname)=@_;
 4508:     my $home=&homeserver($docuname,$docudom);    
 4509:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 4510:     if ($result eq 'ok') {	
 4511:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 4512:             my $metafile = $fname.'.meta';
 4513:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 4514: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 4515:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 4516:             my $sqlresult = 
 4517:                 &update_portfolio_table($docuname,$docudom,$file,
 4518:                                         'portfolio_metadata',$group,
 4519:                                         'delete');
 4520:         }
 4521:     }
 4522:     return $result;
 4523: }
 4524: 
 4525: sub mkdiruserfile {
 4526:     my ($docuname,$docudom,$dir)=@_;
 4527:     my $home=&homeserver($docuname,$docudom);
 4528:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 4529: }
 4530: 
 4531: sub renameuserfile {
 4532:     my ($docuname,$docudom,$old,$new)=@_;
 4533:     my $home=&homeserver($docuname,$docudom);
 4534:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 4535:                         &escape("$old").':'.&escape("$new"),$home);
 4536:     if ($result eq 'ok') {
 4537:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 4538:             my $oldmeta = $old.'.meta';
 4539:             my $newmeta = $new.'.meta';
 4540:             my $metaresult = 
 4541:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 4542: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 4543:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 4544:             my $sqlresult = 
 4545:                 &update_portfolio_table($docuname,$docudom,$file,
 4546:                                         'portfolio_metadata',$group,
 4547:                                         'delete');
 4548:         }
 4549:     }
 4550:     return $result;
 4551: }
 4552: 
 4553: # ------------------------------------------------------------------------- Log
 4554: 
 4555: sub log {
 4556:     my ($dom,$nam,$hom,$what)=@_;
 4557:     return critical("log:$dom:$nam:$what",$hom);
 4558: }
 4559: 
 4560: # ------------------------------------------------------------------ Course Log
 4561: #
 4562: # This routine flushes several buffers of non-mission-critical nature
 4563: #
 4564: 
 4565: sub flushcourselogs {
 4566:     &logthis('Flushing log buffers');
 4567: #
 4568: # course logs
 4569: # This is a log of all transactions in a course, which can be used
 4570: # for data mining purposes
 4571: #
 4572: # It also collects the courseid database, which lists last transaction
 4573: # times and course titles for all courseids
 4574: #
 4575:     my %courseidbuffer=();
 4576:     foreach my $crsid (keys(%courselogs)) {
 4577:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 4578: 		          &escape($courselogs{$crsid}),
 4579: 		          $coursehombuf{$crsid}) eq 'ok') {
 4580: 	    delete $courselogs{$crsid};
 4581:         } else {
 4582:             &logthis('Failed to flush log buffer for '.$crsid);
 4583:             if (length($courselogs{$crsid})>40000) {
 4584:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 4585:                         " exceeded maximum size, deleting.</font>");
 4586:                delete $courselogs{$crsid};
 4587:             }
 4588:         }
 4589:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 4590:             'description' => $coursedescrbuf{$crsid},
 4591:             'inst_code'    => $courseinstcodebuf{$crsid},
 4592:             'type'        => $coursetypebuf{$crsid},
 4593:             'owner'       => $courseownerbuf{$crsid},
 4594:         };
 4595:     }
 4596: #
 4597: # Write course id database (reverse lookup) to homeserver of courses 
 4598: # Is used in pickcourse
 4599: #
 4600:     foreach my $crs_home (keys(%courseidbuffer)) {
 4601:         my $response = &courseidput(&host_domain($crs_home),
 4602:                                     $courseidbuffer{$crs_home},
 4603:                                     $crs_home,'timeonly');
 4604:     }
 4605: #
 4606: # File accesses
 4607: # Writes to the dynamic metadata of resources to get hit counts, etc.
 4608: #
 4609:     foreach my $entry (keys(%accesshash)) {
 4610:         if ($entry =~ /___count$/) {
 4611:             my ($dom,$name);
 4612:             ($dom,$name,undef)=
 4613: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 4614:             if (! defined($dom) || $dom eq '' || 
 4615:                 ! defined($name) || $name eq '') {
 4616:                 my $cid = $env{'request.course.id'};
 4617:                 $dom  = $env{'request.'.$cid.'.domain'};
 4618:                 $name = $env{'request.'.$cid.'.num'};
 4619:             }
 4620:             my $value = $accesshash{$entry};
 4621:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 4622:             my %temphash=($url => $value);
 4623:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 4624:             if ($result eq 'ok') {
 4625:                 delete $accesshash{$entry};
 4626:             }
 4627:         } else {
 4628:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 4629:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 4630:             my %temphash=($entry => $accesshash{$entry});
 4631:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 4632:                 delete $accesshash{$entry};
 4633:             }
 4634:         }
 4635:     }
 4636: #
 4637: # Roles
 4638: # Reverse lookup of user roles for course faculty/staff and co-authorship
 4639: #
 4640:     foreach my $entry (keys(%userrolehash)) {
 4641:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 4642: 	    split(/\:/,$entry);
 4643:         if (&Apache::lonnet::put('nohist_userroles',
 4644:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 4645:                 $rudom,$runame) eq 'ok') {
 4646: 	    delete $userrolehash{$entry};
 4647:         }
 4648:     }
 4649: #
 4650: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
 4651: #
 4652:     my %domrolebuffer = ();
 4653:     foreach my $entry (keys(%domainrolehash)) {
 4654:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 4655:         if ($domrolebuffer{$rudom}) {
 4656:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 4657:                       '='.&escape($domainrolehash{$entry});
 4658:         } else {
 4659:             $domrolebuffer{$rudom}.=&escape($entry).
 4660:                       '='.&escape($domainrolehash{$entry});
 4661:         }
 4662:         delete $domainrolehash{$entry};
 4663:     }
 4664:     foreach my $dom (keys(%domrolebuffer)) {
 4665:         my %servers;
 4666:         if (defined(&domain($dom,'primary'))) {
 4667:             my $primary=&domain($dom,'primary');
 4668:             my $hostname=&hostname($primary);
 4669:             $servers{$primary} = $hostname;
 4670:         } else {
 4671:             %servers = &get_servers($dom,'library');
 4672:         }
 4673: 	foreach my $tryserver (keys(%servers)) {
 4674: 	    if (&reply('domroleput:'.$dom.':'.
 4675: 	               $domrolebuffer{$dom},$tryserver) eq 'ok') {
 4676: 	        last;
 4677: 	    } else {
 4678: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 4679: 	    }
 4680:         }
 4681:     }
 4682:     $dumpcount++;
 4683: }
 4684: 
 4685: sub courselog {
 4686:     my $what=shift;
 4687:     $what=time.':'.$what;
 4688:     unless ($env{'request.course.id'}) { return ''; }
 4689:     $coursedombuf{$env{'request.course.id'}}=
 4690:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 4691:     $coursenumbuf{$env{'request.course.id'}}=
 4692:        $env{'course.'.$env{'request.course.id'}.'.num'};
 4693:     $coursehombuf{$env{'request.course.id'}}=
 4694:        $env{'course.'.$env{'request.course.id'}.'.home'};
 4695:     $coursedescrbuf{$env{'request.course.id'}}=
 4696:        $env{'course.'.$env{'request.course.id'}.'.description'};
 4697:     $courseinstcodebuf{$env{'request.course.id'}}=
 4698:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 4699:     $courseownerbuf{$env{'request.course.id'}}=
 4700:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 4701:     $coursetypebuf{$env{'request.course.id'}}=
 4702:        $env{'course.'.$env{'request.course.id'}.'.type'};
 4703:     if (defined $courselogs{$env{'request.course.id'}}) {
 4704: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 4705:     } else {
 4706: 	$courselogs{$env{'request.course.id'}}.=$what;
 4707:     }
 4708:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 4709: 	&flushcourselogs();
 4710:     }
 4711: }
 4712: 
 4713: sub courseacclog {
 4714:     my $fnsymb=shift;
 4715:     unless ($env{'request.course.id'}) { return ''; }
 4716:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 4717:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 4718:         $what.=':POST';
 4719:         # FIXME: Probably ought to escape things....
 4720: 	foreach my $key (keys(%env)) {
 4721:             if ($key=~/^form\.(.*)/) {
 4722:                 my $formitem = $1;
 4723:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 4724:                     $what.=':'.$formitem.'='.$env{$key};
 4725:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 4726:                     $what.=':'.$formitem.'='.$env{$key};
 4727:                 }
 4728:             }
 4729:         }
 4730:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 4731:         # FIXME: We should not be depending on a form parameter that someone
 4732:         # editing lonsearchcat.pm might change in the future.
 4733:         if ($env{'form.phase'} eq 'course_search') {
 4734:             $what.= ':POST';
 4735:             # FIXME: Probably ought to escape things....
 4736:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 4737:                                  'crsdiscuss') {
 4738:                 $what.=':'.$element.'='.$env{'form.'.$element};
 4739:             }
 4740:         }
 4741:     }
 4742:     &courselog($what);
 4743: }
 4744: 
 4745: sub countacc {
 4746:     my $url=&declutter(shift);
 4747:     return if (! defined($url) || $url eq '');
 4748:     unless ($env{'request.course.id'}) { return ''; }
 4749: #
 4750: # Mark that this url was used in this course
 4751: #
 4752:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 4753: #
 4754: # Increase the access count for this resource in this child process
 4755: #
 4756:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 4757:     $accesshash{$key}++;
 4758: }
 4759: 
 4760: sub linklog {
 4761:     my ($from,$to)=@_;
 4762:     $from=&declutter($from);
 4763:     $to=&declutter($to);
 4764:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 4765:     $accesshash{$to.'___'.$from.'___goto'}=1;
 4766: }
 4767: 
 4768: sub statslog {
 4769:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 4770:     if ($users<2) { return; }
 4771:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 4772:             'course'       => $env{'request.course.id'},
 4773:             'sections'     => '"all"',
 4774:             'num_students' => $users,
 4775:             'part'         => $part,
 4776:             'symb'         => $symb,
 4777:             'mean_tries'   => $av_attempts,
 4778:             'deg_of_diff'  => $degdiff});
 4779:     foreach my $key (keys(%dynstore)) {
 4780:         $accesshash{$key}=$dynstore{$key};
 4781:     }
 4782: }
 4783:   
 4784: sub userrolelog {
 4785:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 4786:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
 4787:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 4788:        $userrolehash
 4789:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 4790:                     =$tend.':'.$tstart;
 4791:     }
 4792:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
 4793:        $userrolehash
 4794:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 4795:                     =$tend.':'.$tstart;
 4796:     }
 4797:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
 4798:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 4799:        $domainrolehash
 4800:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 4801:                     = $tend.':'.$tstart;
 4802:     }
 4803: }
 4804: 
 4805: sub courserolelog {
 4806:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 4807:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 4808:         my $cdom = $1;
 4809:         my $cnum = $2;
 4810:         my $sec = $3;
 4811:         my $namespace = 'rolelog';
 4812:         my %storehash = (
 4813:                            role    => $trole,
 4814:                            start   => $tstart,
 4815:                            end     => $tend,
 4816:                            selfenroll => $selfenroll,
 4817:                            context    => $context,
 4818:                         );
 4819:         if ($trole eq 'gr') {
 4820:             $namespace = 'groupslog';
 4821:             $storehash{'group'} = $sec;
 4822:         } else {
 4823:             $storehash{'section'} = $sec;
 4824:         }
 4825:         &write_log('course',$namespace,\%storehash,$delflag,$username,
 4826:                    $domain,$cnum,$cdom);
 4827:         if (($trole ne 'st') || ($sec ne '')) {
 4828:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 4829:         }
 4830:     }
 4831:     return;
 4832: }
 4833: 
 4834: sub domainrolelog {
 4835:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 4836:     if ($area =~ m{^/($match_domain)/$}) {
 4837:         my $cdom = $1;
 4838:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
 4839:         my $namespace = 'rolelog';
 4840:         my %storehash = (
 4841:                            role    => $trole,
 4842:                            start   => $tstart,
 4843:                            end     => $tend,
 4844:                            context => $context,
 4845:                         );
 4846:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
 4847:                    $domain,$domconfiguser,$cdom);
 4848:     }
 4849:     return;
 4850: 
 4851: }
 4852: 
 4853: sub coauthorrolelog {
 4854:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 4855:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
 4856:         my $audom = $1;
 4857:         my $auname = $2;
 4858:         my $namespace = 'rolelog';
 4859:         my %storehash = (
 4860:                            role    => $trole,
 4861:                            start   => $tstart,
 4862:                            end     => $tend,
 4863:                            context => $context,
 4864:                         );
 4865:         &write_log('author',$namespace,\%storehash,$delflag,$username,
 4866:                    $domain,$auname,$audom);
 4867:     }
 4868:     return;
 4869: }
 4870: 
 4871: sub get_course_adv_roles {
 4872:     my ($cid,$codes) = @_;
 4873:     $cid=$env{'request.course.id'} unless (defined($cid));
 4874:     my %coursehash=&coursedescription($cid);
 4875:     my $crstype = &Apache::loncommon::course_type($cid);
 4876:     my %nothide=();
 4877:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 4878:         if ($user !~ /:/) {
 4879: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 4880:         } else {
 4881:             $nothide{$user}=1;
 4882:         }
 4883:     }
 4884:     my @possdoms = ($coursehash{'domain'});
 4885:     if ($coursehash{'checkforpriv'}) {
 4886:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 4887:     }
 4888:     my %returnhash=();
 4889:     my %dumphash=
 4890:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 4891:     my $now=time;
 4892:     my %privileged;
 4893:     foreach my $entry (keys(%dumphash)) {
 4894: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 4895:         if (($tstart) && ($tstart<0)) { next; }
 4896:         if (($tend) && ($tend<$now)) { next; }
 4897:         if (($tstart) && ($now<$tstart)) { next; }
 4898:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 4899: 	if ($username eq '' || $domain eq '') { next; }
 4900:         if ((&privileged($username,$domain,\@possdoms)) &&
 4901:             (!$nothide{$username.':'.$domain})) { next; }
 4902: 	if ($role eq 'cr') { next; }
 4903:         if ($codes) {
 4904:             if ($section) { $role .= ':'.$section; }
 4905:             if ($returnhash{$role}) {
 4906:                 $returnhash{$role}.=','.$username.':'.$domain;
 4907:             } else {
 4908:                 $returnhash{$role}=$username.':'.$domain;
 4909:             }
 4910:         } else {
 4911:             my $key=&plaintext($role,$crstype);
 4912:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 4913:             if ($returnhash{$key}) {
 4914: 	        $returnhash{$key}.=','.$username.':'.$domain;
 4915:             } else {
 4916:                 $returnhash{$key}=$username.':'.$domain;
 4917:             }
 4918:         }
 4919:     }
 4920:     return %returnhash;
 4921: }
 4922: 
 4923: sub get_my_roles {
 4924:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 4925:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 4926:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 4927:     my (%dumphash,%nothide);
 4928:     if ($context eq 'userroles') {
 4929:         %dumphash = &dump('roles',$udom,$uname);
 4930:     } else {
 4931:         %dumphash = &dump('nohist_userroles',$udom,$uname);
 4932:         if ($hidepriv) {
 4933:             my %coursehash=&coursedescription($udom.'_'.$uname);
 4934:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 4935:                 if ($user !~ /:/) {
 4936:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 4937:                 } else {
 4938:                     $nothide{$user} = 1;
 4939:                 }
 4940:             }
 4941:         }
 4942:     }
 4943:     my %returnhash=();
 4944:     my $now=time;
 4945:     my %privileged;
 4946:     foreach my $entry (keys(%dumphash)) {
 4947:         my ($role,$tend,$tstart);
 4948:         if ($context eq 'userroles') {
 4949:             next if ($entry =~ /^rolesdef/);
 4950: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 4951:         } else {
 4952:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 4953:         }
 4954:         if (($tstart) && ($tstart<0)) { next; }
 4955:         my $status = 'active';
 4956:         if (($tend) && ($tend<=$now)) {
 4957:             $status = 'previous';
 4958:         } 
 4959:         if (($tstart) && ($now<$tstart)) {
 4960:             $status = 'future';
 4961:         }
 4962:         if (ref($types) eq 'ARRAY') {
 4963:             if (!grep(/^\Q$status\E$/,@{$types})) {
 4964:                 next;
 4965:             } 
 4966:         } else {
 4967:             if ($status ne 'active') {
 4968:                 next;
 4969:             }
 4970:         }
 4971:         my ($rolecode,$username,$domain,$section,$area);
 4972:         if ($context eq 'userroles') {
 4973:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
 4974:             (undef,$domain,$username,$section) = split(/\//,$area);
 4975:         } else {
 4976:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 4977:         }
 4978:         if (ref($roledoms) eq 'ARRAY') {
 4979:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 4980:                 next;
 4981:             }
 4982:         }
 4983:         if (ref($roles) eq 'ARRAY') {
 4984:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 4985:                 if ($role =~ /^cr\//) {
 4986:                     if (!grep(/^cr$/,@{$roles})) {
 4987:                         next;
 4988:                     }
 4989:                 } elsif ($role =~ /^gr\//) {
 4990:                     if (!grep(/^gr$/,@{$roles})) {
 4991:                         next;
 4992:                     }
 4993:                 } else {
 4994:                     next;
 4995:                 }
 4996:             }
 4997:         }
 4998:         if ($hidepriv) {
 4999:             my @privroles = ('dc','su');
 5000:             if ($context eq 'userroles') {
 5001:                 next if (grep(/^\Q$role\E$/,@privroles));
 5002:             } else {
 5003:                 my $possdoms = [$domain];
 5004:                 if (ref($roledoms) eq 'ARRAY') {
 5005:                    push(@{$possdoms},@{$roledoms});
 5006:                 }
 5007:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
 5008:                     if (!$nothide{$username.':'.$domain}) {
 5009:                         next;
 5010:                     }
 5011:                 }
 5012:             }
 5013:         }
 5014:         if ($withsec) {
 5015:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 5016:                 $tstart.':'.$tend;
 5017:         } else {
 5018:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 5019:         }
 5020:     }
 5021:     return %returnhash;
 5022: }
 5023: 
 5024: sub get_all_adhocroles {
 5025:     my ($dom) = @_;
 5026:     my @roles_by_num = ();
 5027:     my %domdefaults = &get_domain_defaults($dom);
 5028:     my (%description,%access_in_dom,%access_info);
 5029:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
 5030:         my $count = 0;
 5031:         my %domcurrent = %{$domdefaults{'adhocroles'}};
 5032:         my %ordered;
 5033:         foreach my $role (sort(keys(%domcurrent))) {
 5034:             my ($order,$desc,$access_in_dom);
 5035:             if (ref($domcurrent{$role}) eq 'HASH') {
 5036:                 $order = $domcurrent{$role}{'order'};
 5037:                 $desc = $domcurrent{$role}{'desc'};
 5038:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
 5039:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
 5040:             }
 5041:             if ($order eq '') {
 5042:                 $order = $count;
 5043:             }
 5044:             $ordered{$order} = $role;
 5045:             if ($desc ne '') {
 5046:                 $description{$role} = $desc;
 5047:             } else {
 5048:                 $description{$role}= $role;
 5049:             }
 5050:             $count++;
 5051:         }
 5052:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 5053:             push(@roles_by_num,$ordered{$item});
 5054:         }
 5055:     }
 5056:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
 5057: }
 5058: 
 5059: sub get_my_adhocroles {
 5060:     my ($cid,$checkreg) = @_;
 5061:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
 5062:     if ($env{'request.course.id'} eq $cid) {
 5063:         $cdom = $env{'course.'.$cid.'.domain'};
 5064:         $cnum = $env{'course.'.$cid.'.num'};
 5065:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
 5066:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
 5067:         $cdom = $1;
 5068:         $cnum = $2;
 5069:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
 5070:                                      $cdom,$cnum);
 5071:     }
 5072:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
 5073:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
 5074:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
 5075:         if ($rosterhash{$user} ne '') {
 5076:             my $type = (split(/:/,$rosterhash{$user}))[5];
 5077:             return ([],{}) if ($type eq 'auto');
 5078:         }
 5079:     }
 5080:     if (($cdom ne '') && ($cnum ne ''))  {
 5081:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
 5082:             my $then=$env{'user.login.time'};
 5083:             my $update=$env{'user.update.time'};
 5084:             if (!$update) {
 5085:                 $update = $then;
 5086:             }
 5087:             my @liveroles;
 5088:             foreach my $role ('dh','da') {
 5089:                 if ($env{"user.role.$role./$cdom/"}) {
 5090:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
 5091:                     my $limit = $update;
 5092:                     if ($env{'request.role'} eq "$role./$cdom/") {
 5093:                         $limit = $then;
 5094:                     }
 5095:                     my $activerole = 1;
 5096:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
 5097:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
 5098:                     if ($activerole) {
 5099:                         push(@liveroles,$role);
 5100:                     }
 5101:                 }
 5102:             }
 5103:             if (@liveroles) {
 5104:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
 5105:                     my ($accessref,$accessinfo,%access_in_dom);
 5106:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
 5107:                     if (ref($roles_by_num) eq 'ARRAY') {
 5108:                         if (@{$roles_by_num}) {
 5109:                             my %settings;
 5110:                             if ($env{'request.course.id'} eq $cid) {
 5111:                                 foreach my $envkey (keys(%env)) {
 5112:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
 5113:                                         $settings{$1} = $env{$envkey};
 5114:                                     }
 5115:                                 }
 5116:                             } else {
 5117:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
 5118:                             }
 5119:                             my %setincrs;
 5120:                             if ($settings{'internal.adhocaccess'}) {
 5121:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
 5122:                             }
 5123:                             my @statuses;
 5124:                             if ($env{'environment.inststatus'}) {
 5125:                                 @statuses = split(/,/,$env{'environment.inststatus'});
 5126:                             }
 5127:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
 5128:                             if (ref($accessref) eq 'HASH') {
 5129:                                 %access_in_dom = %{$accessref};
 5130:                             }
 5131:                             foreach my $role (@{$roles_by_num}) {
 5132:                                 my ($curraccess,@okstatus,@personnel);
 5133:                                 if ($setincrs{$role}) {
 5134:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
 5135:                                     if ($curraccess eq 'status') {
 5136:                                         @okstatus = split(/\&/,$rest);
 5137:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5138:                                         @personnel = split(/\&/,$rest);
 5139:                                     }
 5140:                                 } else {
 5141:                                     $curraccess = $access_in_dom{$role};
 5142:                                     if (ref($accessinfo) eq 'HASH') {
 5143:                                         if ($curraccess eq 'status') {
 5144:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 5145:                                                 @okstatus = @{$accessinfo->{$role}};
 5146:                                             }
 5147:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5148:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 5149:                                                 @personnel = @{$accessinfo->{$role}};
 5150:                                             }
 5151:                                         }
 5152:                                     }
 5153:                                 }
 5154:                                 if ($curraccess eq 'none') {
 5155:                                     next;
 5156:                                 } elsif ($curraccess eq 'all') {
 5157:                                     push(@possroles,$role);
 5158:                                 } elsif ($curraccess eq 'dh') {
 5159:                                     if (grep(/^dh$/,@liveroles)) {
 5160:                                         push(@possroles,$role);
 5161:                                     } else {
 5162:                                         next;
 5163:                                     }
 5164:                                 } elsif ($curraccess eq 'da') {
 5165:                                     if (grep(/^da$/,@liveroles)) {
 5166:                                         push(@possroles,$role);
 5167:                                     } else {
 5168:                                         next;
 5169:                                     }
 5170:                                 } elsif ($curraccess eq 'status') {
 5171:                                     if (@okstatus) {
 5172:                                         if (!@statuses) {
 5173:                                             if (grep(/^default$/,@okstatus)) {
 5174:                                                 push(@possroles,$role);
 5175:                                             }
 5176:                                         } else {
 5177:                                             foreach my $status (@okstatus) {
 5178:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
 5179:                                                     push(@possroles,$role);
 5180:                                                     last;
 5181:                                                 }
 5182:                                             }
 5183:                                         }
 5184:                                     }
 5185:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 5186:                                     if (grep(/^\Q$user\E$/,@personnel)) {
 5187:                                         if ($curraccess eq 'exc') {
 5188:                                             push(@possroles,$role);
 5189:                                         }
 5190:                                     } elsif ($curraccess eq 'inc') {
 5191:                                         push(@possroles,$role);
 5192:                                     }
 5193:                                 }
 5194:                             }
 5195:                         }
 5196:                     }
 5197:                 }
 5198:             }
 5199:         }
 5200:     }
 5201:     unless (ref($description) eq 'HASH') {
 5202:         if (ref($roles_by_num) eq 'ARRAY') {
 5203:             my %desc;
 5204:             map { $desc{$_} = $_; } (@{$roles_by_num});
 5205:             $description = \%desc;
 5206:         } else {
 5207:             $description = {};
 5208:         }
 5209:     }
 5210:     return (\@possroles,$description);
 5211: }
 5212: 
 5213: # ----------------------------------------------------- Frontpage Announcements
 5214: #
 5215: #
 5216: 
 5217: sub postannounce {
 5218:     my ($server,$text)=@_;
 5219:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 5220:     unless ($text=~/\w/) { $text=''; }
 5221:     return &reply('setannounce:'.&escape($text),$server);
 5222: }
 5223: 
 5224: sub getannounce {
 5225: 
 5226:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 5227: 	my $announcement='';
 5228: 	while (my $line = <$fh>) { $announcement .= $line; }
 5229: 	close($fh);
 5230: 	if ($announcement=~/\w/) { 
 5231: 	    return 
 5232:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 5233:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 5234: 	} else {
 5235: 	    return '';
 5236: 	}
 5237:     } else {
 5238: 	return '';
 5239:     }
 5240: }
 5241: 
 5242: # ---------------------------------------------------------- Course ID routines
 5243: # Deal with domain's nohist_courseid.db files
 5244: #
 5245: 
 5246: sub courseidput {
 5247:     my ($domain,$storehash,$coursehome,$caller) = @_;
 5248:     return unless (ref($storehash) eq 'HASH');
 5249:     my $outcome;
 5250:     if ($caller eq 'timeonly') {
 5251:         my $cids = '';
 5252:         foreach my $item (keys(%$storehash)) {
 5253:             $cids.=&escape($item).'&';
 5254:         }
 5255:         $cids=~s/\&$//;
 5256:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 5257:                           $coursehome);       
 5258:     } else {
 5259:         my $items = '';
 5260:         foreach my $item (keys(%$storehash)) {
 5261:             $items.= &escape($item).'='.
 5262:                      &freeze_escape($$storehash{$item}).'&';
 5263:         }
 5264:         $items=~s/\&$//;
 5265:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 5266:                           $coursehome);
 5267:     }
 5268:     if ($outcome eq 'unknown_cmd') {
 5269:         my $what;
 5270:         foreach my $cid (keys(%$storehash)) {
 5271:             $what .= &escape($cid).'=';
 5272:             foreach my $item ('description','inst_code','owner','type') {
 5273:                 $what .= &escape($storehash->{$cid}{$item}).':';
 5274:             }
 5275:             $what =~ s/\:$/&/;
 5276:         }
 5277:         $what =~ s/\&$//;  
 5278:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 5279:     } else {
 5280:         return $outcome;
 5281:     }
 5282: }
 5283: 
 5284: sub courseiddump {
 5285:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 5286:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 5287:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 5288:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
 5289:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
 5290:     my $as_hash = 1;
 5291:     my %returnhash;
 5292:     if (!$domfilter) { $domfilter=''; }
 5293:     my %libserv = &all_library();
 5294:     foreach my $tryserver (keys(%libserv)) {
 5295:         if ( (  $hostidflag == 1 
 5296: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 5297: 	     || (!defined($hostidflag)) ) {
 5298: 
 5299: 	    if (($domfilter eq '') ||
 5300: 		(&host_domain($tryserver) eq $domfilter)) {
 5301:                 my $rep;
 5302:                 if (grep { $_ eq $tryserver } &current_machine_ids()) {
 5303:                     $rep = &LONCAPA::Lond::dump_course_id_handler(
 5304:                         join(":", (&host_domain($tryserver), $sincefilter,
 5305:                                 &escape($descfilter), &escape($instcodefilter),
 5306:                                 &escape($ownerfilter), &escape($coursefilter),
 5307:                                 &escape($typefilter), &escape($regexp_ok),
 5308:                                 $as_hash, &escape($selfenrollonly),
 5309:                                 &escape($catfilter), $showhidden, $caller,
 5310:                                 &escape($cloner), &escape($cc_clone), $cloneonly,
 5311:                                 &escape($createdbefore), &escape($createdafter),
 5312:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
 5313:                                 $reqcrsdom,&escape($reqinstcode))));
 5314:                 } else {
 5315:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
 5316:                              $sincefilter.':'.&escape($descfilter).':'.
 5317:                              &escape($instcodefilter).':'.&escape($ownerfilter).
 5318:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
 5319:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
 5320:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
 5321:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
 5322:                              &escape($cc_clone).':'.$cloneonly.':'.
 5323:                              &escape($createdbefore).':'.&escape($createdafter).':'.
 5324:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
 5325:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
 5326:                 }
 5327: 
 5328:                 my @pairs=split(/\&/,$rep);
 5329:                 foreach my $item (@pairs) {
 5330:                     my ($key,$value)=split(/\=/,$item,2);
 5331:                     $key = &unescape($key);
 5332:                     next if ($key =~ /^error: 2 /);
 5333:                     my $result = &thaw_unescape($value);
 5334:                     if (ref($result) eq 'HASH') {
 5335:                         $returnhash{$key}=$result;
 5336:                     } else {
 5337:                         my @responses = split(/:/,$value);
 5338:                         my @items = ('description','inst_code','owner','type');
 5339:                         for (my $i=0; $i<@responses; $i++) {
 5340:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 5341:                         }
 5342:                     }
 5343:                 }
 5344:             }
 5345:         }
 5346:     }
 5347:     return %returnhash;
 5348: }
 5349: 
 5350: sub courselastaccess {
 5351:     my ($cdom,$cnum,$hostidref) = @_;
 5352:     my %returnhash;
 5353:     if ($cdom && $cnum) {
 5354:         my $chome = &homeserver($cnum,$cdom);
 5355:         if ($chome ne 'no_host') {
 5356:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 5357:             &extract_lastaccess(\%returnhash,$rep);
 5358:         }
 5359:     } else {
 5360:         if (!$cdom) { $cdom=''; }
 5361:         my %libserv = &all_library();
 5362:         foreach my $tryserver (keys(%libserv)) {
 5363:             if (ref($hostidref) eq 'ARRAY') {
 5364:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 5365:             } 
 5366:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 5367:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 5368:                 &extract_lastaccess(\%returnhash,$rep);
 5369:             }
 5370:         }
 5371:     }
 5372:     return %returnhash;
 5373: }
 5374: 
 5375: sub extract_lastaccess {
 5376:     my ($returnhash,$rep) = @_;
 5377:     if (ref($returnhash) eq 'HASH') {
 5378:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 5379:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 5380:                  $rep eq '') {
 5381:             my @pairs=split(/\&/,$rep);
 5382:             foreach my $item (@pairs) {
 5383:                 my ($key,$value)=split(/\=/,$item,2);
 5384:                 $key = &unescape($key);
 5385:                 next if ($key =~ /^error: 2 /);
 5386:                 $returnhash->{$key} = &thaw_unescape($value);
 5387:             }
 5388:         }
 5389:     }
 5390:     return;
 5391: }
 5392: 
 5393: # ---------------------------------------------------------- DC e-mail
 5394: 
 5395: sub dcmailput {
 5396:     my ($domain,$msgid,$message,$server)=@_;
 5397:     my $status = &Apache::lonnet::critical(
 5398:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 5399:        &escape($message),$server);
 5400:     return $status;
 5401: }
 5402: 
 5403: sub dcmaildump {
 5404:     my ($dom,$startdate,$enddate,$senders) = @_;
 5405:     my %returnhash=();
 5406: 
 5407:     if (defined(&domain($dom,'primary'))) {
 5408:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 5409:                                                          &escape($enddate).':';
 5410: 	my @esc_senders=map { &escape($_)} @$senders;
 5411: 	$cmd.=&escape(join('&',@esc_senders));
 5412: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 5413:             my ($key,$value) = split(/\=/,$line,2);
 5414:             if (($key) && ($value)) {
 5415:                 $returnhash{&unescape($key)} = &unescape($value);
 5416:             }
 5417:         }
 5418:     }
 5419:     return %returnhash;
 5420: }
 5421: # ---------------------------------------------------------- Domain roles
 5422: 
 5423: sub get_domain_roles {
 5424:     my ($dom,$roles,$startdate,$enddate)=@_;
 5425:     if ((!defined($startdate)) || ($startdate eq '')) {
 5426:         $startdate = '.';
 5427:     }
 5428:     if ((!defined($enddate)) || ($enddate eq '')) {
 5429:         $enddate = '.';
 5430:     }
 5431:     my $rolelist;
 5432:     if (ref($roles) eq 'ARRAY') {
 5433:         $rolelist = join('&',@{$roles});
 5434:     }
 5435:     my %personnel = ();
 5436: 
 5437:     my %servers = &get_servers($dom,'library');
 5438:     foreach my $tryserver (keys(%servers)) {
 5439: 	%{$personnel{$tryserver}}=();
 5440: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 5441: 					    &escape($startdate).':'.
 5442: 					    &escape($enddate).':'.
 5443: 					    &escape($rolelist), $tryserver))) {
 5444: 	    my ($key,$value) = split(/\=/,$line,2);
 5445: 	    if (($key) && ($value)) {
 5446: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 5447: 	    }
 5448: 	}
 5449:     }
 5450:     return %personnel;
 5451: }
 5452: 
 5453: sub get_active_domroles {
 5454:     my ($dom,$roles) = @_;
 5455:     return () unless (ref($roles) eq 'ARRAY');
 5456:     my $now = time;
 5457:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
 5458:     my %domroles;
 5459:     foreach my $server (keys(%dompersonnel)) {
 5460:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
 5461:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
 5462:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
 5463:         }
 5464:     }
 5465:     return %domroles;
 5466: }
 5467: 
 5468: # ----------------------------------------------------------- Interval timing 
 5469: 
 5470: {
 5471: # Caches needed for speedup of navmaps
 5472: # We don't want to cache this for very long at all (5 seconds at most)
 5473: # 
 5474: # The user for whom we cache
 5475: my $cachedkey='';
 5476: # The cached times for this user
 5477: my %cachedtimes=();
 5478: # When this was last done
 5479: my $cachedtime='';
 5480: 
 5481: sub load_all_first_access {
 5482:     my ($uname,$udom,$ignorecache)=@_;
 5483:     if (($cachedkey eq $uname.':'.$udom) &&
 5484:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
 5485:         (!$ignorecache)) {
 5486:         return;
 5487:     }
 5488:     $cachedtime=time;
 5489:     $cachedkey=$uname.':'.$udom;
 5490:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 5491: }
 5492: 
 5493: sub get_first_access {
 5494:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
 5495:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 5496:     if ($argsymb) { $symb=$argsymb; }
 5497:     my ($map,$id,$res)=&decode_symb($symb);
 5498:     if ($argmap) { $map = $argmap; }
 5499:     if ($type eq 'course') {
 5500: 	$res='course';
 5501:     } elsif ($type eq 'map') {
 5502: 	$res=&symbread($map);
 5503:     } else {
 5504: 	$res=$symb;
 5505:     }
 5506:     &load_all_first_access($uname,$udom,$ignorecache);
 5507:     return $cachedtimes{"$courseid\0$res"};
 5508: }
 5509: 
 5510: sub set_first_access {
 5511:     my ($type,$interval)=@_;
 5512:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 5513:     my ($map,$id,$res)=&decode_symb($symb);
 5514:     if ($type eq 'course') {
 5515: 	$res='course';
 5516:     } elsif ($type eq 'map') {
 5517: 	$res=&symbread($map);
 5518:     } else {
 5519: 	$res=$symb;
 5520:     }
 5521:     $cachedkey='';
 5522:     my $firstaccess=&get_first_access($type,$symb,$map);
 5523:     if ($firstaccess) {
 5524:         &logthis("First access time already set ($firstaccess) when attempting ".
 5525:                  "to set new value (type: $type, extent: $res) for $uname:$udom ".
 5526:                  "in $courseid");
 5527:         return 'already_set';
 5528:     } else {
 5529:         my $start = time;
 5530: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 5531:                           $udom,$uname);
 5532:         if ($putres eq 'ok') {
 5533:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 5534:                  $udom,$uname); 
 5535:             &appenv(
 5536:                      {
 5537:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 5538:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 5539:                      }
 5540:                   );
 5541:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
 5542:                 $cachedtimes{"$courseid\0$res"} = $start;
 5543:             }
 5544:         } elsif ($putres ne 'refused') {
 5545:             &logthis("Result: $putres when attempting to set first access time ".
 5546:                      "(type: $type, extent: $res) for $uname:$udom in $courseid");
 5547:         }
 5548:         return $putres;
 5549:     }
 5550:     return 'already_set';
 5551: }
 5552: }
 5553: 
 5554: sub checkout {
 5555:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
 5556:     my $now=time;
 5557:     my $lonhost=$perlvar{'lonHostID'};
 5558:     my $infostr=&escape(
 5559:                  'CHECKOUTTOKEN&'.
 5560:                  $tuname.'&'.
 5561:                  $tudom.'&'.
 5562:                  $tcrsid.'&'.
 5563:                  $symb.'&'.
 5564:                  $now.'&'.$ENV{'REMOTE_ADDR'});
 5565:     my $token=&reply('tmpput:'.$infostr,$lonhost);
 5566:     if ($token=~/^error\:/) {
 5567:         &logthis("<font color=\"blue\">WARNING: ".
 5568:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
 5569:                  "</font>");
 5570:         return '';
 5571:     }
 5572: 
 5573:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
 5574:     $token=~tr/a-z/A-Z/;
 5575: 
 5576:     my %infohash=('resource.0.outtoken' => $token,
 5577:                   'resource.0.checkouttime' => $now,
 5578:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
 5579: 
 5580:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 5581:        return '';
 5582:     } else {
 5583:         &logthis("<font color=\"blue\">WARNING: ".
 5584:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
 5585:                  "</font>");
 5586:     }
 5587: 
 5588:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 5589:                          &escape('Checkout '.$infostr.' - '.
 5590:                                                  $token)) ne 'ok') {
 5591:         return '';
 5592:     } else {
 5593:         &logthis("<font color=\"blue\">WARNING: ".
 5594:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
 5595:                  "</font>");
 5596:     }
 5597:     return $token;
 5598: }
 5599: 
 5600: # ------------------------------------------------------------ Check in an item
 5601: 
 5602: sub checkin {
 5603:     my $token=shift;
 5604:     my $now=time;
 5605:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
 5606:     $lonhost=~tr/A-Z/a-z/;
 5607:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
 5608:     $dtoken=~s/\W/\_/g;
 5609:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
 5610:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
 5611: 
 5612:     unless (($tuname) && ($tudom)) {
 5613:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
 5614:         return '';
 5615:     }
 5616: 
 5617:     unless (&allowed('mgr',$tcrsid)) {
 5618:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
 5619:                  $env{'user.name'}.' - '.$env{'user.domain'});
 5620:         return '';
 5621:     }
 5622: 
 5623:     my %infohash=('resource.0.intoken' => $token,
 5624:                   'resource.0.checkintime' => $now,
 5625:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
 5626: 
 5627:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 5628:        return '';
 5629:     }
 5630: 
 5631:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 5632:                          &escape('Checkin - '.$token)) ne 'ok') {
 5633:         return '';
 5634:     }
 5635: 
 5636:     return ($symb,$tuname,$tudom,$tcrsid);
 5637: }
 5638: 
 5639: # --------------------------------------------- Set Expire Date for Spreadsheet
 5640: 
 5641: sub expirespread {
 5642:     my ($uname,$udom,$stype,$usymb)=@_;
 5643:     my $cid=$env{'request.course.id'}; 
 5644:     if ($cid) {
 5645:        my $now=time;
 5646:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 5647:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 5648:                             $env{'course.'.$cid.'.num'}.
 5649: 	        	    ':nohist_expirationdates:'.
 5650:                             &escape($key).'='.$now,
 5651:                             $env{'course.'.$cid.'.home'})
 5652:     }
 5653:     return 'ok';
 5654: }
 5655: 
 5656: # ----------------------------------------------------- Devalidate Spreadsheets
 5657: 
 5658: sub devalidate {
 5659:     my ($symb,$uname,$udom)=@_;
 5660:     my $cid=$env{'request.course.id'}; 
 5661:     if ($cid) {
 5662:         # delete the stored spreadsheets for
 5663:         # - the student level sheet of this user in course's homespace
 5664:         # - the assessment level sheet for this resource 
 5665:         #   for this user in user's homespace
 5666: 	# - current conditional state info
 5667: 	my $key=$uname.':'.$udom.':';
 5668:         my $status=
 5669: 	    &del('nohist_calculatedsheets',
 5670: 		 [$key.'studentcalc:'],
 5671: 		 $env{'course.'.$cid.'.domain'},
 5672: 		 $env{'course.'.$cid.'.num'})
 5673: 		.' '.
 5674: 	    &del('nohist_calculatedsheets_'.$cid,
 5675: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 5676:         unless ($status eq 'ok ok') {
 5677:            &logthis('Could not devalidate spreadsheet '.
 5678:                     $uname.' at '.$udom.' for '.
 5679: 		    $symb.': '.$status);
 5680:         }
 5681: 	&delenv('user.state.'.$cid);
 5682:     }
 5683: }
 5684: 
 5685: sub get_scalar {
 5686:     my ($string,$end) = @_;
 5687:     my $value;
 5688:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 5689: 	$value = $1;
 5690:     } elsif ($$string =~ s/^([^&]*?)&//) {
 5691: 	$value = $1;
 5692:     }
 5693:     return &unescape($value);
 5694: }
 5695: 
 5696: sub array2str {
 5697:   my (@array) = @_;
 5698:   my $result=&arrayref2str(\@array);
 5699:   $result=~s/^__ARRAY_REF__//;
 5700:   $result=~s/__END_ARRAY_REF__$//;
 5701:   return $result;
 5702: }
 5703: 
 5704: sub arrayref2str {
 5705:   my ($arrayref) = @_;
 5706:   my $result='__ARRAY_REF__';
 5707:   foreach my $elem (@$arrayref) {
 5708:     if(ref($elem) eq 'ARRAY') {
 5709:       $result.=&arrayref2str($elem).'&';
 5710:     } elsif(ref($elem) eq 'HASH') {
 5711:       $result.=&hashref2str($elem).'&';
 5712:     } elsif(ref($elem)) {
 5713:       #print("Got a ref of ".(ref($elem))." skipping.");
 5714:     } else {
 5715:       $result.=&escape($elem).'&';
 5716:     }
 5717:   }
 5718:   $result=~s/\&$//;
 5719:   $result .= '__END_ARRAY_REF__';
 5720:   return $result;
 5721: }
 5722: 
 5723: sub hash2str {
 5724:   my (%hash) = @_;
 5725:   my $result=&hashref2str(\%hash);
 5726:   $result=~s/^__HASH_REF__//;
 5727:   $result=~s/__END_HASH_REF__$//;
 5728:   return $result;
 5729: }
 5730: 
 5731: sub hashref2str {
 5732:   my ($hashref)=@_;
 5733:   my $result='__HASH_REF__';
 5734:   foreach my $key (sort(keys(%$hashref))) {
 5735:     if (ref($key) eq 'ARRAY') {
 5736:       $result.=&arrayref2str($key).'=';
 5737:     } elsif (ref($key) eq 'HASH') {
 5738:       $result.=&hashref2str($key).'=';
 5739:     } elsif (ref($key)) {
 5740:       $result.='=';
 5741:       #print("Got a ref of ".(ref($key))." skipping.");
 5742:     } else {
 5743: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 5744:     }
 5745: 
 5746:     if(ref($hashref->{$key}) eq 'ARRAY') {
 5747:       $result.=&arrayref2str($hashref->{$key}).'&';
 5748:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 5749:       $result.=&hashref2str($hashref->{$key}).'&';
 5750:     } elsif(ref($hashref->{$key})) {
 5751:        $result.='&';
 5752:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 5753:     } else {
 5754:       $result.=&escape($hashref->{$key}).'&';
 5755:     }
 5756:   }
 5757:   $result=~s/\&$//;
 5758:   $result .= '__END_HASH_REF__';
 5759:   return $result;
 5760: }
 5761: 
 5762: sub str2hash {
 5763:     my ($string)=@_;
 5764:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 5765:     return %$hash;
 5766: }
 5767: 
 5768: sub str2hashref {
 5769:   my ($string) = @_;
 5770: 
 5771:   my %hash;
 5772: 
 5773:   if($string !~ /^__HASH_REF__/) {
 5774:       if (! ($string eq '' || !defined($string))) {
 5775: 	  $hash{'error'}='Not hash reference';
 5776:       }
 5777:       return (\%hash, $string);
 5778:   }
 5779: 
 5780:   $string =~ s/^__HASH_REF__//;
 5781: 
 5782:   while($string !~ /^__END_HASH_REF__/) {
 5783:       #key
 5784:       my $key='';
 5785:       if($string =~ /^__HASH_REF__/) {
 5786:           ($key, $string)=&str2hashref($string);
 5787:           if(defined($key->{'error'})) {
 5788:               $hash{'error'}='Bad data';
 5789:               return (\%hash, $string);
 5790:           }
 5791:       } elsif($string =~ /^__ARRAY_REF__/) {
 5792:           ($key, $string)=&str2arrayref($string);
 5793:           if($key->[0] eq 'Array reference error') {
 5794:               $hash{'error'}='Bad data';
 5795:               return (\%hash, $string);
 5796:           }
 5797:       } else {
 5798:           $string =~ s/^(.*?)=//;
 5799: 	  $key=&unescape($1);
 5800:       }
 5801:       $string =~ s/^=//;
 5802: 
 5803:       #value
 5804:       my $value='';
 5805:       if($string =~ /^__HASH_REF__/) {
 5806:           ($value, $string)=&str2hashref($string);
 5807:           if(defined($value->{'error'})) {
 5808:               $hash{'error'}='Bad data';
 5809:               return (\%hash, $string);
 5810:           }
 5811:       } elsif($string =~ /^__ARRAY_REF__/) {
 5812:           ($value, $string)=&str2arrayref($string);
 5813:           if($value->[0] eq 'Array reference error') {
 5814:               $hash{'error'}='Bad data';
 5815:               return (\%hash, $string);
 5816:           }
 5817:       } else {
 5818: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 5819:       }
 5820:       $string =~ s/^&//;
 5821: 
 5822:       $hash{$key}=$value;
 5823:   }
 5824: 
 5825:   $string =~ s/^__END_HASH_REF__//;
 5826: 
 5827:   return (\%hash, $string);
 5828: }
 5829: 
 5830: sub str2array {
 5831:     my ($string)=@_;
 5832:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 5833:     return @$array;
 5834: }
 5835: 
 5836: sub str2arrayref {
 5837:   my ($string) = @_;
 5838:   my @array;
 5839: 
 5840:   if($string !~ /^__ARRAY_REF__/) {
 5841:       if (! ($string eq '' || !defined($string))) {
 5842: 	  $array[0]='Array reference error';
 5843:       }
 5844:       return (\@array, $string);
 5845:   }
 5846: 
 5847:   $string =~ s/^__ARRAY_REF__//;
 5848: 
 5849:   while($string !~ /^__END_ARRAY_REF__/) {
 5850:       my $value='';
 5851:       if($string =~ /^__HASH_REF__/) {
 5852:           ($value, $string)=&str2hashref($string);
 5853:           if(defined($value->{'error'})) {
 5854:               $array[0] ='Array reference error';
 5855:               return (\@array, $string);
 5856:           }
 5857:       } elsif($string =~ /^__ARRAY_REF__/) {
 5858:           ($value, $string)=&str2arrayref($string);
 5859:           if($value->[0] eq 'Array reference error') {
 5860:               $array[0] ='Array reference error';
 5861:               return (\@array, $string);
 5862:           }
 5863:       } else {
 5864: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 5865:       }
 5866:       $string =~ s/^&//;
 5867: 
 5868:       push(@array, $value);
 5869:   }
 5870: 
 5871:   $string =~ s/^__END_ARRAY_REF__//;
 5872: 
 5873:   return (\@array, $string);
 5874: }
 5875: 
 5876: # -------------------------------------------------------------------Temp Store
 5877: 
 5878: sub tmpreset {
 5879:   my ($symb,$namespace,$domain,$stuname) = @_;
 5880:   if (!$symb) {
 5881:     $symb=&symbread();
 5882:     if (!$symb) { $symb= $env{'request.url'}; }
 5883:   }
 5884:   $symb=escape($symb);
 5885: 
 5886:   if (!$namespace) { $namespace=$env{'request.state'}; }
 5887:   $namespace=~s/\//\_/g;
 5888:   $namespace=~s/\W//g;
 5889: 
 5890:   if (!$domain) { $domain=$env{'user.domain'}; }
 5891:   if (!$stuname) { $stuname=$env{'user.name'}; }
 5892:   if ($domain eq 'public' && $stuname eq 'public') {
 5893:       $stuname=$ENV{'REMOTE_ADDR'};
 5894:   }
 5895:   my $path=LONCAPA::tempdir();
 5896:   my %hash;
 5897:   if (tie(%hash,'GDBM_File',
 5898: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 5899: 	  &GDBM_WRCREAT(),0640)) {
 5900:     foreach my $key (keys(%hash)) {
 5901:       if ($key=~ /:$symb/) {
 5902: 	delete($hash{$key});
 5903:       }
 5904:     }
 5905:   }
 5906: }
 5907: 
 5908: sub tmpstore {
 5909:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 5910: 
 5911:   if (!$symb) {
 5912:     $symb=&symbread();
 5913:     if (!$symb) { $symb= $env{'request.url'}; }
 5914:   }
 5915:   $symb=escape($symb);
 5916: 
 5917:   if (!$namespace) {
 5918:     # I don't think we would ever want to store this for a course.
 5919:     # it seems this will only be used if we don't have a course.
 5920:     #$namespace=$env{'request.course.id'};
 5921:     #if (!$namespace) {
 5922:       $namespace=$env{'request.state'};
 5923:     #}
 5924:   }
 5925:   $namespace=~s/\//\_/g;
 5926:   $namespace=~s/\W//g;
 5927:   if (!$domain) { $domain=$env{'user.domain'}; }
 5928:   if (!$stuname) { $stuname=$env{'user.name'}; }
 5929:   if ($domain eq 'public' && $stuname eq 'public') {
 5930:       $stuname=$ENV{'REMOTE_ADDR'};
 5931:   }
 5932:   my $now=time;
 5933:   my %hash;
 5934:   my $path=LONCAPA::tempdir();
 5935:   if (tie(%hash,'GDBM_File',
 5936: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 5937: 	  &GDBM_WRCREAT(),0640)) {
 5938:     $hash{"version:$symb"}++;
 5939:     my $version=$hash{"version:$symb"};
 5940:     my $allkeys=''; 
 5941:     foreach my $key (keys(%$storehash)) {
 5942:       $allkeys.=$key.':';
 5943:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 5944:     }
 5945:     $hash{"$version:$symb:timestamp"}=$now;
 5946:     $allkeys.='timestamp';
 5947:     $hash{"$version:keys:$symb"}=$allkeys;
 5948:     if (untie(%hash)) {
 5949:       return 'ok';
 5950:     } else {
 5951:       return "error:$!";
 5952:     }
 5953:   } else {
 5954:     return "error:$!";
 5955:   }
 5956: }
 5957: 
 5958: # -----------------------------------------------------------------Temp Restore
 5959: 
 5960: sub tmprestore {
 5961:   my ($symb,$namespace,$domain,$stuname) = @_;
 5962: 
 5963:   if (!$symb) {
 5964:     $symb=&symbread();
 5965:     if (!$symb) { $symb= $env{'request.url'}; }
 5966:   }
 5967:   $symb=escape($symb);
 5968: 
 5969:   if (!$namespace) { $namespace=$env{'request.state'}; }
 5970: 
 5971:   if (!$domain) { $domain=$env{'user.domain'}; }
 5972:   if (!$stuname) { $stuname=$env{'user.name'}; }
 5973:   if ($domain eq 'public' && $stuname eq 'public') {
 5974:       $stuname=$ENV{'REMOTE_ADDR'};
 5975:   }
 5976:   my %returnhash;
 5977:   $namespace=~s/\//\_/g;
 5978:   $namespace=~s/\W//g;
 5979:   my %hash;
 5980:   my $path=LONCAPA::tempdir();
 5981:   if (tie(%hash,'GDBM_File',
 5982: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 5983: 	  &GDBM_READER(),0640)) {
 5984:     my $version=$hash{"version:$symb"};
 5985:     $returnhash{'version'}=$version;
 5986:     my $scope;
 5987:     for ($scope=1;$scope<=$version;$scope++) {
 5988:       my $vkeys=$hash{"$scope:keys:$symb"};
 5989:       my @keys=split(/:/,$vkeys);
 5990:       my $key;
 5991:       $returnhash{"$scope:keys"}=$vkeys;
 5992:       foreach $key (@keys) {
 5993: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 5994: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 5995:       }
 5996:     }
 5997:     if (!(untie(%hash))) {
 5998:       return "error:$!";
 5999:     }
 6000:   } else {
 6001:     return "error:$!";
 6002:   }
 6003:   return %returnhash;
 6004: }
 6005: 
 6006: # ----------------------------------------------------------------------- Store
 6007: 
 6008: sub store {
 6009:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 6010:     my $home='';
 6011: 
 6012:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6013: 
 6014:     $symb=&symbclean($symb);
 6015:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 6016: 
 6017:     if (!$domain) { $domain=$env{'user.domain'}; }
 6018:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6019: 
 6020:     &devalidate($symb,$stuname,$domain);
 6021: 
 6022:     $symb=escape($symb);
 6023:     if (!$namespace) { 
 6024:        unless ($namespace=$env{'request.course.id'}) { 
 6025:           return ''; 
 6026:        } 
 6027:     }
 6028:     if (!$home) { $home=$env{'user.home'}; }
 6029: 
 6030:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 6031:     $$storehash{'host'}=$perlvar{'lonHostID'};
 6032: 
 6033:     my $namevalue='';
 6034:     foreach my $key (keys(%$storehash)) {
 6035:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6036:     }
 6037:     $namevalue=~s/\&$//;
 6038:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 6039:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 6040: }
 6041: 
 6042: # -------------------------------------------------------------- Critical Store
 6043: 
 6044: sub cstore {
 6045:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 6046:     my $home='';
 6047: 
 6048:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6049: 
 6050:     $symb=&symbclean($symb);
 6051:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 6052: 
 6053:     if (!$domain) { $domain=$env{'user.domain'}; }
 6054:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6055: 
 6056:     &devalidate($symb,$stuname,$domain);
 6057: 
 6058:     $symb=escape($symb);
 6059:     if (!$namespace) { 
 6060:        unless ($namespace=$env{'request.course.id'}) { 
 6061:           return ''; 
 6062:        } 
 6063:     }
 6064:     if (!$home) { $home=$env{'user.home'}; }
 6065: 
 6066:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 6067:     $$storehash{'host'}=$perlvar{'lonHostID'};
 6068: 
 6069:     my $namevalue='';
 6070:     foreach my $key (keys(%$storehash)) {
 6071:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6072:     }
 6073:     $namevalue=~s/\&$//;
 6074:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 6075:     return critical
 6076:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 6077: }
 6078: 
 6079: # --------------------------------------------------------------------- Restore
 6080: 
 6081: sub restore {
 6082:     my ($symb,$namespace,$domain,$stuname) = @_;
 6083:     my $home='';
 6084: 
 6085:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 6086: 
 6087:     if (!$symb) {
 6088:         return if ($namespace eq 'courserequests');
 6089:         unless ($symb=escape(&symbread())) { return ''; }
 6090:     } else {
 6091:         unless ($namespace eq 'courserequests') {
 6092:             $symb=&escape(&symbclean($symb));
 6093:         }
 6094:     }
 6095:     if (!$namespace) { 
 6096:        unless ($namespace=$env{'request.course.id'}) { 
 6097:           return ''; 
 6098:        } 
 6099:     }
 6100:     if (!$domain) { $domain=$env{'user.domain'}; }
 6101:     if (!$stuname) { $stuname=$env{'user.name'}; }
 6102:     if (!$home) { $home=$env{'user.home'}; }
 6103:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 6104: 
 6105:     my %returnhash=();
 6106:     foreach my $line (split(/\&/,$answer)) {
 6107: 	my ($name,$value)=split(/\=/,$line);
 6108:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 6109:     }
 6110:     my $version;
 6111:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 6112:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 6113:           $returnhash{$item}=$returnhash{$version.':'.$item};
 6114:        }
 6115:     }
 6116:     return %returnhash;
 6117: }
 6118: 
 6119: # ---------------------------------------------------------- Course Description
 6120: #
 6121: #  
 6122: 
 6123: sub coursedescription {
 6124:     my ($courseid,$args)=@_;
 6125:     $courseid=~s/^\///;
 6126:     $courseid=~s/\_/\//g;
 6127:     my ($cdomain,$cnum)=split(/\//,$courseid);
 6128:     my $chome=&homeserver($cnum,$cdomain);
 6129:     my $normalid=$cdomain.'_'.$cnum;
 6130:     # need to always cache even if we get errors otherwise we keep 
 6131:     # trying and trying and trying to get the course description.
 6132:     my %envhash=();
 6133:     my %returnhash=();
 6134:     
 6135:     my $expiretime=600;
 6136:     if ($env{'request.course.id'} eq $normalid) {
 6137: 	$expiretime=120;
 6138:     }
 6139: 
 6140:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 6141:     if (!$args->{'freshen_cache'}
 6142: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 6143: 	foreach my $key (keys(%env)) {
 6144: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 6145: 	    my ($setting) = $1;
 6146: 	    $returnhash{$setting} = $env{$key};
 6147: 	}
 6148: 	return %returnhash;
 6149:     }
 6150: 
 6151:     # get the data again
 6152: 
 6153:     if (!$args->{'one_time'}) {
 6154: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 6155:     }
 6156: 
 6157:     if ($chome ne 'no_host') {
 6158:        %returnhash=&dump('environment',$cdomain,$cnum);
 6159:        if (!exists($returnhash{'con_lost'})) {
 6160: 	   my $username = $env{'user.name'}; # Defult username
 6161: 	   if(defined $args->{'user'}) {
 6162: 	       $username = $args->{'user'};
 6163: 	   }
 6164:            $returnhash{'home'}= $chome;
 6165: 	   $returnhash{'domain'} = $cdomain;
 6166: 	   $returnhash{'num'} = $cnum;
 6167:            if (!defined($returnhash{'type'})) {
 6168:                $returnhash{'type'} = 'Course';
 6169:            }
 6170:            while (my ($name,$value) = each %returnhash) {
 6171:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 6172:            }
 6173:            $returnhash{'url'}=&clutter($returnhash{'url'});
 6174:            $returnhash{'fn'}=LONCAPA::tempdir() .
 6175: 	       $username.'_'.$cdomain.'_'.$cnum;
 6176:            $envhash{'course.'.$normalid.'.home'}=$chome;
 6177:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 6178:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 6179:        }
 6180:     }
 6181:     if (!$args->{'one_time'}) {
 6182: 	&appenv(\%envhash);
 6183:     }
 6184:     return %returnhash;
 6185: }
 6186: 
 6187: sub update_released_required {
 6188:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 6189:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 6190:         $cid = $env{'request.course.id'};
 6191:         $cdom = $env{'course.'.$cid.'.domain'};
 6192:         $cnum = $env{'course.'.$cid.'.num'};
 6193:         $chome = $env{'course.'.$cid.'.home'};
 6194:     }
 6195:     if ($needsrelease) {
 6196:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 6197:         my $needsupdate;
 6198:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 6199:             $needsupdate = 1;
 6200:         } else {
 6201:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 6202:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 6203:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 6204:                 $needsupdate = 1;
 6205:             }
 6206:         }
 6207:         if ($needsupdate) {
 6208:             my %needshash = (
 6209:                              'internal.releaserequired' => $needsrelease,
 6210:                             );
 6211:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 6212:             if ($putresult eq 'ok') {
 6213:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 6214:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 6215:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 6216:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 6217:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 6218:                 }
 6219:             }
 6220:         }
 6221:     }
 6222:     return;
 6223: }
 6224: 
 6225: # -------------------------------------------------See if a user is privileged
 6226: 
 6227: sub privileged {
 6228:     my ($username,$domain,$possdomains,$possroles)=@_;
 6229:     my $now = time;
 6230:     my $roles;
 6231:     if (ref($possroles) eq 'ARRAY') {
 6232:         $roles = $possroles;
 6233:     } else {
 6234:         $roles = ['dc','su'];
 6235:     }
 6236:     if (ref($possdomains) eq 'ARRAY') {
 6237:         my %privileged = &privileged_by_domain($possdomains,$roles);
 6238:         foreach my $dom (@{$possdomains}) {
 6239:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
 6240:                 (ref($privileged{$dom}) eq 'HASH')) {
 6241:                 foreach my $role (@{$roles}) {
 6242:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 6243:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
 6244:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
 6245:                             return 1 unless (($end && $end < $now) ||
 6246:                                              ($start && $start > $now));
 6247:                         }
 6248:                     }
 6249:                 }
 6250:             }
 6251:         }
 6252:     } else {
 6253:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
 6254:         my $now = time;
 6255: 
 6256:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
 6257:             my ($trole, $tend, $tstart) = split(/_/, $role);
 6258:             if (grep(/^\Q$trole\E$/,@{$roles})) {
 6259:                 return 1 unless ($tend && $tend < $now)
 6260:                         or ($tstart && $tstart > $now);
 6261:             }
 6262:         }
 6263:     }
 6264:     return 0;
 6265: }
 6266: 
 6267: sub privileged_by_domain {
 6268:     my ($domains,$roles) = @_;
 6269:     my %privileged = ();
 6270:     my $cachetime = 60*60*24;
 6271:     my $now = time;
 6272:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
 6273:         return %privileged;
 6274:     }
 6275:     foreach my $dom (@{$domains}) {
 6276:         next if (ref($privileged{$dom}) eq 'HASH');
 6277:         my $needroles;
 6278:         foreach my $role (@{$roles}) {
 6279:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
 6280:             if (defined($cached)) {
 6281:                 if (ref($result) eq 'HASH') {
 6282:                     $privileged{$dom}{$role} = $result;
 6283:                 }
 6284:             } else {
 6285:                 $needroles = 1;
 6286:             }
 6287:         }
 6288:         if ($needroles) {
 6289:             my %dompersonnel = &get_domain_roles($dom,$roles);
 6290:             $privileged{$dom} = {};
 6291:             foreach my $server (keys(%dompersonnel)) {
 6292:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 6293:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
 6294:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
 6295:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
 6296:                         next if ($end && $end < $now);
 6297:                         $privileged{$dom}{$trole}{$uname.':'.$udom} =
 6298:                             $dompersonnel{$server}{$item};
 6299:                     }
 6300:                 }
 6301:             }
 6302:             if (ref($privileged{$dom}) eq 'HASH') {
 6303:                 foreach my $role (@{$roles}) {
 6304:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 6305:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
 6306:                     } else {
 6307:                         my %hash = ();
 6308:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
 6309:                     }
 6310:                 }
 6311:             }
 6312:         }
 6313:     }
 6314:     return %privileged;
 6315: }
 6316: 
 6317: # -------------------------------------------------------- Get user privileges
 6318: 
 6319: sub rolesinit {
 6320:     my ($domain, $username) = @_;
 6321:     my %userroles = ('user.login.time' => time);
 6322:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 6323: 
 6324:     # firstaccess and timerinterval are related to timed maps/resources. 
 6325:     # also, blocking can be triggered by an activating timer
 6326:     # it's saved in the user's %env.
 6327:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 6328:     my %timerinterval = &dump('timerinterval', $domain, $username);
 6329:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 6330:         %timerintchk, %timerintenv);
 6331: 
 6332:     foreach my $key (keys(%firstaccess)) {
 6333:         my ($cid, $rest) = split(/\0/, $key);
 6334:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 6335:     }
 6336: 
 6337:     foreach my $key (keys(%timerinterval)) {
 6338:         my ($cid,$rest) = split(/\0/,$key);
 6339:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 6340:     }
 6341: 
 6342:     my %allroles=();
 6343:     my %allgroups=();
 6344: 
 6345:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
 6346:         my $role = $rolesdump{$area};
 6347:         $area =~ s/\_\w\w$//;
 6348: 
 6349:         my ($trole, $tend, $tstart, $group_privs);
 6350: 
 6351:         if ($role =~ /^cr/) {
 6352:         # Custom role, defined by a user 
 6353:         # e.g., user.role.cr/msu/smith/mynewrole
 6354:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 6355:                 $trole = $1;
 6356:                 ($tend, $tstart) = split('_', $2);
 6357:             } else {
 6358:                 $trole = $role;
 6359:             }
 6360:         } elsif ($role =~ m|^gr/|) {
 6361:         # Role of member in a group, defined within a course/community
 6362:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 6363:             ($trole, $tend, $tstart) = split(/_/, $role);
 6364:             next if $tstart eq '-1';
 6365:             ($trole, $group_privs) = split(/\//, $trole);
 6366:             $group_privs = &unescape($group_privs);
 6367:         } else {
 6368:         # Just a normal role, defined in roles.tab
 6369:             ($trole, $tend, $tstart) = split(/_/,$role);
 6370:         }
 6371: 
 6372:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 6373:                  $username);
 6374:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 6375: 
 6376:         # role expired or not available yet?
 6377:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 6378:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 6379: 
 6380:         next if $area eq '' or $trole eq '';
 6381: 
 6382:         my $spec = "$trole.$area";
 6383:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 6384: 
 6385:         if ($trole =~ /^cr\//) {
 6386:         # Custom role, defined by a user
 6387:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 6388:         } elsif ($trole eq 'gr') {
 6389:         # Role of a member in a group, defined within a course/community
 6390:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 6391:             next;
 6392:         } else {
 6393:         # Normal role, defined in roles.tab
 6394:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 6395:         }
 6396: 
 6397:         my $cid = $tdomain.'_'.$trest;
 6398:         unless ($firstaccchk{$cid}) {
 6399:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 6400:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 6401:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 6402:                         $coursetimerstarts{$cid}{$item}; 
 6403:                 }
 6404:             }
 6405:             $firstaccchk{$cid} = 1;
 6406:         }
 6407:         unless ($timerintchk{$cid}) {
 6408:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 6409:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 6410:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 6411:                        $coursetimerintervals{$cid}{$item};
 6412:                 }
 6413:             }
 6414:             $timerintchk{$cid} = 1;
 6415:         }
 6416:     }
 6417: 
 6418:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
 6419:                                                           \%allroles, \%allgroups);
 6420:     $env{'user.adv'} = $userroles{'user.adv'};
 6421:     $env{'user.rar'} = $userroles{'user.rar'};
 6422: 
 6423:     return (\%userroles,\%firstaccenv,\%timerintenv);
 6424: }
 6425: 
 6426: sub set_arearole {
 6427:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
 6428:     unless ($nolog) {
 6429: # log the associated role with the area
 6430:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 6431:     }
 6432:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 6433: }
 6434: 
 6435: sub custom_roleprivs {
 6436:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 6437:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 6438:     my $homsvr = &homeserver($rauthor,$rdomain);
 6439:     if (&hostname($homsvr) ne '') {
 6440:         my ($rdummy,$roledef)=
 6441:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 6442:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 6443:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 6444:             if (defined($syspriv)) {
 6445:                 if ($trest =~ /^$match_community$/) {
 6446:                     $syspriv =~ s/bre\&S//; 
 6447:                 }
 6448:                 $$allroles{'cm./'}.=':'.$syspriv;
 6449:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 6450:             }
 6451:             if ($tdomain ne '') {
 6452:                 if (defined($dompriv)) {
 6453:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 6454:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 6455:                 }
 6456:                 if (($trest ne '') && (defined($coursepriv))) {
 6457:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
 6458:                         my $rolename = $1;
 6459:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
 6460:                     }
 6461:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 6462:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 6463:                 }
 6464:             }
 6465:         }
 6466:     }
 6467: }
 6468: 
 6469: sub course_adhocrole_privs {
 6470:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
 6471:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
 6472:     if ($overrides{"internal.adhocpriv.$rolename"}) {
 6473:         my (%currprivs,%storeprivs);
 6474:         foreach my $item (split(/:/,$coursepriv)) {
 6475:             my ($priv,$restrict) = split(/\&/,$item);
 6476:             $currprivs{$priv} = $restrict;
 6477:         }
 6478:         my (%possadd,%possremove,%full);
 6479:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
 6480:             my ($priv,$restrict)=split(/\&/,$item);
 6481:             $full{$priv} = $restrict;
 6482:         }
 6483:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
 6484:              next if ($item eq '');
 6485:              my ($rule,$rest) = split(/=/,$item);
 6486:              next unless (($rule eq 'off') || ($rule eq 'on'));
 6487:              foreach my $priv (split(/:/,$rest)) {
 6488:                  if ($priv ne '') {
 6489:                      if ($rule eq 'off') {
 6490:                          $possremove{$priv} = 1;
 6491:                      } else {
 6492:                          $possadd{$priv} = 1;
 6493:                      }
 6494:                  }
 6495:              }
 6496:          }
 6497:          foreach my $priv (sort(keys(%full))) {
 6498:              if (exists($currprivs{$priv})) {
 6499:                  unless (exists($possremove{$priv})) {
 6500:                      $storeprivs{$priv} = $currprivs{$priv};
 6501:                  }
 6502:              } elsif (exists($possadd{$priv})) {
 6503:                  $storeprivs{$priv} = $full{$priv};
 6504:              }
 6505:          }
 6506:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
 6507:      }
 6508:      return $coursepriv;
 6509: }
 6510: 
 6511: sub group_roleprivs {
 6512:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 6513:     my $access = 1;
 6514:     my $now = time;
 6515:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 6516:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 6517:     if ($access) {
 6518:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 6519:         $$allgroups{$course}{$group} .=':'.$group_privs;
 6520:     }
 6521: }
 6522: 
 6523: sub standard_roleprivs {
 6524:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 6525:     if (defined($pr{$trole.':s'})) {
 6526:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 6527:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 6528:     }
 6529:     if ($tdomain ne '') {
 6530:         if (defined($pr{$trole.':d'})) {
 6531:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 6532:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 6533:         }
 6534:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 6535:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 6536:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 6537:         }
 6538:     }
 6539: }
 6540: 
 6541: sub set_userprivs {
 6542:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 6543:     my $author=0;
 6544:     my $adv=0;
 6545:     my $rar=0;
 6546:     my %grouproles = ();
 6547:     if (keys(%{$allgroups}) > 0) {
 6548:         my @groupkeys; 
 6549:         foreach my $role (keys(%{$allroles})) {
 6550:             push(@groupkeys,$role);
 6551:         }
 6552:         if (ref($groups_roles) eq 'HASH') {
 6553:             foreach my $key (keys(%{$groups_roles})) {
 6554:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 6555:                     push(@groupkeys,$key);
 6556:                 }
 6557:             }
 6558:         }
 6559:         if (@groupkeys > 0) {
 6560:             foreach my $role (@groupkeys) {
 6561:                 my ($trole,$area,$sec,$extendedarea);
 6562:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 6563:                     $trole = $1;
 6564:                     $area = $2;
 6565:                     $sec = $3;
 6566:                     $extendedarea = $area.$sec;
 6567:                     if (exists($$allgroups{$area})) {
 6568:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 6569:                             my $spec = $trole.'.'.$extendedarea;
 6570:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 6571:                                                 $$allgroups{$area}{$group};
 6572:                         }
 6573:                     }
 6574:                 }
 6575:             }
 6576:         }
 6577:     }
 6578:     foreach my $group (keys(%grouproles)) {
 6579:         $$allroles{$group} = $grouproles{$group};
 6580:     }
 6581:     foreach my $role (keys(%{$allroles})) {
 6582:         my %thesepriv;
 6583:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 6584:         foreach my $item (split(/:/,$$allroles{$role})) {
 6585:             if ($item ne '') {
 6586:                 my ($privilege,$restrictions)=split(/&/,$item);
 6587:                 if ($restrictions eq '') {
 6588:                     $thesepriv{$privilege}='F';
 6589:                 } elsif ($thesepriv{$privilege} ne 'F') {
 6590:                     $thesepriv{$privilege}.=$restrictions;
 6591:                 }
 6592:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 6593:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
 6594:             }
 6595:         }
 6596:         my $thesestr='';
 6597:         foreach my $priv (sort(keys(%thesepriv))) {
 6598: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 6599: 	}
 6600:         $userroles->{'user.priv.'.$role} = $thesestr;
 6601:     }
 6602:     return ($author,$adv,$rar);
 6603: }
 6604: 
 6605: sub role_status {
 6606:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 6607:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 6608:         my ($one,$two) = split(m{\./},$rolekey,2);
 6609:         (undef,undef,$$role) = split(/\./,$one,3);
 6610:         unless (!defined($$role) || $$role eq '') {
 6611:             $$where = '/'.$two;
 6612:             $$trolecode=$$role.'.'.$$where;
 6613:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 6614:             $$tstatus='is';
 6615:             if ($$tstart && $$tstart>$update) {
 6616:                 $$tstatus='future';
 6617:                 if ($$tstart<$now) {
 6618:                     if ($$tstart && $$tstart>$refresh) {
 6619:                         if (($$where ne '') && ($$role ne '')) {
 6620:                             my (%allroles,%allgroups,$group_privs,
 6621:                                 %groups_roles,@rolecodes);
 6622:                             my %userroles = (
 6623:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 6624:                             );
 6625:                             @rolecodes = ('cm'); 
 6626:                             my $spec=$$role.'.'.$$where;
 6627:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 6628:                             if ($$role =~ /^cr\//) {
 6629:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 6630:                                 push(@rolecodes,'cr');
 6631:                             } elsif ($$role eq 'gr') {
 6632:                                 push(@rolecodes,$$role);
 6633:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 6634:                                                     $env{'user.name'});
 6635:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 6636:                                 (undef,my $group_privs) = split(/\//,$trole);
 6637:                                 $group_privs = &unescape($group_privs);
 6638:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 6639:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 6640:                                 &get_groups_roles($tdomain,$trest,
 6641:                                                   \%course_roles,\@rolecodes,
 6642:                                                   \%groups_roles);
 6643:                             } else {
 6644:                                 push(@rolecodes,$$role);
 6645:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 6646:                             }
 6647:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
 6648:                                                                    \%groups_roles);
 6649:                             &appenv(\%userroles,\@rolecodes);
 6650:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 6651:                         }
 6652:                     }
 6653:                     $$tstatus = 'is';
 6654:                 }
 6655:             }
 6656:             if ($$tend) {
 6657:                 if ($$tend<$update) {
 6658:                     $$tstatus='expired';
 6659:                 } elsif ($$tend<$now) {
 6660:                     $$tstatus='will_not';
 6661:                 }
 6662:             }
 6663:         }
 6664:     }
 6665: }
 6666: 
 6667: sub get_groups_roles {
 6668:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 6669:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 6670:                   (ref($rolecodes) eq 'ARRAY') && 
 6671:                   (ref($groups_roles) eq 'HASH')); 
 6672:     if (keys(%{$cdom_courseroles}) > 0) {
 6673:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 6674:         if ($cdom ne '' && $cnum ne '') {
 6675:             foreach my $key (keys(%{$cdom_courseroles})) {
 6676:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 6677:                     my $crsrole = $1;
 6678:                     my $crssec = $2;
 6679:                     if ($crsrole =~ /^cr/) {
 6680:                         unless (grep(/^cr$/,@{$rolecodes})) {
 6681:                             push(@{$rolecodes},'cr');
 6682:                         }
 6683:                     } else {
 6684:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 6685:                             push(@{$rolecodes},$crsrole);
 6686:                         }
 6687:                     }
 6688:                     my $rolekey = "$crsrole./$cdom/$cnum";
 6689:                     if ($crssec ne '') {
 6690:                         $rolekey .= "/$crssec";
 6691:                     }
 6692:                     $rolekey .= './';
 6693:                     $groups_roles->{$rolekey} = $rolecodes;
 6694:                 }
 6695:             }
 6696:         }
 6697:     }
 6698:     return;
 6699: }
 6700: 
 6701: sub delete_env_groupprivs {
 6702:     my ($where,$courseroles,$possroles) = @_;
 6703:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 6704:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 6705:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 6706:         %{$courseroles->{$udom}} =
 6707:             &get_my_roles('','','userroles',['active'],
 6708:                           $possroles,[$udom],1);
 6709:     }
 6710:     if (ref($courseroles->{$udom}) eq 'HASH') {
 6711:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 6712:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 6713:             my $area = '/'.$cdom.'/'.$cnum;
 6714:             my $privkey = "user.priv.$crsrole.$area";
 6715:             if ($crssec ne '') {
 6716:                 $privkey .= '/'.$crssec;
 6717:             }
 6718:             $privkey .= ".$area/$group";
 6719:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 6720:         }
 6721:     }
 6722:     return;
 6723: }
 6724: 
 6725: sub check_adhoc_privs {
 6726:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
 6727:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 6728:     if ($sec) {
 6729:         $cckey .= '/'.$sec;
 6730:     }
 6731:     my $setprivs;
 6732:     if ($env{$cckey}) {
 6733:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 6734:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 6735:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 6736:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 6737:             $setprivs = 1;
 6738:         }
 6739:     } else {
 6740:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 6741:         $setprivs = 1;
 6742:     }
 6743:     return $setprivs;
 6744: }
 6745: 
 6746: sub set_adhoc_privileges {
 6747: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
 6748:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
 6749:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 6750:     if ($sec ne '') {
 6751:         $area .= '/'.$sec;
 6752:     }
 6753:     my $spec = $role.'.'.$area;
 6754:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 6755:                                   $env{'user.name'},1);
 6756:     my %rolehash = ();
 6757:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
 6758:         my $rolename = $1;
 6759:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
 6760:         my %domdef = &get_domain_defaults($dcdom);
 6761:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
 6762:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
 6763:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
 6764:             }
 6765:         }
 6766:     } else {
 6767:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
 6768:     }
 6769:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
 6770:     &appenv(\%userroles,[$role,'cm']);
 6771:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 6772:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
 6773:         &appenv( {'request.role'        => $spec,
 6774:                   'request.role.domain' => $dcdom,
 6775:                   'request.course.sec'  => $sec, 
 6776:                  }
 6777:                );
 6778:         my $tadv=0;
 6779:         if (&allowed('adv') eq 'F') { $tadv=1; }
 6780:         &appenv({'request.role.adv'    => $tadv});
 6781:     }
 6782: }
 6783: 
 6784: # --------------------------------------------------------------- get interface
 6785: 
 6786: sub get {
 6787:    my ($namespace,$storearr,$udomain,$uname)=@_;
 6788:    my $items='';
 6789:    foreach my $item (@$storearr) {
 6790:        $items.=&escape($item).'&';
 6791:    }
 6792:    $items=~s/\&$//;
 6793:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6794:    if (!$uname) { $uname=$env{'user.name'}; }
 6795:    my $uhome=&homeserver($uname,$udomain);
 6796: 
 6797:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 6798:    my @pairs=split(/\&/,$rep);
 6799:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 6800:      return @pairs;
 6801:    }
 6802:    my %returnhash=();
 6803:    my $i=0;
 6804:    foreach my $item (@$storearr) {
 6805:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 6806:       $i++;
 6807:    }
 6808:    return %returnhash;
 6809: }
 6810: 
 6811: # --------------------------------------------------------------- del interface
 6812: 
 6813: sub del {
 6814:    my ($namespace,$storearr,$udomain,$uname)=@_;
 6815:    my $items='';
 6816:    foreach my $item (@$storearr) {
 6817:        $items.=&escape($item).'&';
 6818:    }
 6819: 
 6820:    $items=~s/\&$//;
 6821:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6822:    if (!$uname) { $uname=$env{'user.name'}; }
 6823:    my $uhome=&homeserver($uname,$udomain);
 6824:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 6825: }
 6826: 
 6827: # -------------------------------------------------------------- dump interface
 6828: 
 6829: sub unserialize {
 6830:     my ($rep, $escapedkeys) = @_;
 6831: 
 6832:     return {} if $rep =~ /^error/;
 6833: 
 6834:     my %returnhash=();
 6835:     foreach my $item (split(/\&/,$rep)) {
 6836:         my ($key, $value) = split(/=/, $item, 2);
 6837:         $key = unescape($key) unless $escapedkeys;
 6838:         next if $key =~ /^error: 2 /;
 6839:         $returnhash{$key} = &thaw_unescape($value);
 6840:     }
 6841:     return \%returnhash;
 6842: }
 6843: 
 6844: # see Lond::dump_with_regexp
 6845: # if $escapedkeys hash keys won't get unescaped.
 6846: sub dump {
 6847:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
 6848:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 6849:     if (!$uname) { $uname=$env{'user.name'}; }
 6850:     my $uhome=&homeserver($uname,$udomain);
 6851: 
 6852:     if ($regexp) {
 6853:         $regexp=&escape($regexp);
 6854:     } else {
 6855:         $regexp='.';
 6856:     }
 6857:     if (grep { $_ eq $uhome } &current_machine_ids()) {
 6858:         # user is hosted on this machine
 6859:         my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
 6860:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
 6861:         return %{&unserialize($reply, $escapedkeys)};
 6862:     }
 6863:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 6864:     my @pairs=split(/\&/,$rep);
 6865:     my %returnhash=();
 6866:     if (!($rep =~ /^error/ )) {
 6867: 	foreach my $item (@pairs) {
 6868: 	    my ($key,$value)=split(/=/,$item,2);
 6869:             $key = &unescape($key) unless ($escapedkeys);
 6870: 	    next if ($key =~ /^error: 2 /);
 6871: 	    $returnhash{$key}=&thaw_unescape($value);
 6872: 	}
 6873:     }
 6874:     return %returnhash;
 6875: }
 6876: 
 6877: 
 6878: # --------------------------------------------------------- dumpstore interface
 6879: 
 6880: sub dumpstore {
 6881:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 6882:    # same as dump but keys must be escaped. They may contain colon separated
 6883:    # lists of values that may themself contain colons (e.g. symbs).
 6884:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
 6885: }
 6886: 
 6887: # -------------------------------------------------------------- keys interface
 6888: 
 6889: sub getkeys {
 6890:    my ($namespace,$udomain,$uname)=@_;
 6891:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6892:    if (!$uname) { $uname=$env{'user.name'}; }
 6893:    my $uhome=&homeserver($uname,$udomain);
 6894:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 6895:    my @keyarray=();
 6896:    foreach my $key (split(/\&/,$rep)) {
 6897:       next if ($key =~ /^error: 2 /);
 6898:       push(@keyarray,&unescape($key));
 6899:    }
 6900:    return @keyarray;
 6901: }
 6902: 
 6903: # --------------------------------------------------------------- currentdump
 6904: sub currentdump {
 6905:    my ($courseid,$sdom,$sname)=@_;
 6906:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 6907:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 6908:    $sname    = $env{'user.name'}         if (! defined($sname));
 6909:    my $uhome = &homeserver($sname,$sdom);
 6910:    my $rep;
 6911: 
 6912:    if (grep { $_ eq $uhome } current_machine_ids()) {
 6913:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
 6914:                    $courseid)));
 6915:    } else {
 6916:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 6917:    }
 6918: 
 6919:    return if ($rep =~ /^(error:|no_such_host)/);
 6920:    #
 6921:    my %returnhash=();
 6922:    #
 6923:    if ($rep eq 'unknown_cmd') {
 6924:        # an old lond will not know currentdump
 6925:        # Do a dump and make it look like a currentdump
 6926:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 6927:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 6928:        my %hash = @tmp;
 6929:        @tmp=();
 6930:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 6931:    } else {
 6932:        my @pairs=split(/\&/,$rep);
 6933:        foreach my $pair (@pairs) {
 6934:            my ($key,$value)=split(/=/,$pair,2);
 6935:            my ($symb,$param) = split(/:/,$key);
 6936:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 6937:                                                         &thaw_unescape($value);
 6938:        }
 6939:    }
 6940:    return %returnhash;
 6941: }
 6942: 
 6943: sub convert_dump_to_currentdump{
 6944:     my %hash = %{shift()};
 6945:     my %returnhash;
 6946:     # Code ripped from lond, essentially.  The only difference
 6947:     # here is the unescaping done by lonnet::dump().  Conceivably
 6948:     # we might run in to problems with parameter names =~ /^v\./
 6949:     while (my ($key,$value) = each(%hash)) {
 6950:         my ($v,$symb,$param) = split(/:/,$key);
 6951: 	$symb  = &unescape($symb);
 6952: 	$param = &unescape($param);
 6953:         next if ($v eq 'version' || $symb eq 'keys');
 6954:         next if (exists($returnhash{$symb}) &&
 6955:                  exists($returnhash{$symb}->{$param}) &&
 6956:                  $returnhash{$symb}->{'v.'.$param} > $v);
 6957:         $returnhash{$symb}->{$param}=$value;
 6958:         $returnhash{$symb}->{'v.'.$param}=$v;
 6959:     }
 6960:     #
 6961:     # Remove all of the keys in the hashes which keep track of
 6962:     # the version of the parameter.
 6963:     while (my ($symb,$param_hash) = each(%returnhash)) {
 6964:         # use a foreach because we are going to delete from the hash.
 6965:         foreach my $key (keys(%$param_hash)) {
 6966:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 6967:         }
 6968:     }
 6969:     return \%returnhash;
 6970: }
 6971: 
 6972: # ------------------------------------------------------ critical inc interface
 6973: 
 6974: sub cinc {
 6975:     return &inc(@_,'critical');
 6976: }
 6977: 
 6978: # --------------------------------------------------------------- inc interface
 6979: 
 6980: sub inc {
 6981:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 6982:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 6983:     if (!$uname) { $uname=$env{'user.name'}; }
 6984:     my $uhome=&homeserver($uname,$udomain);
 6985:     my $items='';
 6986:     if (! ref($store)) {
 6987:         # got a single value, so use that instead
 6988:         $items = &escape($store).'=&';
 6989:     } elsif (ref($store) eq 'SCALAR') {
 6990:         $items = &escape($$store).'=&';        
 6991:     } elsif (ref($store) eq 'ARRAY') {
 6992:         $items = join('=&',map {&escape($_);} @{$store});
 6993:     } elsif (ref($store) eq 'HASH') {
 6994:         while (my($key,$value) = each(%{$store})) {
 6995:             $items.= &escape($key).'='.&escape($value).'&';
 6996:         }
 6997:     }
 6998:     $items=~s/\&$//;
 6999:     if ($critical) {
 7000: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 7001:     } else {
 7002: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 7003:     }
 7004: }
 7005: 
 7006: # --------------------------------------------------------------- put interface
 7007: 
 7008: sub put {
 7009:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7010:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7011:    if (!$uname) { $uname=$env{'user.name'}; }
 7012:    my $uhome=&homeserver($uname,$udomain);
 7013:    my $items='';
 7014:    foreach my $item (keys(%$storehash)) {
 7015:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7016:    }
 7017:    $items=~s/\&$//;
 7018:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 7019: }
 7020: 
 7021: # ------------------------------------------------------------ newput interface
 7022: 
 7023: sub newput {
 7024:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7025:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7026:    if (!$uname) { $uname=$env{'user.name'}; }
 7027:    my $uhome=&homeserver($uname,$udomain);
 7028:    my $items='';
 7029:    foreach my $key (keys(%$storehash)) {
 7030:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 7031:    }
 7032:    $items=~s/\&$//;
 7033:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 7034: }
 7035: 
 7036: # ---------------------------------------------------------  putstore interface
 7037: 
 7038: sub putstore {
 7039:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
 7040:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7041:    if (!$uname) { $uname=$env{'user.name'}; }
 7042:    my $uhome=&homeserver($uname,$udomain);
 7043:    my $items='';
 7044:    foreach my $key (keys(%$storehash)) {
 7045:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 7046:    }
 7047:    $items=~s/\&$//;
 7048:    my $esc_symb=&escape($symb);
 7049:    my $esc_v=&escape($version);
 7050:    my $reply =
 7051:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 7052: 	      $uhome);
 7053:    if (($tolog) && ($reply eq 'ok')) {
 7054:        my $namevalue='';
 7055:        foreach my $key (keys(%{$storehash})) {
 7056:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 7057:        }
 7058:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
 7059:                      '&host='.&escape($perlvar{'lonHostID'}).
 7060:                      '&version='.$esc_v.
 7061:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
 7062:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
 7063:    }
 7064:    if ($reply eq 'unknown_cmd') {
 7065:        # gfall back to way things use to be done
 7066:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 7067: 			    $uname);
 7068:    }
 7069:    return $reply;
 7070: }
 7071: 
 7072: sub old_putstore {
 7073:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 7074:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 7075:     if (!$uname) { $uname=$env{'user.name'}; }
 7076:     my $uhome=&homeserver($uname,$udomain);
 7077:     my %newstorehash;
 7078:     foreach my $item (keys(%$storehash)) {
 7079: 	my $key = $version.':'.&escape($symb).':'.$item;
 7080: 	$newstorehash{$key} = $storehash->{$item};
 7081:     }
 7082:     my $items='';
 7083:     my %allitems = ();
 7084:     foreach my $item (keys(%newstorehash)) {
 7085: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 7086: 	    my $key = $1.':keys:'.$2;
 7087: 	    $allitems{$key} .= $3.':';
 7088: 	}
 7089: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 7090:     }
 7091:     foreach my $item (keys(%allitems)) {
 7092: 	$allitems{$item} =~ s/\:$//;
 7093: 	$items.= $item.'='.$allitems{$item}.'&';
 7094:     }
 7095:     $items=~s/\&$//;
 7096:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 7097: }
 7098: 
 7099: # ------------------------------------------------------ critical put interface
 7100: 
 7101: sub cput {
 7102:    my ($namespace,$storehash,$udomain,$uname)=@_;
 7103:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7104:    if (!$uname) { $uname=$env{'user.name'}; }
 7105:    my $uhome=&homeserver($uname,$udomain);
 7106:    my $items='';
 7107:    foreach my $item (keys(%$storehash)) {
 7108:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7109:    }
 7110:    $items=~s/\&$//;
 7111:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 7112: }
 7113: 
 7114: # -------------------------------------------------------------- eget interface
 7115: 
 7116: sub eget {
 7117:    my ($namespace,$storearr,$udomain,$uname)=@_;
 7118:    my $items='';
 7119:    foreach my $item (@$storearr) {
 7120:        $items.=&escape($item).'&';
 7121:    }
 7122:    $items=~s/\&$//;
 7123:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 7124:    if (!$uname) { $uname=$env{'user.name'}; }
 7125:    my $uhome=&homeserver($uname,$udomain);
 7126:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 7127:    my @pairs=split(/\&/,$rep);
 7128:    my %returnhash=();
 7129:    my $i=0;
 7130:    foreach my $item (@$storearr) {
 7131:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 7132:       $i++;
 7133:    }
 7134:    return %returnhash;
 7135: }
 7136: 
 7137: # ------------------------------------------------------------ tmpput interface
 7138: sub tmpput {
 7139:     my ($storehash,$server,$context)=@_;
 7140:     my $items='';
 7141:     foreach my $item (keys(%$storehash)) {
 7142: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 7143:     }
 7144:     $items=~s/\&$//;
 7145:     if (defined($context)) {
 7146:         $items .= ':'.&escape($context);
 7147:     }
 7148:     return &reply("tmpput:$items",$server);
 7149: }
 7150: 
 7151: # ------------------------------------------------------------ tmpget interface
 7152: sub tmpget {
 7153:     my ($token,$server)=@_;
 7154:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 7155:     my $rep=&reply("tmpget:$token",$server);
 7156:     my %returnhash;
 7157:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
 7158:         return %returnhash;
 7159:     }
 7160:     foreach my $item (split(/\&/,$rep)) {
 7161: 	my ($key,$value)=split(/=/,$item);
 7162: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 7163:     }
 7164:     return %returnhash;
 7165: }
 7166: 
 7167: # ------------------------------------------------------------ tmpdel interface
 7168: sub tmpdel {
 7169:     my ($token,$server)=@_;
 7170:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 7171:     return &reply("tmpdel:$token",$server);
 7172: }
 7173: 
 7174: # ------------------------------------------------------------ get_timebased_id
 7175: 
 7176: sub get_timebased_id {
 7177:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
 7178:         $maxtries) = @_;
 7179:     my ($newid,$error,$dellock);
 7180:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
 7181:         return ('','ok','invalid call to get suffix');
 7182:     }
 7183: 
 7184: # set defaults for any optional args for which values were not supplied
 7185:     if ($who eq '') {
 7186:         $who = $env{'user.name'}.':'.$env{'user.domain'};
 7187:     }
 7188:     if (!$locktries) {
 7189:         $locktries = 3;
 7190:     }
 7191:     if (!$maxtries) {
 7192:         $maxtries = 10;
 7193:     }
 7194: 
 7195:     if (($cdom eq '') || ($cnum eq '')) {
 7196:         if ($env{'request.course.id'}) {
 7197:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7198:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7199:         }
 7200:         if (($cdom eq '') || ($cnum eq '')) {
 7201:             return ('','ok','call to get suffix not in course context');
 7202:         }
 7203:     }
 7204: 
 7205: # construct locking item
 7206:     my $lockhash = {
 7207:                       $prefix."\0".'locked_'.$keyid => $who,
 7208:                    };
 7209:     my $tries = 0;
 7210: 
 7211: # attempt to get lock on nohist_$namespace file
 7212:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 7213:     while (($gotlock ne 'ok') && $tries <$locktries) {
 7214:         $tries ++;
 7215:         sleep 1;
 7216:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 7217:     }
 7218: 
 7219: # attempt to get unique identifier, based on current timestamp
 7220:     if ($gotlock eq 'ok') {
 7221:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
 7222:         my $id = time;
 7223:         $newid = $id;
 7224:         if ($idtype eq 'addcode') {
 7225:             $newid .= &sixnum_code();
 7226:         }
 7227:         my $idtries = 0;
 7228:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
 7229:             if ($idtype eq 'concat') {
 7230:                 $newid = $id.$idtries;
 7231:             } elsif ($idtype eq 'addcode') {
 7232:                 $newid = $newid.&sixnum_code();
 7233:             } else {
 7234:                 $newid ++;
 7235:             }
 7236:             $idtries ++;
 7237:         }
 7238:         if (!exists($inuse{$prefix."\0".$newid})) {
 7239:             my %new_item =  (
 7240:                               $prefix."\0".$newid => $who,
 7241:                             );
 7242:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
 7243:                                                  $cdom,$cnum);
 7244:             if ($putresult ne 'ok') {
 7245:                 undef($newid);
 7246:                 $error = 'error saving new item: '.$putresult;
 7247:             }
 7248:         } else {
 7249:              undef($newid);
 7250:              $error = ('error: no unique suffix available for the new item ');
 7251:         }
 7252: #  remove lock
 7253:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
 7254:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
 7255:     } else {
 7256:         $error = "error: could not obtain lockfile\n";
 7257:         $dellock = 'ok';
 7258:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
 7259:             $dellock = 'nolock';
 7260:         }
 7261:     }
 7262:     return ($newid,$dellock,$error);
 7263: }
 7264: 
 7265: sub sixnum_code {
 7266:     my $code;
 7267:     for (0..6) {
 7268:         $code .= int( rand(9) );
 7269:     }
 7270:     return $code;
 7271: }
 7272: 
 7273: # -------------------------------------------------- portfolio access checking
 7274: 
 7275: sub portfolio_access {
 7276:     my ($requrl,$clientip) = @_;
 7277:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 7278:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
 7279:     if ($result) {
 7280:         my %setters;
 7281:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 7282:             my ($startblock,$endblock) =
 7283:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 7284:             if ($startblock && $endblock) {
 7285:                 return 'B';
 7286:             }
 7287:         } else {
 7288:             my ($startblock,$endblock) =
 7289:                 &Apache::loncommon::blockcheck(\%setters,'port');
 7290:             if ($startblock && $endblock) {
 7291:                 return 'B';
 7292:             }
 7293:         }
 7294:     }
 7295:     if ($result eq 'ok') {
 7296:        return 'F';
 7297:     } elsif ($result =~ /^[^:]+:guest_/) {
 7298:        return 'A';
 7299:     }
 7300:     return '';
 7301: }
 7302: 
 7303: sub get_portfolio_access {
 7304:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
 7305: 
 7306:     if (!ref($access_hash)) {
 7307: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 7308: 	my %access_controls = &get_access_controls($current_perms,$group,
 7309: 						   $file_name);
 7310: 	$access_hash = $access_controls{$file_name};
 7311:     }
 7312: 
 7313:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
 7314:     my $now = time;
 7315:     if (ref($access_hash) eq 'HASH') {
 7316:         foreach my $key (keys(%{$access_hash})) {
 7317:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 7318:             if ($start > $now) {
 7319:                 next;
 7320:             }
 7321:             if ($end && $end<$now) {
 7322:                 next;
 7323:             }
 7324:             if ($scope eq 'public') {
 7325:                 $public = $key;
 7326:                 last;
 7327:             } elsif ($scope eq 'guest') {
 7328:                 $guest = $key;
 7329:             } elsif ($scope eq 'domains') {
 7330:                 push(@domains,$key);
 7331:             } elsif ($scope eq 'users') {
 7332:                 push(@users,$key);
 7333:             } elsif ($scope eq 'course') {
 7334:                 push(@courses,$key);
 7335:             } elsif ($scope eq 'group') {
 7336:                 push(@groups,$key);
 7337:             } elsif ($scope eq 'ip') {
 7338:                 push(@ips,$key);
 7339:             }
 7340:         }
 7341:         if ($public) {
 7342:             return 'ok';
 7343:         } elsif (@ips > 0) {
 7344:             my $allowed;
 7345:             foreach my $ipkey (@ips) {
 7346:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
 7347:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
 7348:                         $allowed = 1;
 7349:                         last;
 7350:                     }
 7351:                 }
 7352:             }
 7353:             if ($allowed) {
 7354:                 return 'ok';
 7355:             }
 7356:         }
 7357:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 7358:             if ($guest) {
 7359:                 return $guest;
 7360:             }
 7361:         } else {
 7362:             if (@domains > 0) {
 7363:                 foreach my $domkey (@domains) {
 7364:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 7365:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 7366:                             return 'ok';
 7367:                         }
 7368:                     }
 7369:                 }
 7370:             }
 7371:             if (@users > 0) {
 7372:                 foreach my $userkey (@users) {
 7373:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 7374:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 7375:                             if (ref($item) eq 'HASH') {
 7376:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 7377:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 7378:                                     return 'ok';
 7379:                                 }
 7380:                             }
 7381:                         }
 7382:                     } 
 7383:                 }
 7384:             }
 7385:             my %roleshash;
 7386:             my @courses_and_groups = @courses;
 7387:             push(@courses_and_groups,@groups); 
 7388:             if (@courses_and_groups > 0) {
 7389:                 my (%allgroups,%allroles); 
 7390:                 my ($start,$end,$role,$sec,$group);
 7391:                 foreach my $envkey (%env) {
 7392:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 7393:                         my $cid = $2.'_'.$3; 
 7394:                         if ($1 eq 'gr') {
 7395:                             $group = $4;
 7396:                             $allgroups{$cid}{$group} = $env{$envkey};
 7397:                         } else {
 7398:                             if ($4 eq '') {
 7399:                                 $sec = 'none';
 7400:                             } else {
 7401:                                 $sec = $4;
 7402:                             }
 7403:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 7404:                         }
 7405:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 7406:                         my $cid = $2.'_'.$3;
 7407:                         if ($4 eq '') {
 7408:                             $sec = 'none';
 7409:                         } else {
 7410:                             $sec = $4;
 7411:                         }
 7412:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 7413:                     }
 7414:                 }
 7415:                 if (keys(%allroles) == 0) {
 7416:                     return;
 7417:                 }
 7418:                 foreach my $key (@courses_and_groups) {
 7419:                     my %content = %{$$access_hash{$key}};
 7420:                     my $cnum = $content{'number'};
 7421:                     my $cdom = $content{'domain'};
 7422:                     my $cid = $cdom.'_'.$cnum;
 7423:                     if (!exists($allroles{$cid})) {
 7424:                         next;
 7425:                     }    
 7426:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 7427:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 7428:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 7429:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 7430:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 7431:                         foreach my $role (keys(%{$allroles{$cid}})) {
 7432:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 7433:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 7434:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 7435:                                         if (grep/^all$/,@sections) {
 7436:                                             return 'ok';
 7437:                                         } else {
 7438:                                             if (grep/^$sec$/,@sections) {
 7439:                                                 return 'ok';
 7440:                                             }
 7441:                                         }
 7442:                                     }
 7443:                                 }
 7444:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 7445:                                     if (grep/^none$/,@groups) {
 7446:                                         return 'ok';
 7447:                                     }
 7448:                                 } else {
 7449:                                     if (grep/^all$/,@groups) {
 7450:                                         return 'ok';
 7451:                                     } 
 7452:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 7453:                                         if (grep/^$group$/,@groups) {
 7454:                                             return 'ok';
 7455:                                         }
 7456:                                     }
 7457:                                 } 
 7458:                             }
 7459:                         }
 7460:                     }
 7461:                 }
 7462:             }
 7463:             if ($guest) {
 7464:                 return $guest;
 7465:             }
 7466:         }
 7467:     }
 7468:     return;
 7469: }
 7470: 
 7471: sub course_group_datechecker {
 7472:     my ($dates,$now,$status) = @_;
 7473:     my ($start,$end) = split(/\./,$dates);
 7474:     if (!$start && !$end) {
 7475:         return 'ok';
 7476:     }
 7477:     if (grep/^active$/,@{$status}) {
 7478:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 7479:             return 'ok';
 7480:         }
 7481:     }
 7482:     if (grep/^previous$/,@{$status}) {
 7483:         if ($end > $now ) {
 7484:             return 'ok';
 7485:         }
 7486:     }
 7487:     if (grep/^future$/,@{$status}) {
 7488:         if ($start > $now) {
 7489:             return 'ok';
 7490:         }
 7491:     }
 7492:     return; 
 7493: }
 7494: 
 7495: sub parse_portfolio_url {
 7496:     my ($url) = @_;
 7497: 
 7498:     my ($type,$udom,$unum,$group,$file_name);
 7499:     
 7500:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 7501: 	$type = 1;
 7502:         $udom = $1;
 7503:         $unum = $2;
 7504:         $file_name = $3;
 7505:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 7506: 	$type = 2;
 7507:         $udom = $1;
 7508:         $unum = $2;
 7509:         $group = $3;
 7510:         $file_name = $3.'/'.$4;
 7511:     }
 7512:     if (wantarray) {
 7513: 	return ($type,$udom,$unum,$file_name,$group);
 7514:     }
 7515:     return $type;
 7516: }
 7517: 
 7518: sub is_portfolio_url {
 7519:     my ($url) = @_;
 7520:     return scalar(&parse_portfolio_url($url));
 7521: }
 7522: 
 7523: sub is_portfolio_file {
 7524:     my ($file) = @_;
 7525:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 7526:         return 1;
 7527:     }
 7528:     return;
 7529: }
 7530: 
 7531: sub usertools_access {
 7532:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 7533:     my ($access,%tools);
 7534:     if ($context eq '') {
 7535:         $context = 'tools';
 7536:     }
 7537:     if ($context eq 'requestcourses') {
 7538:         %tools = (
 7539:                       official   => 1,
 7540:                       unofficial => 1,
 7541:                       community  => 1,
 7542:                       textbook   => 1,
 7543:                  );
 7544:     } elsif ($context eq 'requestauthor') {
 7545:         %tools = (
 7546:                       requestauthor => 1,
 7547:                  );
 7548:     } else {
 7549:         %tools = (
 7550:                       aboutme   => 1,
 7551:                       blog      => 1,
 7552:                       webdav    => 1,
 7553:                       portfolio => 1,
 7554:                  );
 7555:     }
 7556:     return if (!defined($tools{$tool}));
 7557: 
 7558:     if (($udom eq '') || ($uname eq '')) {
 7559:         $udom = $env{'user.domain'};
 7560:         $uname = $env{'user.name'};
 7561:     }
 7562: 
 7563:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7564:         if ($action ne 'reload') {
 7565:             if ($context eq 'requestcourses') {
 7566:                 return $env{'environment.canrequest.'.$tool};
 7567:             } elsif ($context eq 'requestauthor') {
 7568:                 return $env{'environment.canrequest.author'};
 7569:             } else {
 7570:                 return $env{'environment.availabletools.'.$tool};
 7571:             }
 7572:         }
 7573:     }
 7574: 
 7575:     my ($toolstatus,$inststatus,$envkey);
 7576:     if ($context eq 'requestauthor') {
 7577:         $envkey = $context;
 7578:     } else {
 7579:         $envkey = $context.'.'.$tool;
 7580:     }
 7581: 
 7582:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 7583:          ($action ne 'reload')) {
 7584:         $toolstatus = $env{'environment.'.$envkey};
 7585:         $inststatus = $env{'environment.inststatus'};
 7586:     } else {
 7587:         if (ref($userenvref) eq 'HASH') {
 7588:             $toolstatus = $userenvref->{$envkey};
 7589:             $inststatus = $userenvref->{'inststatus'};
 7590:         } else {
 7591:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 7592:             $toolstatus = $userenv{$envkey};
 7593:             $inststatus = $userenv{'inststatus'};
 7594:         }
 7595:     }
 7596: 
 7597:     if ($toolstatus ne '') {
 7598:         if ($toolstatus) {
 7599:             $access = 1;
 7600:         } else {
 7601:             $access = 0;
 7602:         }
 7603:         return $access;
 7604:     }
 7605: 
 7606:     my ($is_adv,%domdef);
 7607:     if (ref($is_advref) eq 'HASH') {
 7608:         $is_adv = $is_advref->{'is_adv'};
 7609:     } else {
 7610:         $is_adv = &is_advanced_user($udom,$uname);
 7611:     }
 7612:     if (ref($domdefref) eq 'HASH') {
 7613:         %domdef = %{$domdefref};
 7614:     } else {
 7615:         %domdef = &get_domain_defaults($udom);
 7616:     }
 7617:     if (ref($domdef{$tool}) eq 'HASH') {
 7618:         if ($is_adv) {
 7619:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 7620:                 if ($domdef{$tool}{'_LC_adv'}) { 
 7621:                     $access = 1;
 7622:                 } else {
 7623:                     $access = 0;
 7624:                 }
 7625:                 return $access;
 7626:             }
 7627:         }
 7628:         if ($inststatus ne '') {
 7629:             my ($hasaccess,$hasnoaccess);
 7630:             foreach my $affiliation (split(/:/,$inststatus)) {
 7631:                 if ($domdef{$tool}{$affiliation} ne '') { 
 7632:                     if ($domdef{$tool}{$affiliation}) {
 7633:                         $hasaccess = 1;
 7634:                     } else {
 7635:                         $hasnoaccess = 1;
 7636:                     }
 7637:                 }
 7638:             }
 7639:             if ($hasaccess || $hasnoaccess) {
 7640:                 if ($hasaccess) {
 7641:                     $access = 1;
 7642:                 } elsif ($hasnoaccess) {
 7643:                     $access = 0; 
 7644:                 }
 7645:                 return $access;
 7646:             }
 7647:         } else {
 7648:             if ($domdef{$tool}{'default'} ne '') {
 7649:                 if ($domdef{$tool}{'default'}) {
 7650:                     $access = 1;
 7651:                 } elsif ($domdef{$tool}{'default'} == 0) {
 7652:                     $access = 0;
 7653:                 }
 7654:                 return $access;
 7655:             }
 7656:         }
 7657:     } else {
 7658:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 7659:             $access = 1;
 7660:         } else {
 7661:             $access = 0;
 7662:         }
 7663:         return $access;
 7664:     }
 7665: }
 7666: 
 7667: sub is_course_owner {
 7668:     my ($cdom,$cnum,$udom,$uname) = @_;
 7669:     if (($udom eq '') || ($uname eq '')) {
 7670:         $udom = $env{'user.domain'};
 7671:         $uname = $env{'user.name'};
 7672:     }
 7673:     unless (($udom eq '') || ($uname eq '')) {
 7674:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 7675:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 7676:                 return 1;
 7677:             } else {
 7678:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 7679:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 7680:                     return 1;
 7681:                 }
 7682:             }
 7683:         }
 7684:     }
 7685:     return;
 7686: }
 7687: 
 7688: sub is_advanced_user {
 7689:     my ($udom,$uname) = @_;
 7690:     if ($udom ne '' && $uname ne '') {
 7691:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7692:             if (wantarray) {
 7693:                 return ($env{'user.adv'},$env{'user.author'});
 7694:             } else {
 7695:                 return $env{'user.adv'};
 7696:             }
 7697:         }
 7698:     }
 7699:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 7700:     my %allroles;
 7701:     my ($is_adv,$is_author);
 7702:     foreach my $role (keys(%roleshash)) {
 7703:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 7704:         my $area = '/'.$tdomain.'/'.$trest;
 7705:         if ($sec ne '') {
 7706:             $area .= '/'.$sec;
 7707:         }
 7708:         if (($area ne '') && ($trole ne '')) {
 7709:             my $spec=$trole.'.'.$area;
 7710:             if ($trole =~ /^cr\//) {
 7711:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 7712:             } elsif ($trole ne 'gr') {
 7713:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 7714:             }
 7715:             if ($trole eq 'au') {
 7716:                 $is_author = 1;
 7717:             }
 7718:         }
 7719:     }
 7720:     foreach my $role (keys(%allroles)) {
 7721:         last if ($is_adv);
 7722:         foreach my $item (split(/:/,$allroles{$role})) {
 7723:             if ($item ne '') {
 7724:                 my ($privilege,$restrictions)=split(/&/,$item);
 7725:                 if ($privilege eq 'adv') {
 7726:                     $is_adv = 1;
 7727:                     last;
 7728:                 }
 7729:             }
 7730:         }
 7731:     }
 7732:     if (wantarray) {
 7733:         return ($is_adv,$is_author);
 7734:     }
 7735:     return $is_adv;
 7736: }
 7737: 
 7738: sub check_can_request {
 7739:     my ($dom,$can_request,$request_domains) = @_;
 7740:     my $canreq = 0;
 7741:     my ($types,$typename) = &Apache::loncommon::course_types();
 7742:     my @options = ('approval','validate','autolimit');
 7743:     my $optregex = join('|',@options);
 7744:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 7745:         foreach my $type (@{$types}) {
 7746:             if (&usertools_access($env{'user.name'},
 7747:                                   $env{'user.domain'},
 7748:                                   $type,undef,'requestcourses')) {
 7749:                 $canreq ++;
 7750:                 if (ref($request_domains) eq 'HASH') {
 7751:                     push(@{$request_domains->{$type}},$env{'user.domain'});
 7752:                 }
 7753:                 if ($dom eq $env{'user.domain'}) {
 7754:                     $can_request->{$type} = 1;
 7755:                 }
 7756:             }
 7757:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
 7758:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 7759:                 if (@curr > 0) {
 7760:                     foreach my $item (@curr) {
 7761:                         if (ref($request_domains) eq 'HASH') {
 7762:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 7763:                             if ($otherdom ne '') {
 7764:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 7765:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 7766:                                         push(@{$request_domains->{$type}},$otherdom);
 7767:                                     }
 7768:                                 } else {
 7769:                                     push(@{$request_domains->{$type}},$otherdom);
 7770:                                 }
 7771:                             }
 7772:                         }
 7773:                     }
 7774:                     unless($dom eq $env{'user.domain'}) {
 7775:                         $canreq ++;
 7776:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 7777:                             $can_request->{$type} = 1;
 7778:                         }
 7779:                     }
 7780:                 }
 7781:             }
 7782:         }
 7783:     }
 7784:     return $canreq;
 7785: }
 7786: 
 7787: # ---------------------------------------------- Custom access rule evaluation
 7788: 
 7789: sub customaccess {
 7790:     my ($priv,$uri)=@_;
 7791:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 7792:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 7793:     $udom = &LONCAPA::clean_domain($udom);
 7794:     $ucrs = &LONCAPA::clean_username($ucrs);
 7795:     my $access=0;
 7796:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 7797: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 7798: 	if ($type eq 'user') {
 7799: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 7800: 		my ($tdom,$tuname)=split(m{/},$scope);
 7801: 		if ($tdom) {
 7802: 		    if ($tdom ne $env{'user.domain'}) { next; }
 7803: 		}
 7804: 		if ($tuname) {
 7805: 		    if ($tuname ne $env{'user.name'}) { next; }
 7806: 		}
 7807: 		$access=($effect eq 'allow');
 7808: 		last;
 7809: 	    }
 7810: 	} else {
 7811: 	    if ($role) {
 7812: 		if ($role ne $urole) { next; }
 7813: 	    }
 7814: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 7815: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 7816: 		if ($tdom) {
 7817: 		    if ($tdom ne $udom) { next; }
 7818: 		}
 7819: 		if ($tcrs) {
 7820: 		    if ($tcrs ne $ucrs) { next; }
 7821: 		}
 7822: 		if ($tsec) {
 7823: 		    if ($tsec ne $usec) { next; }
 7824: 		}
 7825: 		$access=($effect eq 'allow');
 7826: 		last;
 7827: 	    }
 7828: 	    if ($realm eq '' && $role eq '') {
 7829: 		$access=($effect eq 'allow');
 7830: 	    }
 7831: 	}
 7832:     }
 7833:     return $access;
 7834: }
 7835: 
 7836: # ------------------------------------------------- Check for a user privilege
 7837: 
 7838: sub allowed {
 7839:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
 7840:     my $ver_orguri=$uri;
 7841:     $uri=&deversion($uri);
 7842:     my $orguri=$uri;
 7843:     $uri=&declutter($uri);
 7844: 
 7845:     if ($priv eq 'evb') {
 7846: # Evade communication block restrictions for specified role in a course
 7847:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 7848:             return $1;
 7849:         } else {
 7850:             return;
 7851:         }
 7852:     }
 7853: 
 7854:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 7855: # Free bre access to adm and meta resources
 7856:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|ext\.tool)$})) 
 7857: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 7858: 	&& ($priv eq 'bre')) {
 7859: 	return 'F';
 7860:     }
 7861: 
 7862: # Free bre access to user's own portfolio contents
 7863:     my ($space,$domain,$name,@dir)=split('/',$uri);
 7864:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 7865: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 7866:         my %setters;
 7867:         my ($startblock,$endblock) = 
 7868:             &Apache::loncommon::blockcheck(\%setters,'port');
 7869:         if ($startblock && $endblock) {
 7870:             return 'B';
 7871:         } else {
 7872:             return 'F';
 7873:         }
 7874:     }
 7875: 
 7876: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 7877:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 7878:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 7879:         if (exists($env{'request.course.id'})) {
 7880:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7881:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7882:             if (($domain eq $cdom) && ($name eq $cnum)) {
 7883:                 my $courseprivid=$env{'request.course.id'};
 7884:                 $courseprivid=~s/\_/\//;
 7885:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 7886:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 7887:                     return $1; 
 7888:                 } else {
 7889:                     if ($env{'request.course.sec'}) {
 7890:                         $courseprivid.='/'.$env{'request.course.sec'};
 7891:                     }
 7892:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 7893:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 7894:                         return $2;
 7895:                     }
 7896:                 }
 7897:             }
 7898:         }
 7899:     }
 7900: 
 7901: # Free bre to public access
 7902: 
 7903:     if ($priv eq 'bre') {
 7904:         my $copyright=&metadata($uri,'copyright');
 7905: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 7906:            return 'F'; 
 7907:         }
 7908:         if ($copyright eq 'priv') {
 7909:             $uri=~/([^\/]+)\/([^\/]+)\//;
 7910: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 7911: 		return '';
 7912:             }
 7913:         }
 7914:         if ($copyright eq 'domain') {
 7915:             $uri=~/([^\/]+)\/([^\/]+)\//;
 7916: 	    unless (($env{'user.domain'} eq $1) ||
 7917:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 7918: 		return '';
 7919:             }
 7920:         }
 7921:         if ($env{'request.role'}=~ /li\.\//) {
 7922:             # Library role, so allow browsing of resources in this domain.
 7923:             return 'F';
 7924:         }
 7925:         if ($copyright eq 'custom') {
 7926: 	    unless (&customaccess($priv,$uri)) { return ''; }
 7927:         }
 7928:     }
 7929:     # Domain coordinator is trying to create a course
 7930:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 7931:         # uri is the requested domain in this case.
 7932:         # comparison to 'request.role.domain' shows if the user has selected
 7933:         # a role of dc for the domain in question.
 7934:         return 'F' if ($uri eq $env{'request.role.domain'});
 7935:     }
 7936: 
 7937:     my $thisallowed='';
 7938:     my $statecond=0;
 7939:     my $courseprivid='';
 7940: 
 7941:     my $ownaccess;
 7942:     # Community Coordinator or Assistant Co-author browsing resource space.
 7943:     if (($priv eq 'bro') && ($env{'user.author'})) {
 7944:         if ($uri eq '') {
 7945:             $ownaccess = 1;
 7946:         } else {
 7947:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 7948:                 my $udom = $env{'user.domain'};
 7949:                 my $uname = $env{'user.name'};
 7950:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 7951:                     $ownaccess = 1;
 7952:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 7953:                     unless ($uri =~ m{\.\./}) {
 7954:                         $ownaccess = 1;
 7955:                     }
 7956:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 7957:                     my $now = time;
 7958:                     if ($uri =~ m{^([^/]+)/?$}) {
 7959:                         my $adom = $1;
 7960:                         foreach my $key (keys(%env)) {
 7961:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 7962:                                 my ($start,$end) = split('.',$env{$key});
 7963:                                 if (($now >= $start) && (!$end || $end < $now)) {
 7964:                                     $ownaccess = 1;
 7965:                                     last;
 7966:                                 }
 7967:                             }
 7968:                         }
 7969:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 7970:                         my $adom = $1;
 7971:                         my $aname = $2;
 7972:                         foreach my $role ('ca','aa') { 
 7973:                             if ($env{"user.role.$role./$adom/$aname"}) {
 7974:                                 my ($start,$end) =
 7975:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 7976:                                 if (($now >= $start) && (!$end || $end < $now)) {
 7977:                                     $ownaccess = 1;
 7978:                                     last;
 7979:                                 }
 7980:                             }
 7981:                         }
 7982:                     }
 7983:                 }
 7984:             }
 7985:         }
 7986:     }
 7987: 
 7988: # Course
 7989: 
 7990:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 7991:         unless (($priv eq 'bro') && (!$ownaccess)) {
 7992:             $thisallowed.=$1;
 7993:         }
 7994:     }
 7995: 
 7996: # Domain
 7997: 
 7998:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 7999:        =~/\Q$priv\E\&([^\:]*)/) {
 8000:         unless (($priv eq 'bro') && (!$ownaccess)) {
 8001:             $thisallowed.=$1;
 8002:         }
 8003:     }
 8004: 
 8005: # User who is not author or co-author might still be able to edit
 8006: # resource of an author in the domain (e.g., if Domain Coordinator).
 8007:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 8008:         (&allowed('mdc',$env{'request.course.id'}))) {
 8009:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 8010:             $thisallowed.=$1;
 8011:         }
 8012:     }
 8013: 
 8014: # Course: uri itself is a course
 8015:     my $courseuri=$uri;
 8016:     $courseuri=~s/\_(\d)/\/$1/;
 8017:     $courseuri=~s/^([^\/])/\/$1/;
 8018: 
 8019:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 8020:        =~/\Q$priv\E\&([^\:]*)/) {
 8021:         if ($priv eq 'mip') {
 8022:             my $rem = $1;
 8023:             if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
 8024:                 ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
 8025:                 my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8026:                 if ($cdom ne '') {
 8027:                     my %passwdconf = &get_passwdconf($cdom);
 8028:                     if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
 8029:                         if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
 8030:                             if (@{$passwdconf{'crsownerchg'}{'by'}}) {
 8031:                                 my @inststatuses = split(':',$env{'environment.inststatus'});
 8032:                                 unless (@inststatuses) {
 8033:                                     @inststatuses = ('default');
 8034:                                 }
 8035:                                 foreach my $status (@inststatuses) {
 8036:                                     if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
 8037:                                         $thisallowed.=$rem;
 8038:                                     }
 8039:                                 }
 8040:                             }
 8041:                         }
 8042:                     }
 8043:                 }
 8044:             }
 8045:         } else {
 8046:             unless (($priv eq 'bro') && (!$ownaccess)) {
 8047:                 $thisallowed.=$1;
 8048:             }
 8049:         }
 8050:     }
 8051: 
 8052: # URI is an uploaded document for this course, default permissions don't matter
 8053: # not allowing 'edit' access (editupload) to uploaded course docs
 8054:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 8055: 	$thisallowed='';
 8056:         my ($match)=&is_on_map($uri);
 8057:         if ($match) {
 8058:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 8059:                   =~/\Q$priv\E\&([^\:]*)/) {
 8060:                 my $value = $1;
 8061:                 if ($noblockcheck) {
 8062:                     $thisallowed.=$value;
 8063:                 } else {
 8064:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
 8065:                     if (@blockers > 0) {
 8066:                         $thisallowed = 'B';
 8067:                     } else {
 8068:                         $thisallowed.=$value;
 8069:                     }
 8070:                 }
 8071:             }
 8072:         } else {
 8073:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 8074:             if ($refuri) {
 8075:                 if ($refuri =~ m|^/adm/|) {
 8076:                     $thisallowed='F';
 8077:                 } else {
 8078:                     $refuri=&declutter($refuri);
 8079:                     my ($match) = &is_on_map($refuri);
 8080:                     if ($match) {
 8081:                         if ($noblockcheck) {
 8082:                             $thisallowed='F';
 8083:                         } else {
 8084:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 8085:                             if (@blockers > 0) {
 8086:                                 $thisallowed = 'B';
 8087:                             } else {
 8088:                                 $thisallowed='F';
 8089:                             }
 8090:                         }
 8091:                     }
 8092:                 }
 8093:             }
 8094:         }
 8095:     }
 8096: 
 8097:     if ($priv eq 'bre'
 8098: 	&& $thisallowed ne 'F' 
 8099: 	&& $thisallowed ne '2'
 8100: 	&& &is_portfolio_url($uri)) {
 8101: 	$thisallowed = &portfolio_access($uri,$clientip);
 8102:     }
 8103:     
 8104: # Full access at system, domain or course-wide level? Exit.
 8105:     if ($thisallowed=~/F/) {
 8106: 	return 'F';
 8107:     }
 8108: 
 8109: # If this is generating or modifying users, exit with special codes
 8110: 
 8111:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 8112: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 8113: 	    my ($audom,$auname)=split('/',$uri);
 8114: # no author name given, so this just checks on the general right to make a co-author in this domain
 8115: 	    unless ($auname) { return $thisallowed; }
 8116: # an author name is given, so we are about to actually make a co-author for a certain account
 8117: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 8118: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 8119: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 8120: 	}
 8121: 	return $thisallowed;
 8122:     }
 8123: #
 8124: # Gathered so far: system, domain and course wide privileges
 8125: #
 8126: # Course: See if uri or referer is an individual resource that is part of 
 8127: # the course
 8128: 
 8129:     if ($env{'request.course.id'}) {
 8130: 
 8131: # If this is modifying password (internal auth) domains must match for user and user's role.
 8132: 
 8133:         if ($priv eq 'mip') {
 8134:             if ($env{'user.domain'} eq $env{'request.role.domain'}) {
 8135:                 return $thisallowed;
 8136:             } else {
 8137:                 return '';
 8138:             }
 8139:         }
 8140: 
 8141:        $courseprivid=$env{'request.course.id'};
 8142:        if ($env{'request.course.sec'}) {
 8143:           $courseprivid.='/'.$env{'request.course.sec'};
 8144:        }
 8145:        $courseprivid=~s/\_/\//;
 8146:        my $checkreferer=1;
 8147:        my ($match,$cond)=&is_on_map($uri);
 8148:        if ($match) {
 8149:            $statecond=$cond;
 8150:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 8151:                =~/\Q$priv\E\&([^\:]*)/) {
 8152:                my $value = $1;
 8153:                if ($priv eq 'bre') {
 8154:                    if ($noblockcheck) {
 8155:                        $thisallowed.=$value;
 8156:                    } else {
 8157:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
 8158:                        if (@blockers > 0) {
 8159:                            $thisallowed = 'B';
 8160:                        } else {
 8161:                            $thisallowed.=$value;
 8162:                        }
 8163:                    }
 8164:                } else {
 8165:                    $thisallowed.=$value;
 8166:                }
 8167:                $checkreferer=0;
 8168:            }
 8169:        }
 8170:        
 8171:        if ($checkreferer) {
 8172: 	  my $refuri=$env{'httpref.'.$orguri};
 8173:             unless ($refuri) {
 8174:                 foreach my $key (keys(%env)) {
 8175: 		    if ($key=~/^httpref\..*\*/) {
 8176: 			my $pattern=$key;
 8177:                         $pattern=~s/^httpref\.\/res\///;
 8178:                         $pattern=~s/\*/\[\^\/\]\+/g;
 8179:                         $pattern=~s/\//\\\//g;
 8180:                         if ($orguri=~/$pattern/) {
 8181: 			    $refuri=$env{$key};
 8182:                         }
 8183:                     }
 8184:                 }
 8185:             }
 8186: 
 8187:          if ($refuri) { 
 8188: 	  $refuri=&declutter($refuri);
 8189:           my ($match,$cond)=&is_on_map($refuri);
 8190:             if ($match) {
 8191:               my $refstatecond=$cond;
 8192:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 8193:                   =~/\Q$priv\E\&([^\:]*)/) {
 8194:                   my $value = $1;
 8195:                   if ($priv eq 'bre') {
 8196:                       if ($noblockcheck) {
 8197:                           $thisallowed.=$value;
 8198:                       } else {
 8199:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 8200:                           if (@blockers > 0) {
 8201:                               $thisallowed = 'B';
 8202:                           } else {
 8203:                               $thisallowed.=$value;
 8204:                           }
 8205:                       }
 8206:                   } else {
 8207:                       $thisallowed.=$value;
 8208:                   }
 8209:                   $uri=$refuri;
 8210:                   $statecond=$refstatecond;
 8211:               }
 8212:           }
 8213:         }
 8214:        }
 8215:    }
 8216: 
 8217: #
 8218: # Gathered now: all privileges that could apply, and condition number
 8219: # 
 8220: #
 8221: # Full or no access?
 8222: #
 8223: 
 8224:     if ($thisallowed=~/F/) {
 8225: 	return 'F';
 8226:     }
 8227: 
 8228:     unless ($thisallowed) {
 8229:         return '';
 8230:     }
 8231: 
 8232: # Restrictions exist, deal with them
 8233: #
 8234: #   C:according to course preferences
 8235: #   R:according to resource settings
 8236: #   L:unless locked
 8237: #   X:according to user session state
 8238: #
 8239: 
 8240: # Possibly locked functionality, check all courses
 8241: # Locks might take effect only after 10 minutes cache expiration for other
 8242: # courses, and 2 minutes for current course
 8243: 
 8244:     my $envkey;
 8245:     if ($thisallowed=~/L/) {
 8246:         foreach $envkey (keys(%env)) {
 8247:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 8248:                my $courseid=$2;
 8249:                my $roleid=$1.'.'.$2;
 8250:                $courseid=~s/^\///;
 8251:                my $expiretime=600;
 8252:                if ($env{'request.role'} eq $roleid) {
 8253: 		  $expiretime=120;
 8254:                }
 8255: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 8256:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 8257:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 8258: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 8259:                }
 8260:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 8261:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 8262: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 8263:                        &log($env{'user.domain'},$env{'user.name'},
 8264:                             $env{'user.home'},
 8265:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 8266:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 8267:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 8268: 		       return '';
 8269:                    }
 8270:                }
 8271:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 8272:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 8273: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 8274:                        &log($env{'user.domain'},$env{'user.name'},
 8275:                             $env{'user.home'},
 8276:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 8277:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 8278:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 8279: 		       return '';
 8280:                    }
 8281:                }
 8282: 	   }
 8283:        }
 8284:     }
 8285:    
 8286: #
 8287: # Rest of the restrictions depend on selected course
 8288: #
 8289: 
 8290:     unless ($env{'request.course.id'}) {
 8291: 	if ($thisallowed eq 'A') {
 8292: 	    return 'A';
 8293:         } elsif ($thisallowed eq 'B') {
 8294:             return 'B';
 8295: 	} else {
 8296: 	    return '1';
 8297: 	}
 8298:     }
 8299: 
 8300: #
 8301: # Now user is definitely in a course
 8302: #
 8303: 
 8304: 
 8305: # Course preferences
 8306: 
 8307:    if ($thisallowed=~/C/) {
 8308:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 8309:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 8310:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 8311: 	   =~/\Q$rolecode\E/) {
 8312: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 8313: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 8314: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 8315: 			$env{'request.course.id'});
 8316: 	   }
 8317:            return '';
 8318:        }
 8319: 
 8320:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 8321: 	   =~/\Q$unamedom\E/) {
 8322: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 8323: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 8324: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 8325: 			$env{'request.course.id'});
 8326: 	   }
 8327:            return '';
 8328:        }
 8329:    }
 8330: 
 8331: # Resource preferences
 8332: 
 8333:    if ($thisallowed=~/R/) {
 8334:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 8335:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 8336: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 8337: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 8338: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 8339: 	   }
 8340: 	   return '';
 8341:        }
 8342:    }
 8343: 
 8344: # Restricted by state or randomout?
 8345: 
 8346:    if ($thisallowed=~/X/) {
 8347:       if ($env{'acc.randomout'}) {
 8348: 	 if (!$symb) { $symb=&symbread($uri,1); }
 8349:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 8350:             return ''; 
 8351:          }
 8352:       }
 8353:       if (&condval($statecond)) {
 8354: 	 return '2';
 8355:       } else {
 8356:          return '';
 8357:       }
 8358:    }
 8359: 
 8360:     if ($thisallowed eq 'A') {
 8361: 	return 'A';
 8362:     } elsif ($thisallowed eq 'B') {
 8363:         return 'B';
 8364:     }
 8365:    return 'F';
 8366: }
 8367: 
 8368: # ------------------------------------------- Check construction space access
 8369: 
 8370: sub constructaccess {
 8371:     my ($url,$setpriv)=@_;
 8372: 
 8373: # We do not allow editing of previous versions of files
 8374:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
 8375: 
 8376: # Get username and domain from URL
 8377:     my ($ownername,$ownerdomain,$ownerhome);
 8378: 
 8379:     ($ownerdomain,$ownername) =
 8380:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)(?:/|$)});
 8381: 
 8382: # The URL does not really point to any authorspace, forget it
 8383:     unless (($ownername) && ($ownerdomain)) { return ''; }
 8384: 
 8385: # Now we need to see if the user has access to the authorspace of
 8386: # $ownername at $ownerdomain
 8387: 
 8388:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
 8389: # Real author for this?
 8390:        $ownerhome = $env{'user.home'};
 8391:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
 8392:           return ($ownername,$ownerdomain,$ownerhome);
 8393:        }
 8394:     } else {
 8395: # Co-author for this?
 8396:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
 8397:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
 8398:             $ownerhome = &homeserver($ownername,$ownerdomain);
 8399:             return ($ownername,$ownerdomain,$ownerhome);
 8400:         }
 8401:     }
 8402: 
 8403: # We don't have any access right now. If we are not possibly going to do anything about this,
 8404: # we might as well leave
 8405:    unless ($setpriv) { return ''; }
 8406: 
 8407: # Backdoor access?
 8408:     my $allowed=&allowed('eco',$ownerdomain);
 8409: # Nope
 8410:     unless ($allowed) { return ''; }
 8411: # Looks like we may have access, but could be locked by the owner of the construction space
 8412:     if ($allowed eq 'U') {
 8413:         my %blocked=&get('environment',['domcoord.author'],
 8414:                          $ownerdomain,$ownername);
 8415: # Is blocked by owner
 8416:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
 8417:     }
 8418:     if (($allowed eq 'F') || ($allowed eq 'U')) {
 8419: # Grant temporary access
 8420:         my $then=$env{'user.login.time'};
 8421:         my $update=$env{'user.update.time'};
 8422:         if (!$update) { $update = $then; }
 8423:         my $refresh=$env{'user.refresh.time'};
 8424:         if (!$refresh) { $refresh = $update; }
 8425:         my $now = time;
 8426:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
 8427:                            $now,'ca','constructaccess');
 8428:         $ownerhome = &homeserver($ownername,$ownerdomain);
 8429:         return($ownername,$ownerdomain,$ownerhome);
 8430:     }
 8431: # No business here
 8432:     return '';
 8433: }
 8434: 
 8435: # ----------------------------------------------------------- Content Blocking
 8436: 
 8437: {
 8438: # Caches for faster Course Contents display where content blocking
 8439: # is in operation (i.e., interval param set) for timed quiz.
 8440: #
 8441: # User for whom data are being temporarily cached.
 8442: my $cacheduser='';
 8443: # Cached blockers for this user (a hash of blocking items).
 8444: my %cachedblockers=();
 8445: # When the data were last cached.
 8446: my $cachedlast='';
 8447: 
 8448: sub load_all_blockers {
 8449:     my ($uname,$udom,$blocks)=@_;
 8450:     if (($uname ne '') && ($udom ne '')) {
 8451:         if (($cacheduser eq $uname.':'.$udom) &&
 8452:             (abs($cachedlast-time)<5)) {
 8453:             return;
 8454:         }
 8455:     }
 8456:     $cachedlast=time;
 8457:     $cacheduser=$uname.':'.$udom;
 8458:     %cachedblockers = &get_commblock_resources($blocks);
 8459: }
 8460: 
 8461: sub get_comm_blocks {
 8462:     my ($cdom,$cnum) = @_;
 8463:     if ($cdom eq '' || $cnum eq '') {
 8464:         return unless ($env{'request.course.id'});
 8465:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8466:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8467:     }
 8468:     my %commblocks;
 8469:     my $hashid=$cdom.'_'.$cnum;
 8470:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 8471:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 8472:         %commblocks = %{$blocksref};
 8473:     } else {
 8474:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 8475:         my $cachetime = 600;
 8476:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 8477:     }
 8478:     return %commblocks;
 8479: }
 8480: 
 8481: sub get_commblock_resources {
 8482:     my ($blocks) = @_;
 8483:     my %blockers = ();
 8484:     return %blockers unless ($env{'request.course.id'});
 8485:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 8486:     my %commblocks;
 8487:     if (ref($blocks) eq 'HASH') {
 8488:         %commblocks = %{$blocks};
 8489:     } else {
 8490:         %commblocks = &get_comm_blocks();
 8491:     }
 8492:     return %blockers unless (keys(%commblocks) > 0);
 8493:     my $navmap = Apache::lonnavmaps::navmap->new();
 8494:     return %blockers unless (ref($navmap));
 8495:     my $now = time;
 8496:     foreach my $block (keys(%commblocks)) {
 8497:         if ($block =~ /^(\d+)____(\d+)$/) {
 8498:             my ($start,$end) = ($1,$2);
 8499:             if ($start <= $now && $end >= $now) {
 8500:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 8501:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 8502:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 8503:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 8504:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
 8505:                             }
 8506:                         }
 8507:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 8508:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 8509:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 8510:                             }
 8511:                         }
 8512:                     }
 8513:                 }
 8514:             }
 8515:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 8516:             my $item = $1;
 8517:             my @to_test;
 8518:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 8519:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 8520:                     my @interval;
 8521:                     my $type = 'map';
 8522:                     if ($item eq 'course') {
 8523:                         $type = 'course';
 8524:                         @interval=&EXT("resource.0.interval");
 8525:                     } else {
 8526:                         if ($item =~ /___\d+___/) {
 8527:                             $type = 'resource';
 8528:                             @interval=&EXT("resource.0.interval",$item);
 8529:                             if (ref($navmap)) {
 8530:                                 my $res = $navmap->getBySymb($item);
 8531:                                 push(@to_test,$res);
 8532:                             }
 8533:                         } else {
 8534:                             my $mapsymb = &symbread($item,1);
 8535:                             if ($mapsymb) {
 8536:                                 if (ref($navmap)) {
 8537:                                     my $mapres = $navmap->getBySymb($mapsymb);
 8538:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
 8539:                                     foreach my $res (@to_test) {
 8540:                                         my $symb = $res->symb();
 8541:                                         next if ($symb eq $mapsymb);
 8542:                                         if ($symb ne '') {
 8543:                                             @interval=&EXT("resource.0.interval",$symb);
 8544:                                             if ($interval[1] eq 'map') {
 8545:                                                 last;
 8546:                                             }
 8547:                                         }
 8548:                                     }
 8549:                                 }
 8550:                             }
 8551:                         }
 8552:                     }
 8553:                     if ($interval[0] =~ /^(\d+)/) {
 8554:                         my $timelimit = $1; 
 8555:                         my $first_access;
 8556:                         if ($type eq 'resource') {
 8557:                             $first_access=&get_first_access($interval[1],$item);
 8558:                         } elsif ($type eq 'map') {
 8559:                             $first_access=&get_first_access($interval[1],undef,$item);
 8560:                         } else {
 8561:                             $first_access=&get_first_access($interval[1]);
 8562:                         }
 8563:                         if ($first_access) {
 8564:                             my $timesup = $first_access+$timelimit;
 8565:                             if ($timesup > $now) {
 8566:                                 my $activeblock;
 8567:                                 foreach my $res (@to_test) {
 8568:                                     if ($res->answerable()) {
 8569:                                         $activeblock = 1;
 8570:                                         last;
 8571:                                     }
 8572:                                 }
 8573:                                 if ($activeblock) {
 8574:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 8575:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 8576:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
 8577:                                          }
 8578:                                     }
 8579:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 8580:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 8581:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 8582:                                         }
 8583:                                     }
 8584:                                 }
 8585:                             }
 8586:                         }
 8587:                     }
 8588:                 }
 8589:             }
 8590:         }
 8591:     }
 8592:     return %blockers;
 8593: }
 8594: 
 8595: sub has_comm_blocking {
 8596:     my ($priv,$symb,$uri,$blocks) = @_;
 8597:     my @blockers;
 8598:     return unless ($env{'request.course.id'});
 8599:     return unless ($priv eq 'bre');
 8600:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 8601:     return if ($env{'request.state'} eq 'construct');
 8602:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
 8603:     return unless (keys(%cachedblockers) > 0);
 8604:     my (%possibles,@symbs);
 8605:     if (!$symb) {
 8606:         $symb = &symbread($uri,1,1,1,\%possibles);
 8607:     }
 8608:     if ($symb) {
 8609:         @symbs = ($symb);
 8610:     } elsif (keys(%possibles)) {
 8611:         @symbs = keys(%possibles);
 8612:     }
 8613:     my $noblock;
 8614:     foreach my $symb (@symbs) {
 8615:         last if ($noblock);
 8616:         my ($map,$resid,$resurl)=&decode_symb($symb);
 8617:         foreach my $block (keys(%cachedblockers)) {
 8618:             if ($block =~ /^firstaccess____(.+)$/) {
 8619:                 my $item = $1;
 8620:                 if (($item eq $map) || ($item eq $symb)) {
 8621:                     $noblock = 1;
 8622:                     last;
 8623:                 }
 8624:             }
 8625:             if (ref($cachedblockers{$block}) eq 'HASH') {
 8626:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
 8627:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
 8628:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 8629:                             push(@blockers,$block);
 8630:                         }
 8631:                     }
 8632:                 }
 8633:             }
 8634:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
 8635:                 if ($cachedblockers{$block}{'maps'}{$map}) {
 8636:                     unless (grep(/^\Q$block\E$/,@blockers)) {
 8637:                         push(@blockers,$block);
 8638:                     }
 8639:                 }
 8640:             }
 8641:         }
 8642:     }
 8643:     return if ($noblock);
 8644:     return @blockers;
 8645: }
 8646: }
 8647: 
 8648: # -------------------------------- Deversion and split uri into path an filename
 8649: 
 8650: #
 8651: #   Removes the version from a URI and
 8652: #   splits it in to its filename and path to the filename.
 8653: #   Seems like File::Basename could have done this more clearly.
 8654: #   Parameters:
 8655: #      $uri   - input URI
 8656: #   Returns:
 8657: #     Two element list consisting of 
 8658: #     $pathname  - the URI up to and excluding the trailing /
 8659: #     $filename  - The part of the URI following the last /
 8660: #  NOTE:
 8661: #    Another realization of this is simply:
 8662: #    use File::Basename;
 8663: #    ...
 8664: #    $uri = shift;
 8665: #    $filename = basename($uri);
 8666: #    $path     = dirname($uri);
 8667: #    return ($filename, $path);
 8668: #
 8669: #     The implementation below is probably faster however.
 8670: #
 8671: sub split_uri_for_cond {
 8672:     my $uri=&deversion(&declutter(shift));
 8673:     my @uriparts=split(/\//,$uri);
 8674:     my $filename=pop(@uriparts);
 8675:     my $pathname=join('/',@uriparts);
 8676:     return ($pathname,$filename);
 8677: }
 8678: # --------------------------------------------------- Is a resource on the map?
 8679: 
 8680: sub is_on_map {
 8681:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 8682:     #Trying to find the conditional for the file
 8683:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 8684: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 8685:     if ($match) {
 8686: 	return (1,$1);
 8687:     } else {
 8688: 	return (0,0);
 8689:     }
 8690: }
 8691: 
 8692: # --------------------------------------------------------- Get symb from alias
 8693: 
 8694: sub get_symb_from_alias {
 8695:     my $symb=shift;
 8696:     my ($map,$resid,$url)=&decode_symb($symb);
 8697: # Already is a symb
 8698:     if ($url) { return $symb; }
 8699: # Must be an alias
 8700:     my $aliassymb='';
 8701:     my %bighash;
 8702:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8703:                             &GDBM_READER(),0640)) {
 8704:         my $rid=$bighash{'mapalias_'.$symb};
 8705: 	if ($rid) {
 8706: 	    my ($mapid,$resid)=split(/\./,$rid);
 8707: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 8708: 				    $resid,$bighash{'src_'.$rid});
 8709: 	}
 8710:         untie %bighash;
 8711:     }
 8712:     return $aliassymb;
 8713: }
 8714: 
 8715: # ----------------------------------------------------------------- Define Role
 8716: 
 8717: sub definerole {
 8718:   if (allowed('mcr','/')) {
 8719:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
 8720:     foreach my $role (split(':',$sysrole)) {
 8721: 	my ($crole,$cqual)=split(/\&/,$role);
 8722:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 8723:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 8724: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 8725:                return "refused:s:$crole&$cqual"; 
 8726:             }
 8727:         }
 8728:     }
 8729:     foreach my $role (split(':',$domrole)) {
 8730: 	my ($crole,$cqual)=split(/\&/,$role);
 8731:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 8732:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 8733: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 8734:                return "refused:d:$crole&$cqual"; 
 8735:             }
 8736:         }
 8737:     }
 8738:     foreach my $role (split(':',$courole)) {
 8739: 	my ($crole,$cqual)=split(/\&/,$role);
 8740:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 8741:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 8742: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 8743:                return "refused:c:$crole&$cqual"; 
 8744:             }
 8745:         }
 8746:     }
 8747:     my $uhome;
 8748:     if (($uname ne '') && ($udom ne '')) {
 8749:         $uhome = &homeserver($uname,$udom);
 8750:         return $uhome if ($uhome eq 'no_host');
 8751:     } else {
 8752:         $uname = $env{'user.name'};
 8753:         $udom = $env{'user.domain'};
 8754:         $uhome = $env{'user.home'};
 8755:     }
 8756:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 8757:                 "$udom:$uname:rolesdef_$rolename=".
 8758:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 8759:     return reply($command,$uhome);
 8760:   } else {
 8761:     return 'refused';
 8762:   }
 8763: }
 8764: 
 8765: # ---------------- Make a metadata query against the network of library servers
 8766: 
 8767: sub metadata_query {
 8768:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
 8769:     my %rhash;
 8770:     my %libserv = &all_library();
 8771:     my @server_list = (defined($server_array) ? @$server_array
 8772:                                               : keys(%libserv) );
 8773:     for my $server (@server_list) {
 8774:         my $domains = '';
 8775:         if (ref($domains_hash) eq 'HASH') {
 8776:             $domains = $domains_hash->{$server};    
 8777:         }
 8778: 	unless ($custom or $customshow) {
 8779: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
 8780: 	    $rhash{$server}=$reply;
 8781: 	}
 8782: 	else {
 8783: 	    my $reply=&reply("querysend:".&escape($query).':'.
 8784: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
 8785: 			     $server);
 8786: 	    $rhash{$server}=$reply;
 8787: 	}
 8788:     }
 8789:     return \%rhash;
 8790: }
 8791: 
 8792: # ----------------------------------------- Send log queries and wait for reply
 8793: 
 8794: sub log_query {
 8795:     my ($uname,$udom,$query,%filters)=@_;
 8796:     my $uhome=&homeserver($uname,$udom);
 8797:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 8798:     my $uhost=&hostname($uhome);
 8799:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 8800:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 8801:                        $uhome);
 8802:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 8803:     return get_query_reply($queryid);
 8804: }
 8805: 
 8806: # -------------------------- Update MySQL table for portfolio file
 8807: 
 8808: sub update_portfolio_table {
 8809:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 8810:     if ($group ne '') {
 8811:         $file_name =~s /^\Q$group\E//;
 8812:     }
 8813:     my $homeserver = &homeserver($uname,$udom);
 8814:     my $queryid=
 8815:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 8816:                ':'.&escape($file_name).':'.$action,$homeserver);
 8817:     my $reply = &get_query_reply($queryid);
 8818:     return $reply;
 8819: }
 8820: 
 8821: # -------------------------- Update MySQL allusers table
 8822: 
 8823: sub update_allusers_table {
 8824:     my ($uname,$udom,$names) = @_;
 8825:     my $homeserver = &homeserver($uname,$udom);
 8826:     my $queryid=
 8827:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 8828:                'lastname='.&escape($names->{'lastname'}).'%%'.
 8829:                'firstname='.&escape($names->{'firstname'}).'%%'.
 8830:                'middlename='.&escape($names->{'middlename'}).'%%'.
 8831:                'generation='.&escape($names->{'generation'}).'%%'.
 8832:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 8833:                'id='.&escape($names->{'id'}),$homeserver);
 8834:     return;
 8835: }
 8836: 
 8837: # ------- Request retrieval of institutional classlists for course(s)
 8838: 
 8839: sub fetch_enrollment_query {
 8840:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 8841:     my ($homeserver,$sleep,$loopmax);
 8842:     my $maxtries = 1;
 8843:     if ($context eq 'automated') {
 8844:         $homeserver = $perlvar{'lonHostID'};
 8845:         $sleep = 2;
 8846:         $loopmax = 100;
 8847:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 8848:     } else {
 8849:         $homeserver = &homeserver($cnum,$dom);
 8850:     }
 8851:     my $host=&hostname($homeserver);
 8852:     my $cmd = '';
 8853:     foreach my $affiliate (keys(%{$affiliatesref})) {
 8854:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 8855:     }
 8856:     $cmd =~ s/%%$//;
 8857:     $cmd = &escape($cmd);
 8858:     my $query = 'fetchenrollment';
 8859:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 8860:     unless ($queryid=~/^\Q$host\E\_/) { 
 8861:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 8862:         return 'error: '.$queryid;
 8863:     }
 8864:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
 8865:     my $tries = 1;
 8866:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 8867:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
 8868:         $tries ++;
 8869:     }
 8870:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 8871:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 8872:     } else {
 8873:         my @responses = split(/:/,$reply);
 8874:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
 8875:             foreach my $line (@responses) {
 8876:                 my ($key,$value) = split(/=/,$line,2);
 8877:                 $$replyref{$key} = $value;
 8878:             }
 8879:         } else {
 8880:             my $pathname = LONCAPA::tempdir();
 8881:             foreach my $line (@responses) {
 8882:                 my ($key,$value) = split(/=/,$line);
 8883:                 $$replyref{$key} = $value;
 8884:                 if ($value > 0) {
 8885:                     foreach my $item (@{$$affiliatesref{$key}}) {
 8886:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 8887:                         my $destname = $pathname.'/'.$filename;
 8888:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 8889:                         if ($xml_classlist =~ /^error/) {
 8890:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 8891:                         } else {
 8892:                             if ( open(FILE,">",$destname) ) {
 8893:                                 print FILE &unescape($xml_classlist);
 8894:                                 close(FILE);
 8895:                             } else {
 8896:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 8897:                             }
 8898:                         }
 8899:                     }
 8900:                 }
 8901:             }
 8902:         }
 8903:         return 'ok';
 8904:     }
 8905:     return 'error';
 8906: }
 8907: 
 8908: sub get_query_reply {
 8909:     my ($queryid,$sleep,$loopmax) = @_;
 8910:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
 8911:         $sleep = 0.2;
 8912:     }
 8913:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
 8914:         $loopmax = 100;
 8915:     }
 8916:     my $replyfile=LONCAPA::tempdir().$queryid;
 8917:     my $reply='';
 8918:     for (1..$loopmax) {
 8919: 	sleep($sleep);
 8920:         if (-e $replyfile.'.end') {
 8921: 	    if (open(my $fh,"<",$replyfile)) {
 8922: 		$reply = join('',<$fh>);
 8923: 		close($fh);
 8924: 	   } else { return 'error: reply_file_error'; }
 8925:            return &unescape($reply);
 8926: 	}
 8927:     }
 8928:     return 'timeout:'.$queryid;
 8929: }
 8930: 
 8931: sub courselog_query {
 8932: #
 8933: # possible filters:
 8934: # url: url or symb
 8935: # username
 8936: # domain
 8937: # action: view, submit, grade
 8938: # start: timestamp
 8939: # end: timestamp
 8940: #
 8941:     my (%filters)=@_;
 8942:     unless ($env{'request.course.id'}) { return 'no_course'; }
 8943:     if ($filters{'url'}) {
 8944: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 8945:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 8946:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 8947:     }
 8948:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 8949:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8950:     return &log_query($cname,$cdom,'courselog',%filters);
 8951: }
 8952: 
 8953: sub userlog_query {
 8954: #
 8955: # possible filters:
 8956: # action: log check role
 8957: # start: timestamp
 8958: # end: timestamp
 8959: #
 8960:     my ($uname,$udom,%filters)=@_;
 8961:     return &log_query($uname,$udom,'userlog',%filters);
 8962: }
 8963: 
 8964: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 8965: 
 8966: sub auto_run {
 8967:     my ($cnum,$cdom) = @_;
 8968:     my $response = 0;
 8969:     my $settings;
 8970:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 8971:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 8972:         $settings = $domconfig{'autoenroll'};
 8973:         if ($settings->{'run'} eq '1') {
 8974:             $response = 1;
 8975:         }
 8976:     } else {
 8977:         my $homeserver;
 8978:         if (&is_course($cdom,$cnum)) {
 8979:             $homeserver = &homeserver($cnum,$cdom);
 8980:         } else {
 8981:             $homeserver = &domain($cdom,'primary');
 8982:         }
 8983:         if ($homeserver ne 'no_host') {
 8984:             $response = &reply('autorun:'.$cdom,$homeserver);
 8985:         }
 8986:     }
 8987:     return $response;
 8988: }
 8989: 
 8990: sub auto_get_sections {
 8991:     my ($cnum,$cdom,$inst_coursecode) = @_;
 8992:     my $homeserver;
 8993:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 8994:         $homeserver = &homeserver($cnum,$cdom);
 8995:     }
 8996:     if (!defined($homeserver)) { 
 8997:         if ($cdom =~ /^$match_domain$/) {
 8998:             $homeserver = &domain($cdom,'primary');
 8999:         }
 9000:     }
 9001:     my @secs;
 9002:     if (defined($homeserver)) {
 9003:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 9004:         unless ($response eq 'refused') {
 9005:             @secs = split(/:/,$response);
 9006:         }
 9007:     }
 9008:     return @secs;
 9009: }
 9010: 
 9011: sub auto_new_course {
 9012:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 9013:     my $homeserver = &homeserver($cnum,$cdom);
 9014:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 9015:     return $response;
 9016: }
 9017: 
 9018: sub auto_validate_courseID {
 9019:     my ($cnum,$cdom,$inst_course_id) = @_;
 9020:     my $homeserver = &homeserver($cnum,$cdom);
 9021:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 9022:     return $response;
 9023: }
 9024: 
 9025: sub auto_validate_instcode {
 9026:     my ($cnum,$cdom,$instcode,$owner) = @_;
 9027:     my ($homeserver,$response);
 9028:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 9029:         $homeserver = &homeserver($cnum,$cdom);
 9030:     }
 9031:     if (!defined($homeserver)) {
 9032:         if ($cdom =~ /^$match_domain$/) {
 9033:             $homeserver = &domain($cdom,'primary');
 9034:         }
 9035:     }
 9036:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 9037:                         &escape($instcode).':'.&escape($owner),$homeserver));
 9038:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
 9039:     return ($outcome,$description,$defaultcredits);
 9040: }
 9041: 
 9042: sub auto_create_password {
 9043:     my ($cnum,$cdom,$authparam,$udom) = @_;
 9044:     my ($homeserver,$response);
 9045:     my $create_passwd = 0;
 9046:     my $authchk = '';
 9047:     if ($udom =~ /^$match_domain$/) {
 9048:         $homeserver = &domain($udom,'primary');
 9049:     }
 9050:     if ($homeserver eq '') {
 9051:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 9052:             $homeserver = &homeserver($cnum,$cdom);
 9053:         }
 9054:     }
 9055:     if ($homeserver eq '') {
 9056:         $authchk = 'nodomain';
 9057:     } else {
 9058:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 9059:         if ($response eq 'refused') {
 9060:             $authchk = 'refused';
 9061:         } else {
 9062:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 9063:         }
 9064:     }
 9065:     return ($authparam,$create_passwd,$authchk);
 9066: }
 9067: 
 9068: sub auto_photo_permission {
 9069:     my ($cnum,$cdom,$students) = @_;
 9070:     my $homeserver = &homeserver($cnum,$cdom);
 9071:     my ($outcome,$perm_reqd,$conditions) = 
 9072: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 9073:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9074: 	return (undef,undef);
 9075:     }
 9076:     return ($outcome,$perm_reqd,$conditions);
 9077: }
 9078: 
 9079: sub auto_checkphotos {
 9080:     my ($uname,$udom,$pid) = @_;
 9081:     my $homeserver = &homeserver($uname,$udom);
 9082:     my ($result,$resulttype);
 9083:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 9084: 				   &escape($uname).':'.&escape($pid),
 9085: 				   $homeserver));
 9086:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9087: 	return (undef,undef);
 9088:     }
 9089:     if ($outcome) {
 9090:         ($result,$resulttype) = split(/:/,$outcome);
 9091:     } 
 9092:     return ($result,$resulttype);
 9093: }
 9094: 
 9095: sub auto_photochoice {
 9096:     my ($cnum,$cdom) = @_;
 9097:     my $homeserver = &homeserver($cnum,$cdom);
 9098:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 9099: 						       &escape($cdom),
 9100: 						       $homeserver)));
 9101:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 9102: 	return (undef,undef);
 9103:     }
 9104:     return ($update,$comment);
 9105: }
 9106: 
 9107: sub auto_photoupdate {
 9108:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 9109:     my $homeserver = &homeserver($cnum,$dom);
 9110:     my $host=&hostname($homeserver);
 9111:     my $cmd = '';
 9112:     my $maxtries = 1;
 9113:     foreach my $affiliate (keys(%{$affiliatesref})) {
 9114:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 9115:     }
 9116:     $cmd =~ s/%%$//;
 9117:     $cmd = &escape($cmd);
 9118:     my $query = 'institutionalphotos';
 9119:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 9120:     unless ($queryid=~/^\Q$host\E\_/) {
 9121:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 9122:         return 'error: '.$queryid;
 9123:     }
 9124:     my $reply = &get_query_reply($queryid);
 9125:     my $tries = 1;
 9126:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 9127:         $reply = &get_query_reply($queryid);
 9128:         $tries ++;
 9129:     }
 9130:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 9131:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 9132:     } else {
 9133:         my @responses = split(/:/,$reply);
 9134:         my $outcome = shift(@responses); 
 9135:         foreach my $item (@responses) {
 9136:             my ($key,$value) = split(/=/,$item);
 9137:             $$photo{$key} = $value;
 9138:         }
 9139:         return $outcome;
 9140:     }
 9141:     return 'error';
 9142: }
 9143: 
 9144: sub auto_instcode_format {
 9145:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 9146: 	$cat_order) = @_;
 9147:     my $courses = '';
 9148:     my @homeservers;
 9149:     if ($caller eq 'global') {
 9150: 	my %servers = &get_servers($codedom,'library');
 9151: 	foreach my $tryserver (keys(%servers)) {
 9152: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9153: 		push(@homeservers,$tryserver);
 9154: 	    }
 9155:         }
 9156:     } elsif ($caller eq 'requests') {
 9157:         if ($codedom =~ /^$match_domain$/) {
 9158:             my $chome = &domain($codedom,'primary');
 9159:             unless ($chome eq 'no_host') {
 9160:                 push(@homeservers,$chome);
 9161:             }
 9162:         }
 9163:     } else {
 9164:         push(@homeservers,&homeserver($caller,$codedom));
 9165:     }
 9166:     foreach my $code (keys(%{$instcodes})) {
 9167:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 9168:     }
 9169:     chop($courses);
 9170:     my $ok_response = 0;
 9171:     my $response;
 9172:     while (@homeservers > 0 && $ok_response == 0) {
 9173:         my $server = shift(@homeservers); 
 9174:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 9175:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 9176:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 9177: 		split(/:/,$response);
 9178:             %{$codes} = (%{$codes},&str2hash($codes_str));
 9179:             push(@{$codetitles},&str2array($codetitles_str));
 9180:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 9181:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 9182:             $ok_response = 1;
 9183:         }
 9184:     }
 9185:     if ($ok_response) {
 9186:         return 'ok';
 9187:     } else {
 9188:         return $response;
 9189:     }
 9190: }
 9191: 
 9192: sub auto_instcode_defaults {
 9193:     my ($domain,$returnhash,$code_order) = @_;
 9194:     my @homeservers;
 9195: 
 9196:     my %servers = &get_servers($domain,'library');
 9197:     foreach my $tryserver (keys(%servers)) {
 9198: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9199: 	    push(@homeservers,$tryserver);
 9200: 	}
 9201:     }
 9202: 
 9203:     my $response;
 9204:     foreach my $server (@homeservers) {
 9205:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 9206:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 9207: 	
 9208: 	foreach my $pair (split(/\&/,$response)) {
 9209: 	    my ($name,$value)=split(/\=/,$pair);
 9210: 	    if ($name eq 'code_order') {
 9211: 		@{$code_order} = split(/\&/,&unescape($value));
 9212: 	    } else {
 9213: 		$returnhash->{&unescape($name)}=&unescape($value);
 9214: 	    }
 9215: 	}
 9216: 	return 'ok';
 9217:     }
 9218: 
 9219:     return $response;
 9220: }
 9221: 
 9222: sub auto_possible_instcodes {
 9223:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 9224:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 9225:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 9226:         return;
 9227:     }
 9228:     my (@homeservers,$uhome);
 9229:     if (defined(&domain($domain,'primary'))) {
 9230:         $uhome=&domain($domain,'primary');
 9231:         push(@homeservers,&domain($domain,'primary'));
 9232:     } else {
 9233:         my %servers = &get_servers($domain,'library');
 9234:         foreach my $tryserver (keys(%servers)) {
 9235:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 9236:                 push(@homeservers,$tryserver);
 9237:             }
 9238:         }
 9239:     }
 9240:     my $response;
 9241:     foreach my $server (@homeservers) {
 9242:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 9243:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 9244:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 9245:             split(':',$response);
 9246:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 9247:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 9248:         foreach my $item (split('&',$cat_title)) {   
 9249:             my ($name,$value)=split('=',$item);
 9250:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 9251:         }
 9252:         foreach my $item (split('&',$cat_order)) {
 9253:             my ($name,$value)=split('=',$item);
 9254:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 9255:         }
 9256:         return 'ok';
 9257:     }
 9258:     return $response;
 9259: }
 9260: 
 9261: sub auto_courserequest_checks {
 9262:     my ($dom) = @_;
 9263:     my ($homeserver,%validations);
 9264:     if ($dom =~ /^$match_domain$/) {
 9265:         $homeserver = &domain($dom,'primary');
 9266:     }
 9267:     unless ($homeserver eq 'no_host') {
 9268:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 9269:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9270:             my @items = split(/&/,$response);
 9271:             foreach my $item (@items) {
 9272:                 my ($key,$value) = split('=',$item);
 9273:                 $validations{&unescape($key)} = &thaw_unescape($value);
 9274:             }
 9275:         }
 9276:     }
 9277:     return %validations; 
 9278: }
 9279: 
 9280: sub auto_courserequest_validation {
 9281:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
 9282:     my ($homeserver,$response);
 9283:     if ($dom =~ /^$match_domain$/) {
 9284:         $homeserver = &domain($dom,'primary');
 9285:     }
 9286:     unless ($homeserver eq 'no_host') {
 9287:         my $customdata;
 9288:         if (ref($custominfo) eq 'HASH') {
 9289:             $customdata = &freeze_escape($custominfo);
 9290:         }
 9291:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 9292:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 9293:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
 9294:                                     $customdata,$homeserver));
 9295:     }
 9296:     return $response;
 9297: }
 9298: 
 9299: sub auto_validate_class_sec {
 9300:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 9301:     my $homeserver = &homeserver($cnum,$cdom);
 9302:     my $ownerlist;
 9303:     if (ref($owners) eq 'ARRAY') {
 9304:         $ownerlist = join(',',@{$owners});
 9305:     } else {
 9306:         $ownerlist = $owners;
 9307:     }
 9308:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 9309:                         &escape($ownerlist).':'.$cdom,$homeserver);
 9310:     return $response;
 9311: }
 9312: 
 9313: sub auto_validate_instclasses {
 9314:     my ($cdom,$cnum,$owners,$classesref) = @_;
 9315:     my ($homeserver,%validations);
 9316:     $homeserver = &homeserver($cnum,$cdom);
 9317:     unless ($homeserver eq 'no_host') {
 9318:         my $ownerlist;
 9319:         if (ref($owners) eq 'ARRAY') {
 9320:             $ownerlist = join(',',@{$owners});
 9321:         } else {
 9322:             $ownerlist = $owners;
 9323:         }
 9324:         if (ref($classesref) eq 'HASH') {
 9325:             my $classes = &freeze_escape($classesref);
 9326:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
 9327:                                 ':'.$cdom.':'.$classes,$homeserver);
 9328:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9329:                 my @items = split(/&/,$response);
 9330:                 foreach my $item (@items) {
 9331:                     my ($key,$value) = split('=',$item);
 9332:                     $validations{&unescape($key)} = &thaw_unescape($value);
 9333:                 }
 9334:             }
 9335:         }
 9336:     }
 9337:     return %validations;
 9338: }
 9339: 
 9340: sub auto_crsreq_update {
 9341:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
 9342:         $code,$accessstart,$accessend,$inbound) = @_;
 9343:     my ($homeserver,%crsreqresponse);
 9344:     if ($cdom =~ /^$match_domain$/) {
 9345:         $homeserver = &domain($cdom,'primary');
 9346:     }
 9347:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 9348:         my $info;
 9349:         if (ref($inbound) eq 'HASH') {
 9350:             $info = &freeze_escape($inbound);
 9351:         }
 9352:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
 9353:                             ':'.&escape($action).':'.&escape($ownername).':'.
 9354:                             &escape($ownerdomain).':'.&escape($fullname).':'.
 9355:                             &escape($title).':'.&escape($code).':'.
 9356:                             &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
 9357:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 9358:             my @items = split(/&/,$response);
 9359:             foreach my $item (@items) {
 9360:                 my ($key,$value) = split('=',$item);
 9361:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
 9362:             }
 9363:         }
 9364:     }
 9365:     return \%crsreqresponse;
 9366: }
 9367: 
 9368: sub auto_export_grades {
 9369:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
 9370:     my ($homeserver,%exportresponse);
 9371:     if ($cdom =~ /^$match_domain$/) {
 9372:         $homeserver = &domain($cdom,'primary');
 9373:     }
 9374:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 9375:         my $info;
 9376:         if (ref($inforef) eq 'HASH') {
 9377:             $info = &freeze_escape($inforef);
 9378:         }
 9379:         if (ref($gradesref) eq 'HASH') {
 9380:             my $grades = &freeze_escape($gradesref);
 9381:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
 9382:                                 $info.':'.$grades,$homeserver);
 9383:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
 9384:                 my @items = split(/&/,$response);
 9385:                 foreach my $item (@items) {
 9386:                     my ($key,$value) = split('=',$item);
 9387:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
 9388:                 }
 9389:             }
 9390:         }
 9391:     }
 9392:     return \%exportresponse;
 9393: }
 9394: 
 9395: sub check_instcode_cloning {
 9396:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
 9397:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 9398:         return;
 9399:     }
 9400:     my $canclone;
 9401:     if (@{$code_order} > 0) {
 9402:         my $instcoderegexp ='^';
 9403:         my @clonecodes = split(/\&/,$cloner);
 9404:         foreach my $item (@{$code_order}) {
 9405:             if (grep(/^\Q$item\E=/,@clonecodes)) {
 9406:                 foreach my $pair (@clonecodes) {
 9407:                     my ($key,$val) = split(/\=/,$pair,2);
 9408:                     $val = &unescape($val);
 9409:                     if ($key eq $item) {
 9410:                         $instcoderegexp .= '('.$val.')';
 9411:                         last;
 9412:                     }
 9413:                 }
 9414:             } else {
 9415:                 $instcoderegexp .= $codedefaults->{$item};
 9416:             }
 9417:         }
 9418:         $instcoderegexp .= '$';
 9419:         my (@from,@to);
 9420:         eval {
 9421:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
 9422:                (@to) = ($clonetocode =~ /$instcoderegexp/);
 9423:         };
 9424:         if ((@from > 0) && (@to > 0)) {
 9425:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
 9426:             if (!@diffs) {
 9427:                 $canclone = 1;
 9428:             }
 9429:         }
 9430:     }
 9431:     return $canclone;
 9432: }
 9433: 
 9434: sub default_instcode_cloning {
 9435:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
 9436:     my (%codedefaults,@code_order,$canclone);
 9437:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
 9438:         %codedefaults = %{$codedefaultsref};
 9439:         @code_order = @{$codeorderref};
 9440:     } elsif ($clonedom) {
 9441:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
 9442:     }
 9443:     if (($domdefclone) && (@code_order)) {
 9444:         my @clonecodes = split(/\+/,$domdefclone);
 9445:         my $instcoderegexp ='^';
 9446:         foreach my $item (@code_order) {
 9447:             if (grep(/^\Q$item\E$/,@clonecodes)) {
 9448:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
 9449:             } else {
 9450:                 $instcoderegexp .= $codedefaults{$item};
 9451:             }
 9452:         }
 9453:         $instcoderegexp .= '$';
 9454:         my (@from,@to);
 9455:         eval {
 9456:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
 9457:             (@to) = ($clonetocode =~ /$instcoderegexp/);
 9458:         };
 9459:         if ((@from > 0) && (@to > 0)) {
 9460:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
 9461:             if (!@diffs) {
 9462:                 $canclone = 1;
 9463:             }
 9464:         }
 9465:     }
 9466:     return $canclone;
 9467: }
 9468: 
 9469: # ------------------------------------------------------- Course Group routines
 9470: 
 9471: sub get_coursegroups {
 9472:     my ($cdom,$cnum,$group,$namespace) = @_;
 9473:     return(&dump($namespace,$cdom,$cnum,$group));
 9474: }
 9475: 
 9476: sub modify_coursegroup {
 9477:     my ($cdom,$cnum,$groupsettings) = @_;
 9478:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 9479: }
 9480: 
 9481: sub toggle_coursegroup_status {
 9482:     my ($cdom,$cnum,$group,$action) = @_;
 9483:     my ($from_namespace,$to_namespace);
 9484:     if ($action eq 'delete') {
 9485:         $from_namespace = 'coursegroups';
 9486:         $to_namespace = 'deleted_groups';
 9487:     } else {
 9488:         $from_namespace = 'deleted_groups';
 9489:         $to_namespace = 'coursegroups';
 9490:     }
 9491:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 9492:     if (my $tmp = &error(%curr_group)) {
 9493:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 9494:         return ('read error',$tmp);
 9495:     } else {
 9496:         my %savedsettings = %curr_group; 
 9497:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 9498:         my $deloutcome;
 9499:         if ($result eq 'ok') {
 9500:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 9501:         } else {
 9502:             return ('write error',$result);
 9503:         }
 9504:         if ($deloutcome eq 'ok') {
 9505:             return 'ok';
 9506:         } else {
 9507:             return ('delete error',$deloutcome);
 9508:         }
 9509:     }
 9510: }
 9511: 
 9512: sub modify_group_roles {
 9513:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 9514:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 9515:     my $role = 'gr/'.&escape($userprivs);
 9516:     my ($uname,$udom) = split(/:/,$user);
 9517:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 9518:     if ($result eq 'ok') {
 9519:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 9520:     }
 9521:     return $result;
 9522: }
 9523: 
 9524: sub modify_coursegroup_membership {
 9525:     my ($cdom,$cnum,$membership) = @_;
 9526:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 9527:     return $result;
 9528: }
 9529: 
 9530: sub get_active_groups {
 9531:     my ($udom,$uname,$cdom,$cnum) = @_;
 9532:     my $now = time;
 9533:     my %groups = ();
 9534:     foreach my $key (keys(%env)) {
 9535:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 9536:             my ($start,$end) = split(/\./,$env{$key});
 9537:             if (($end!=0) && ($end<$now)) { next; }
 9538:             if (($start!=0) && ($start>$now)) { next; }
 9539:             if ($1 eq $cdom && $2 eq $cnum) {
 9540:                 $groups{$3} = $env{$key} ;
 9541:             }
 9542:         }
 9543:     }
 9544:     return %groups;
 9545: }
 9546: 
 9547: sub get_group_membership {
 9548:     my ($cdom,$cnum,$group) = @_;
 9549:     return(&dump('groupmembership',$cdom,$cnum,$group));
 9550: }
 9551: 
 9552: sub get_users_groups {
 9553:     my ($udom,$uname,$courseid) = @_;
 9554:     my @usersgroups;
 9555:     my $cachetime=1800;
 9556: 
 9557:     my $hashid="$udom:$uname:$courseid";
 9558:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 9559:     if (defined($cached)) {
 9560:         @usersgroups = split(/:/,$grouplist);
 9561:     } else {  
 9562:         $grouplist = '';
 9563:         my $courseurl = &courseid_to_courseurl($courseid);
 9564:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 9565:         my $access_end = $env{'course.'.$courseid.
 9566:                               '.default_enrollment_end_date'};
 9567:         my $now = time;
 9568:         foreach my $key (keys(%roleshash)) {
 9569:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 9570:                 my $group = $1;
 9571:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 9572:                     my $start = $2;
 9573:                     my $end = $1;
 9574:                     if ($start == -1) { next; } # deleted from group
 9575:                     if (($start!=0) && ($start>$now)) { next; }
 9576:                     if (($end!=0) && ($end<$now)) {
 9577:                         if ($access_end && $access_end < $now) {
 9578:                             if ($access_end - $end < 86400) {
 9579:                                 push(@usersgroups,$group);
 9580:                             }
 9581:                         }
 9582:                         next;
 9583:                     }
 9584:                     push(@usersgroups,$group);
 9585:                 }
 9586:             }
 9587:         }
 9588:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 9589:         $grouplist = join(':',@usersgroups);
 9590:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 9591:     }
 9592:     return @usersgroups;
 9593: }
 9594: 
 9595: sub devalidate_getgroups_cache {
 9596:     my ($udom,$uname,$cdom,$cnum)=@_;
 9597:     my $courseid = $cdom.'_'.$cnum;
 9598: 
 9599:     my $hashid="$udom:$uname:$courseid";
 9600:     &devalidate_cache_new('getgroups',$hashid);
 9601: }
 9602: 
 9603: # ------------------------------------------------------------------ Plain Text
 9604: 
 9605: sub plaintext {
 9606:     my ($short,$type,$cid,$forcedefault) = @_;
 9607:     if ($short =~ m{^cr/}) {
 9608: 	return (split('/',$short))[-1];
 9609:     }
 9610:     if (!defined($cid)) {
 9611:         $cid = $env{'request.course.id'};
 9612:     }
 9613:     my %rolenames = (
 9614:                       Course    => 'std',
 9615:                       Community => 'alt1',
 9616:                     );
 9617:     if ($cid ne '') {
 9618:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 9619:             unless ($forcedefault) {
 9620:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 9621:                 &Apache::lonlocal::mt_escape(\$roletext);
 9622:                 return &Apache::lonlocal::mt($roletext);
 9623:             }
 9624:         }
 9625:     }
 9626:     if ((defined($type)) && (defined($rolenames{$type})) &&
 9627:         (defined($rolenames{$type})) && 
 9628:         (defined($prp{$short}{$rolenames{$type}}))) {
 9629:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 9630:     } elsif ($cid ne '') {
 9631:         my $crstype = $env{'course.'.$cid.'.type'};
 9632:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
 9633:             (defined($prp{$short}{$rolenames{$crstype}}))) {
 9634:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
 9635:         }
 9636:     }
 9637:     return &Apache::lonlocal::mt($prp{$short}{'std'});
 9638: }
 9639: 
 9640: # ----------------------------------------------------------------- Assign Role
 9641: 
 9642: sub assignrole {
 9643:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 9644:         $context)=@_;
 9645:     my $mrole;
 9646:     if ($role =~ /^cr\//) {
 9647:         my $cwosec=$url;
 9648:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 9649: 	unless (&allowed('ccr',$cwosec)) {
 9650:            my $refused = 1;
 9651:            if ($context eq 'requestcourses') {
 9652:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 9653:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
 9654:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
 9655:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 9656:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9657:                            if ($crsenv{'internal.courseowner'} eq
 9658:                                $env{'user.name'}.':'.$env{'user.domain'}) {
 9659:                                $refused = '';
 9660:                            }
 9661:                        }
 9662:                    }
 9663:                }
 9664:            }
 9665:            if ($refused) {
 9666:                &logthis('Refused custom assignrole: '.
 9667:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
 9668:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
 9669:                return 'refused';
 9670:            }
 9671:         }
 9672:         $mrole='cr';
 9673:     } elsif ($role =~ /^gr\//) {
 9674:         my $cwogrp=$url;
 9675:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 9676:         unless (&allowed('mdg',$cwogrp)) {
 9677:             &logthis('Refused group assignrole: '.
 9678:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 9679:                     $env{'user.name'}.' at '.$env{'user.domain'});
 9680:             return 'refused';
 9681:         }
 9682:         $mrole='gr';
 9683:     } else {
 9684:         my $cwosec=$url;
 9685:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 9686:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 9687:             my $refused;
 9688:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 9689:                 if (!(&allowed('c'.$role,$url))) {
 9690:                     $refused = 1;
 9691:                 }
 9692:             } else {
 9693:                 $refused = 1;
 9694:             }
 9695:             if ($refused) {
 9696:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 9697:                 if (!$selfenroll && $context eq 'course') {
 9698:                     my %crsenv;
 9699:                     if ($role eq 'cc' || $role eq 'co') {
 9700:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9701:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
 9702:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
 9703:                                 if ($crsenv{'internal.courseowner'} eq 
 9704:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 9705:                                     $refused = '';
 9706:                                 }
 9707:                             }
 9708:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
 9709:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
 9710:                                 if ($crsenv{'internal.courseowner'} eq 
 9711:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 9712:                                     $refused = '';
 9713:                                 }
 9714:                             }
 9715:                         }
 9716:                     }
 9717:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 9718:                     $refused = '';
 9719:                 } elsif ($context eq 'requestcourses') {
 9720:                     my @possroles = ('st','ta','ep','in','cc','co');
 9721:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
 9722:                         my $wrongcc;
 9723:                         if ($cnum =~ /^$match_community$/) {
 9724:                             $wrongcc = 1 if ($role eq 'cc');
 9725:                         } else {
 9726:                             $wrongcc = 1 if ($role eq 'co');
 9727:                         }
 9728:                         unless ($wrongcc) {
 9729:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9730:                             if ($crsenv{'internal.courseowner'} eq 
 9731:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
 9732:                                 $refused = '';
 9733:                             }
 9734:                         }
 9735:                     }
 9736:                 } elsif ($context eq 'requestauthor') {
 9737:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 9738:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
 9739:                         if ($env{'environment.requestauthor'} eq 'automatic') {
 9740:                             $refused = '';
 9741:                         } else {
 9742:                             my %domdefaults = &get_domain_defaults($udom);
 9743:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
 9744:                                 my $checkbystatus;
 9745:                                 if ($env{'user.adv'}) {
 9746:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
 9747:                                     if ($disposition eq 'automatic') {
 9748:                                         $refused = '';
 9749:                                     } elsif ($disposition eq '') {
 9750:                                         $checkbystatus = 1;
 9751:                                     }
 9752:                                 } else {
 9753:                                     $checkbystatus = 1;
 9754:                                 }
 9755:                                 if ($checkbystatus) {
 9756:                                     if ($env{'environment.inststatus'}) {
 9757:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
 9758:                                         foreach my $type (@inststatuses) {
 9759:                                             if (($type ne '') &&
 9760:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
 9761:                                                 $refused = '';
 9762:                                             }
 9763:                                         }
 9764:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
 9765:                                         $refused = '';
 9766:                                     }
 9767:                                 }
 9768:                             }
 9769:                         }
 9770:                     }
 9771:                 }
 9772:                 if ($refused) {
 9773:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 9774:                              ' '.$role.' '.$end.' '.$start.' by '.
 9775: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 9776:                     return 'refused';
 9777:                 }
 9778:             }
 9779:         } elsif ($role eq 'au') {
 9780:             if ($url ne '/'.$udom.'/') {
 9781:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
 9782:                          ' to assign author role for '.$uname.':'.$udom.
 9783:                          ' in domain: '.$url.' refused (wrong domain).');
 9784:                 return 'refused';
 9785:             }
 9786:         }
 9787:         $mrole=$role;
 9788:     }
 9789:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 9790:                 "$udom:$uname:$url".'_'."$mrole=$role";
 9791:     if ($end) { $command.='_'.$end; }
 9792:     if ($start) {
 9793: 	if ($end) { 
 9794:            $command.='_'.$start; 
 9795:         } else {
 9796:            $command.='_0_'.$start;
 9797:         }
 9798:     }
 9799:     my $origstart = $start;
 9800:     my $origend = $end;
 9801:     my $delflag;
 9802: # actually delete
 9803:     if ($deleteflag) {
 9804: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 9805: # modify command to delete the role
 9806:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 9807:                 "$udom:$uname:$url".'_'."$mrole";
 9808: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 9809: # set start and finish to negative values for userrolelog
 9810:            $start=-1;
 9811:            $end=-1;
 9812:            $delflag = 1;
 9813:         }
 9814:     }
 9815: # send command
 9816:     my $answer=&reply($command,&homeserver($uname,$udom));
 9817: # log new user role if status is ok
 9818:     if ($answer eq 'ok') {
 9819: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 9820:         if (($role eq 'cc') || ($role eq 'in') ||
 9821:             ($role eq 'ep') || ($role eq 'ad') ||
 9822:             ($role eq 'ta') || ($role eq 'st') ||
 9823:             ($role=~/^cr/) || ($role eq 'gr') ||
 9824:             ($role eq 'co')) {
 9825: # for course roles, perform group memberships changes triggered by role change.
 9826:             unless ($role =~ /^gr/) {
 9827:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 9828:                                                  $origstart,$selfenroll,$context);
 9829:             }
 9830:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 9831:                            $selfenroll,$context);
 9832:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
 9833:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
 9834:                  ($role eq 'da')) {
 9835:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 9836:                            $context);
 9837:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
 9838:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 9839:                              $context);
 9840:         }
 9841:         if ($role eq 'cc') {
 9842:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
 9843:         }
 9844:     }
 9845:     return $answer;
 9846: }
 9847: 
 9848: sub autoupdate_coowners {
 9849:     my ($url,$end,$start,$uname,$udom) = @_;
 9850:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
 9851:     if (($cdom ne '') && ($cnum ne '')) {
 9852:         my $now = time;
 9853:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
 9854:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
 9855:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
 9856:             my $instcode = $coursehash{'internal.coursecode'};
 9857:             if ($instcode ne '') {
 9858:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
 9859:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
 9860:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
 9861:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
 9862:                         if ($result eq 'valid') {
 9863:                             if ($coursehash{'internal.co-owners'}) {
 9864:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 9865:                                     push(@newcoowners,$coowner);
 9866:                                 }
 9867:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
 9868:                                     push(@newcoowners,$uname.':'.$udom);
 9869:                                 }
 9870:                                 @newcoowners = sort(@newcoowners);
 9871:                             } else {
 9872:                                 push(@newcoowners,$uname.':'.$udom);
 9873:                             }
 9874:                         } else {
 9875:                             if ($coursehash{'internal.co-owners'}) {
 9876:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 9877:                                     unless ($coowner eq $uname.':'.$udom) {
 9878:                                         push(@newcoowners,$coowner);
 9879:                                     }
 9880:                                 }
 9881:                                 unless (@newcoowners > 0) {
 9882:                                     $delcoowners = 1;
 9883:                                     $coowners = '';
 9884:                                 }
 9885:                             }
 9886:                         }
 9887:                         if (@newcoowners || $delcoowners) {
 9888:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
 9889:                                             $delcoowners,@newcoowners);
 9890:                         }
 9891:                     }
 9892:                 }
 9893:             }
 9894:         }
 9895:     }
 9896: }
 9897: 
 9898: sub store_coowners {
 9899:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
 9900:     my $cid = $cdom.'_'.$cnum;
 9901:     my ($coowners,$delresult,$putresult);
 9902:     if (@newcoowners) {
 9903:         $coowners = join(',',@newcoowners);
 9904:         my %coownershash = (
 9905:                             'internal.co-owners' => $coowners,
 9906:                            );
 9907:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
 9908:         if ($putresult eq 'ok') {
 9909:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
 9910:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
 9911:             }
 9912:         }
 9913:     }
 9914:     if ($delcoowners) {
 9915:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
 9916:         if ($delresult eq 'ok') {
 9917:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
 9918:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
 9919:             }
 9920:         }
 9921:     }
 9922:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
 9923:         my %crsinfo =
 9924:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 9925:         if (ref($crsinfo{$cid}) eq 'HASH') {
 9926:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
 9927:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
 9928:         }
 9929:     }
 9930: }
 9931: 
 9932: # -------------------------------------------------- Modify user authentication
 9933: # Overrides without validation
 9934: 
 9935: sub modifyuserauth {
 9936:     my ($udom,$uname,$umode,$upass)=@_;
 9937:     my $uhome=&homeserver($uname,$udom);
 9938:     my $allowed;
 9939:     if (&allowed('mau',$udom)) {
 9940:         $allowed = 1;
 9941:     } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
 9942:              ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
 9943:              (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
 9944:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9945:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9946:         if (($cdom ne '') && ($cnum ne '')) {
 9947:             my $is_owner = &is_course_owner($cdom,$cnum);
 9948:             if ($is_owner) {
 9949:                 $allowed = 1;
 9950:             }
 9951:         }
 9952:     }
 9953:     unless ($allowed) { return 'refused'; }
 9954:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 9955:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 9956:              ' in domain '.$env{'request.role.domain'});  
 9957:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 9958: 		     &escape($upass),$uhome);
 9959:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 9960:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 9961:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 9962:     &log($udom,,$uname,$uhome,
 9963:         'Authentication changed by '.$env{'user.domain'}.', '.
 9964:                                      $env{'user.name'}.', '.$umode.
 9965:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 9966:     unless ($reply eq 'ok') {
 9967:         &logthis('Authentication mode error: '.$reply);
 9968: 	return 'error: '.$reply;
 9969:     }   
 9970:     return 'ok';
 9971: }
 9972: 
 9973: # --------------------------------------------------------------- Modify a user
 9974: 
 9975: sub modifyuser {
 9976:     my ($udom,    $uname, $uid,
 9977:         $umode,   $upass, $first,
 9978:         $middle,  $last,  $gene,
 9979:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
 9980:     $udom= &LONCAPA::clean_domain($udom);
 9981:     $uname=&LONCAPA::clean_username($uname);
 9982:     my $showcandelete = 'none';
 9983:     if (ref($candelete) eq 'ARRAY') {
 9984:         if (@{$candelete} > 0) {
 9985:             $showcandelete = join(', ',@{$candelete});
 9986:         }
 9987:     }
 9988:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 9989:              $umode.', '.$first.', '.$middle.', '.
 9990: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
 9991:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 9992:                                      ' desiredhome not specified'). 
 9993:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 9994:              ' in domain '.$env{'request.role.domain'});
 9995:     my $uhome=&homeserver($uname,$udom,'true');
 9996:     my $newuser;
 9997:     if ($uhome eq 'no_host') {
 9998:         $newuser = 1;
 9999:     }
10000: # ----------------------------------------------------------------- Create User
10001:     if (($uhome eq 'no_host') && 
10002: 	(($umode && $upass) || ($umode eq 'localauth'))) {
10003:         my $unhome='';
10004:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
10005:             $unhome = $desiredhome;
10006: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
10007: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
10008:         } else { # load balancing routine for determining $unhome
10009:             my $loadm=10000000;
10010: 	    my %servers = &get_servers($udom,'library');
10011: 	    foreach my $tryserver (keys(%servers)) {
10012: 		my $answer=reply('load',$tryserver);
10013: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
10014: 		    $loadm=$answer;
10015: 		    $unhome=$tryserver;
10016: 		}
10017: 	    }
10018:         }
10019:         if (($unhome eq '') || ($unhome eq 'no_host')) {
10020: 	    return 'error: unable to find a home server for '.$uname.
10021:                    ' in domain '.$udom;
10022:         }
10023:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
10024:                          &escape($upass),$unhome);
10025: 	unless ($reply eq 'ok') {
10026:             return 'error: '.$reply;
10027:         }   
10028:         $uhome=&homeserver($uname,$udom,'true');
10029:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
10030: 	    return 'error: unable verify users home machine.';
10031:         }
10032:     }   # End of creation of new user
10033: # ---------------------------------------------------------------------- Add ID
10034:     if ($uid) {
10035:        $uid=~tr/A-Z/a-z/;
10036:        my %uidhash=&idrget($udom,$uname);
10037:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
10038:          && (!$forceid)) {
10039: 	  unless ($uid eq $uidhash{$uname}) {
10040: 	      return 'error: user id "'.$uid.'" does not match '.
10041:                   'current user id "'.$uidhash{$uname}.'".';
10042:           }
10043:        } else {
10044: 	  &idput($udom,($uname => $uid));
10045:        }
10046:     }
10047: # -------------------------------------------------------------- Add names, etc
10048:     my @tmp=&get('environment',
10049: 		   ['firstname','middlename','lastname','generation','id',
10050:                     'permanentemail','inststatus'],
10051: 		   $udom,$uname);
10052:     my (%names,%oldnames);
10053:     if ($tmp[0] =~ m/^error:.*/) { 
10054:         %names=(); 
10055:     } else {
10056:         %names = @tmp;
10057:         %oldnames = %names;
10058:     }
10059: #
10060: # If name, email and/or uid are blank (e.g., because an uploaded file
10061: # of users did not contain them), do not overwrite existing values
10062: # unless field is in $candelete array ref.  
10063: #
10064: 
10065:     my @fields = ('firstname','middlename','lastname','generation',
10066:                   'permanentemail','id');
10067:     my %newvalues;
10068:     if (ref($candelete) eq 'ARRAY') {
10069:         foreach my $field (@fields) {
10070:             if (grep(/^\Q$field\E$/,@{$candelete})) {
10071:                 if ($field eq 'firstname') {
10072:                     $names{$field} = $first;
10073:                 } elsif ($field eq 'middlename') {
10074:                     $names{$field} = $middle;
10075:                 } elsif ($field eq 'lastname') {
10076:                     $names{$field} = $last;
10077:                 } elsif ($field eq 'generation') { 
10078:                     $names{$field} = $gene;
10079:                 } elsif ($field eq 'permanentemail') {
10080:                     $names{$field} = $email;
10081:                 } elsif ($field eq 'id') {
10082:                     $names{$field}  = $uid;
10083:                 }
10084:             }
10085:         }
10086:     }
10087:     if ($first)  { $names{'firstname'}  = $first; }
10088:     if (defined($middle)) { $names{'middlename'} = $middle; }
10089:     if ($last)   { $names{'lastname'}   = $last; }
10090:     if (defined($gene))   { $names{'generation'} = $gene; }
10091:     if ($email) {
10092:        $email=~s/[^\w\@\.\-\,]//gs;
10093:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
10094:     }
10095:     if ($uid) { $names{'id'}  = $uid; }
10096:     if (defined($inststatus)) {
10097:         $names{'inststatus'} = '';
10098:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
10099:         if (ref($usertypes) eq 'HASH') {
10100:             my @okstatuses; 
10101:             foreach my $item (split(/:/,$inststatus)) {
10102:                 if (defined($usertypes->{$item})) {
10103:                     push(@okstatuses,$item);  
10104:                 }
10105:             }
10106:             if (@okstatuses) {
10107:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
10108:             }
10109:         }
10110:     }
10111:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
10112:                  $umode.', '.$first.', '.$middle.', '.
10113:                  $last.', '.$gene.', '.$email.', '.$inststatus;
10114:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
10115:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
10116:     } else {
10117:         $logmsg .= ' during self creation';
10118:     }
10119:     my $changed;
10120:     if ($newuser) {
10121:         $changed = 1;
10122:     } else {
10123:         foreach my $field (@fields) {
10124:             if ($names{$field} ne $oldnames{$field}) {
10125:                 $changed = 1;
10126:                 last;
10127:             }
10128:         }
10129:     }
10130:     unless ($changed) {
10131:         $logmsg = 'No changes in user information needed for: '.$logmsg;
10132:         &logthis($logmsg);
10133:         return 'ok';
10134:     }
10135:     my $reply = &put('environment', \%names, $udom,$uname);
10136:     if ($reply ne 'ok') { 
10137:         return 'error: '.$reply;
10138:     }
10139:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
10140:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
10141:     }
10142:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
10143:     &devalidate_cache_new('namescache',$uname.':'.$udom);
10144:     $logmsg = 'Success modifying user '.$logmsg;
10145:     &logthis($logmsg);
10146:     return 'ok';
10147: }
10148: 
10149: # -------------------------------------------------------------- Modify student
10150: 
10151: sub modifystudent {
10152:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
10153:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
10154:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
10155:     if (!$cid) {
10156: 	unless ($cid=$env{'request.course.id'}) {
10157: 	    return 'not_in_class';
10158: 	}
10159:     }
10160: # --------------------------------------------------------------- Make the user
10161:     my $reply=&modifyuser
10162: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
10163:          $desiredhome,$email,$inststatus);
10164:     unless ($reply eq 'ok') { return $reply; }
10165:     # This will cause &modify_student_enrollment to get the uid from the
10166:     # student's environment
10167:     $uid = undef if (!$forceid);
10168:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
10169: 					$gene,$usec,$end,$start,$type,$locktype,
10170:                                         $cid,$selfenroll,$context,$credits,$instsec);
10171:     return $reply;
10172: }
10173: 
10174: sub modify_student_enrollment {
10175:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
10176:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
10177:     my ($cdom,$cnum,$chome);
10178:     if (!$cid) {
10179: 	unless ($cid=$env{'request.course.id'}) {
10180: 	    return 'not_in_class';
10181: 	}
10182: 	$cdom=$env{'course.'.$cid.'.domain'};
10183: 	$cnum=$env{'course.'.$cid.'.num'};
10184:     } else {
10185: 	($cdom,$cnum)=split(/_/,$cid);
10186:     }
10187:     $chome=$env{'course.'.$cid.'.home'};
10188:     if (!$chome) {
10189: 	$chome=&homeserver($cnum,$cdom);
10190:     }
10191:     if (!$chome) { return 'unknown_course'; }
10192:     # Make sure the user exists
10193:     my $uhome=&homeserver($uname,$udom);
10194:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
10195: 	return 'error: no such user';
10196:     }
10197:     # Get student data if we were not given enough information
10198:     if (!defined($first)  || $first  eq '' || 
10199:         !defined($last)   || $last   eq '' || 
10200:         !defined($uid)    || $uid    eq '' || 
10201:         !defined($middle) || $middle eq '' || 
10202:         !defined($gene)   || $gene   eq '') {
10203:         # They did not supply us with enough data to enroll the student, so
10204:         # we need to pick up more information.
10205:         my %tmp = &get('environment',
10206:                        ['firstname','middlename','lastname', 'generation','id']
10207:                        ,$udom,$uname);
10208: 
10209:         #foreach my $key (keys(%tmp)) {
10210:         #    &logthis("key $key = ".$tmp{$key});
10211:         #}
10212:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
10213:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
10214:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
10215:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
10216:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
10217:     }
10218:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
10219:     my $user = "$uname:$udom";
10220:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
10221:     my $reply=cput('classlist',
10222: 		   {$user => 
10223: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
10224: 		   $cdom,$cnum);
10225:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
10226:         &devalidate_getsection_cache($udom,$uname,$cid);
10227:     } else { 
10228: 	return 'error: '.$reply;
10229:     }
10230:     # Add student role to user
10231:     my $uurl='/'.$cid;
10232:     $uurl=~s/\_/\//g;
10233:     if ($usec) {
10234: 	$uurl.='/'.$usec;
10235:     }
10236:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
10237:                              $selfenroll,$context);
10238:     if ($result ne 'ok') {
10239:         if ($old_entry{$user} ne '') {
10240:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
10241:         } else {
10242:             $reply = &del('classlist',[$user],$cdom,$cnum);
10243:         }
10244:     }
10245:     return $result; 
10246: }
10247: 
10248: sub format_name {
10249:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
10250:     my $name;
10251:     if ($first ne 'lastname') {
10252: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
10253:     } else {
10254: 	if ($lastname=~/\S/) {
10255: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
10256: 	    $name=~s/\s+,/,/;
10257: 	} else {
10258: 	    $name.= $firstname.' '.$middlename.' '.$generation;
10259: 	}
10260:     }
10261:     $name=~s/^\s+//;
10262:     $name=~s/\s+$//;
10263:     $name=~s/\s+/ /g;
10264:     return $name;
10265: }
10266: 
10267: # ------------------------------------------------- Write to course preferences
10268: 
10269: sub writecoursepref {
10270:     my ($courseid,%prefs)=@_;
10271:     $courseid=~s/^\///;
10272:     $courseid=~s/\_/\//g;
10273:     my ($cdomain,$cnum)=split(/\//,$courseid);
10274:     my $chome=homeserver($cnum,$cdomain);
10275:     if (($chome eq '') || ($chome eq 'no_host')) { 
10276: 	return 'error: no such course';
10277:     }
10278:     my $cstring='';
10279:     foreach my $pref (keys(%prefs)) {
10280: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
10281:     }
10282:     $cstring=~s/\&$//;
10283:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
10284: }
10285: 
10286: # ---------------------------------------------------------- Make/modify course
10287: 
10288: sub createcourse {
10289:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
10290:         $course_owner,$crstype,$cnum,$context,$category)=@_;
10291:     $url=&declutter($url);
10292:     my $cid='';
10293:     if ($context eq 'requestcourses') {
10294:         my $can_create = 0;
10295:         my ($ownername,$ownerdom) = split(':',$course_owner);
10296:         if ($udom eq $ownerdom) {
10297:             if (&usertools_access($ownername,$ownerdom,$category,undef,
10298:                                   $context)) {
10299:                 $can_create = 1;
10300:             }
10301:         } else {
10302:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
10303:                                            $category);
10304:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
10305:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
10306:                 if (@curr > 0) {
10307:                     my @options = qw(approval validate autolimit);
10308:                     my $optregex = join('|',@options);
10309:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
10310:                         $can_create = 1;
10311:                     }
10312:                 }
10313:             }
10314:         }
10315:         if ($can_create) {
10316:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
10317:                 unless (&allowed('ccc',$udom)) {
10318:                     return 'refused'; 
10319:                 }
10320:             }
10321:         } else {
10322:             return 'refused';
10323:         }
10324:     } elsif (!&allowed('ccc',$udom)) {
10325:         return 'refused';
10326:     }
10327: # --------------------------------------------------------------- Get Unique ID
10328:     my $uname;
10329:     if ($cnum =~ /^$match_courseid$/) {
10330:         my $chome=&homeserver($cnum,$udom,'true');
10331:         if (($chome eq '') || ($chome eq 'no_host')) {
10332:             $uname = $cnum;
10333:         } else {
10334:             $uname = &generate_coursenum($udom,$crstype);
10335:         }
10336:     } else {
10337:         $uname = &generate_coursenum($udom,$crstype);
10338:     }
10339:     return $uname if ($uname =~ /^error/);
10340: # -------------------------------------------------- Check supplied server name
10341:     if (!defined($course_server)) {
10342:         if (defined(&domain($udom,'primary'))) {
10343:             $course_server = &domain($udom,'primary');
10344:         } else {
10345:             $course_server = $env{'user.home'}; 
10346:         }
10347:     }
10348:     my %host_servers =
10349:         &Apache::lonnet::get_servers($udom,'library');
10350:     unless ($host_servers{$course_server}) {
10351:         return 'error: invalid home server for course: '.$course_server;
10352:     }
10353: # ------------------------------------------------------------- Make the course
10354:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
10355:                       $course_server);
10356:     unless ($reply eq 'ok') { return 'error: '.$reply; }
10357:     my $uhome=&homeserver($uname,$udom,'true');
10358:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
10359: 	return 'error: no such course';
10360:     }
10361: # ----------------------------------------------------------------- Course made
10362: # log existence
10363:     my $now = time;
10364:     my $newcourse = {
10365:                     $udom.'_'.$uname => {
10366:                                      description => $description,
10367:                                      inst_code   => $inst_code,
10368:                                      owner       => $course_owner,
10369:                                      type        => $crstype,
10370:                                      creator     => $env{'user.name'}.':'.
10371:                                                     $env{'user.domain'},
10372:                                      created     => $now,
10373:                                      context     => $context,
10374:                                                 },
10375:                     };
10376:     &courseidput($udom,$newcourse,$uhome,'notime');
10377: # set toplevel url
10378:     my $topurl=$url;
10379:     unless ($nonstandard) {
10380: # ------------------------------------------ For standard courses, make top url
10381:         my $mapurl=&clutter($url);
10382:         if ($mapurl eq '/res/') { $mapurl=''; }
10383:         $env{'form.initmap'}=(<<ENDINITMAP);
10384: <map>
10385: <resource id="1" type="start"></resource>
10386: <resource id="2" src="$mapurl"></resource>
10387: <resource id="3" type="finish"></resource>
10388: <link index="1" from="1" to="2"></link>
10389: <link index="2" from="2" to="3"></link>
10390: </map>
10391: ENDINITMAP
10392:         $topurl=&declutter(
10393:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
10394:                           );
10395:     }
10396: # ----------------------------------------------------------- Write preferences
10397:     &writecoursepref($udom.'_'.$uname,
10398:                      ('description'              => $description,
10399:                       'url'                      => $topurl,
10400:                       'internal.creator'         => $env{'user.name'}.':'.
10401:                                                     $env{'user.domain'},
10402:                       'internal.created'         => $now,
10403:                       'internal.creationcontext' => $context)
10404:                     );
10405:     return '/'.$udom.'/'.$uname;
10406: }
10407: 
10408: # ------------------------------------------------------------------- Create ID
10409: sub generate_coursenum {
10410:     my ($udom,$crstype) = @_;
10411:     my $domdesc = &domain($udom);
10412:     return 'error: invalid domain' if ($domdesc eq '');
10413:     my $first;
10414:     if ($crstype eq 'Community') {
10415:         $first = '0';
10416:     } else {
10417:         $first = int(1+rand(9)); 
10418:     } 
10419:     my $uname=$first.
10420:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10421:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
10422:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10423: # ----------------------------------------------- Make sure that does not exist
10424:     my $uhome=&homeserver($uname,$udom,'true');
10425:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
10426:         if ($crstype eq 'Community') {
10427:             $first = '0';
10428:         } else {
10429:             $first = int(1+rand(9));
10430:         }
10431:         $uname=$first.
10432:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10433:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
10434:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10435:         $uhome=&homeserver($uname,$udom,'true');
10436:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
10437:             return 'error: unable to generate unique course-ID';
10438:         }
10439:     }
10440:     return $uname;
10441: }
10442: 
10443: sub is_course {
10444:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
10445:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
10446:     return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
10447:     my $uhome=&homeserver($cnum,$cdom);
10448:     my $iscourse;
10449:     if (grep { $_ eq $uhome } current_machine_ids()) {
10450:         $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
10451:     } else {
10452:         my $hashid = $cdom.':'.$cnum;
10453:         ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
10454:         unless (defined($cached)) {
10455:             my %courses = &courseiddump($cdom, '.', 1, '.', '.',
10456:                                         $cnum,undef,undef,'.');
10457:             $iscourse = 0;
10458:             if (exists($courses{$cdom.'_'.$cnum})) {
10459:                 $iscourse = 1;
10460:             }
10461:             &do_cache_new('iscourse',$hashid,$iscourse,3600);
10462:         }
10463:     }
10464:     return unless($iscourse);
10465:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
10466: }
10467: 
10468: sub store_userdata {
10469:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
10470:     my $result;
10471:     if ($datakey ne '') {
10472:         if (ref($storehash) eq 'HASH') {
10473:             if ($udom eq '' || $uname eq '') {
10474:                 $udom = $env{'user.domain'};
10475:                 $uname = $env{'user.name'};
10476:             }
10477:             my $uhome=&homeserver($uname,$udom);
10478:             if (($uhome eq '') || ($uhome eq 'no_host')) {
10479:                 $result = 'error: no_host';
10480:             } else {
10481:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
10482:                 $storehash->{'host'} = $perlvar{'lonHostID'};
10483: 
10484:                 my $namevalue='';
10485:                 foreach my $key (keys(%{$storehash})) {
10486:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
10487:                 }
10488:                 $namevalue=~s/\&$//;
10489:                 unless ($namespace eq 'courserequests') {
10490:                     $datakey = &escape($datakey);
10491:                 }
10492:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
10493:                                   $namevalue,$uhome);
10494:             }
10495:         } else {
10496:             $result = 'error: data to store was not a hash reference'; 
10497:         }
10498:     } else {
10499:         $result= 'error: invalid requestkey'; 
10500:     }
10501:     return $result;
10502: }
10503: 
10504: # ---------------------------------------------------------- Assign Custom Role
10505: 
10506: sub assigncustomrole {
10507:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
10508:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
10509:                        $end,$start,$deleteflag,$selfenroll,$context);
10510: }
10511: 
10512: # ----------------------------------------------------------------- Revoke Role
10513: 
10514: sub revokerole {
10515:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
10516:     my $now=time;
10517:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
10518: }
10519: 
10520: # ---------------------------------------------------------- Revoke Custom Role
10521: 
10522: sub revokecustomrole {
10523:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
10524:     my $now=time;
10525:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
10526:            $deleteflag,$selfenroll,$context);
10527: }
10528: 
10529: # ------------------------------------------------------------ Disk usage
10530: sub diskusage {
10531:     my ($udom,$uname,$directorypath,$getpropath)=@_;
10532:     $directorypath =~ s/\/$//;
10533:     my $listing=&reply('du2:'.&escape($directorypath).':'
10534:                        .&escape($getpropath).':'.&escape($uname).':'
10535:                        .&escape($udom),homeserver($uname,$udom));
10536:     if ($listing eq 'unknown_cmd') {
10537:         if ($getpropath) {
10538:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
10539:         }
10540:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
10541:     }
10542:     return $listing;
10543: }
10544: 
10545: sub is_locked {
10546:     my ($file_name, $domain, $user, $which) = @_;
10547:     my @check;
10548:     my $is_locked;
10549:     push (@check,$file_name);
10550:     my %locked = &get('file_permissions',\@check,
10551: 		      $env{'user.domain'},$env{'user.name'});
10552:     my ($tmp)=keys(%locked);
10553:     if ($tmp=~/^error:/) { undef(%locked); }
10554:     
10555:     if (ref($locked{$file_name}) eq 'ARRAY') {
10556:         $is_locked = 'false';
10557:         foreach my $entry (@{$locked{$file_name}}) {
10558:            if (ref($entry) eq 'ARRAY') {
10559:                $is_locked = 'true';
10560:                if (ref($which) eq 'ARRAY') {
10561:                    push(@{$which},$entry);
10562:                } else {
10563:                    last;
10564:                }
10565:            }
10566:        }
10567:     } else {
10568:         $is_locked = 'false';
10569:     }
10570:     return $is_locked;
10571: }
10572: 
10573: sub declutter_portfile {
10574:     my ($file) = @_;
10575:     $file =~ s{^(/portfolio/|portfolio/)}{/};
10576:     return $file;
10577: }
10578: 
10579: # ------------------------------------------------------------- Mark as Read Only
10580: 
10581: sub mark_as_readonly {
10582:     my ($domain,$user,$files,$what) = @_;
10583:     my %current_permissions = &dump('file_permissions',$domain,$user);
10584:     my ($tmp)=keys(%current_permissions);
10585:     if ($tmp=~/^error:/) { undef(%current_permissions); }
10586:     foreach my $file (@{$files}) {
10587: 	$file = &declutter_portfile($file);
10588:         push(@{$current_permissions{$file}},$what);
10589:     }
10590:     &put('file_permissions',\%current_permissions,$domain,$user);
10591:     return;
10592: }
10593: 
10594: # ------------------------------------------------------------Save Selected Files
10595: 
10596: sub save_selected_files {
10597:     my ($user, $path, @files) = @_;
10598:     my $filename = $user."savedfiles";
10599:     my @other_files = &files_not_in_path($user, $path);
10600:     open (OUT,'>',LONCAPA::tempdir().$filename);
10601:     foreach my $file (@files) {
10602:         print (OUT $env{'form.currentpath'}.$file."\n");
10603:     }
10604:     foreach my $file (@other_files) {
10605:         print (OUT $file."\n");
10606:     }
10607:     close (OUT);
10608:     return 'ok';
10609: }
10610: 
10611: sub clear_selected_files {
10612:     my ($user) = @_;
10613:     my $filename = $user."savedfiles";
10614:     open (OUT,'>',LONCAPA::tempdir().$filename);
10615:     print (OUT undef);
10616:     close (OUT);
10617:     return ("ok");    
10618: }
10619: 
10620: sub files_in_path {
10621:     my ($user, $path) = @_;
10622:     my $filename = $user."savedfiles";
10623:     my %return_files;
10624:     open (IN,'<',LONCAPA::tempdir().$filename);
10625:     while (my $line_in = <IN>) {
10626:         chomp ($line_in);
10627:         my @paths_and_file = split (m!/!, $line_in);
10628:         my $file_part = pop (@paths_and_file);
10629:         my $path_part = join ('/', @paths_and_file);
10630:         $path_part.='/';
10631:         my $path_and_file = $path_part.$file_part;
10632:         if ($path_part eq $path) {
10633:             $return_files{$file_part}= 'selected';
10634:         }
10635:     }
10636:     close (IN);
10637:     return (\%return_files);
10638: }
10639: 
10640: # called in portfolio select mode, to show files selected NOT in current directory
10641: sub files_not_in_path {
10642:     my ($user, $path) = @_;
10643:     my $filename = $user."savedfiles";
10644:     my @return_files;
10645:     my $path_part;
10646:     open(IN, '<',LONCAPA::tempdir().$filename);
10647:     while (my $line = <IN>) {
10648:         #ok, I know it's clunky, but I want it to work
10649:         my @paths_and_file = split(m|/|, $line);
10650:         my $file_part = pop(@paths_and_file);
10651:         chomp($file_part);
10652:         my $path_part = join('/', @paths_and_file);
10653:         $path_part .= '/';
10654:         my $path_and_file = $path_part.$file_part;
10655:         if ($path_part ne $path) {
10656:             push(@return_files, ($path_and_file));
10657:         }
10658:     }
10659:     close(OUT);
10660:     return (@return_files);
10661: }
10662: 
10663: #----------------------------------------------Get portfolio file permissions
10664: 
10665: sub get_portfile_permissions {
10666:     my ($domain,$user) = @_;
10667:     my %current_permissions = &dump('file_permissions',$domain,$user);
10668:     my ($tmp)=keys(%current_permissions);
10669:     if ($tmp=~/^error:/) { undef(%current_permissions); }
10670:     return \%current_permissions;
10671: }
10672: 
10673: #---------------------------------------------Get portfolio file access controls
10674: 
10675: sub get_access_controls {
10676:     my ($current_permissions,$group,$file) = @_;
10677:     my %access;
10678:     my $real_file = $file;
10679:     $file =~ s/\.meta$//;
10680:     if (defined($file)) {
10681:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
10682:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
10683:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
10684:             }
10685:         }
10686:     } else {
10687:         foreach my $key (keys(%{$current_permissions})) {
10688:             if ($key =~ /\0accesscontrol$/) {
10689:                 if (defined($group)) {
10690:                     if ($key !~ m-^\Q$group\E/-) {
10691:                         next;
10692:                     }
10693:                 }
10694:                 my ($fullpath) = split(/\0/,$key);
10695:                 if (ref($$current_permissions{$key}) eq 'HASH') {
10696:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
10697:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
10698:                     }
10699:                 }
10700:             }
10701:         }
10702:     }
10703:     return %access;
10704: }
10705: 
10706: sub modify_access_controls {
10707:     my ($file_name,$changes,$domain,$user)=@_;
10708:     my ($outcome,$deloutcome);
10709:     my %store_permissions;
10710:     my %new_values;
10711:     my %new_control;
10712:     my %translation;
10713:     my @deletions = ();
10714:     my $now = time;
10715:     if (exists($$changes{'activate'})) {
10716:         if (ref($$changes{'activate'}) eq 'HASH') {
10717:             my @newitems = sort(keys(%{$$changes{'activate'}}));
10718:             my $numnew = scalar(@newitems);
10719:             for (my $i=0; $i<$numnew; $i++) {
10720:                 my $newkey = $newitems[$i];
10721:                 my $newid = &Apache::loncommon::get_cgi_id();
10722:                 if ($newkey =~ /^\d+:/) { 
10723:                     $newkey =~ s/^(\d+)/$newid/;
10724:                     $translation{$1} = $newid;
10725:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
10726:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
10727:                     $translation{$1} = $newid;
10728:                 }
10729:                 $new_values{$file_name."\0".$newkey} = 
10730:                                           $$changes{'activate'}{$newitems[$i]};
10731:                 $new_control{$newkey} = $now;
10732:             }
10733:         }
10734:     }
10735:     my %todelete;
10736:     my %changed_items;
10737:     foreach my $action ('delete','update') {
10738:         if (exists($$changes{$action})) {
10739:             if (ref($$changes{$action}) eq 'HASH') {
10740:                 foreach my $key (keys(%{$$changes{$action}})) {
10741:                     my ($itemnum) = ($key =~ /^([^:]+):/);
10742:                     if ($action eq 'delete') { 
10743:                         $todelete{$itemnum} = 1;
10744:                     } else {
10745:                         $changed_items{$itemnum} = $key;
10746:                     }
10747:                 }
10748:             }
10749:         }
10750:     }
10751:     # get lock on access controls for file.
10752:     my $lockhash = {
10753:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
10754:                                                        ':'.$env{'user.domain'},
10755:                    }; 
10756:     my $tries = 0;
10757:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10758:    
10759:     while (($gotlock ne 'ok') && $tries < 10) {
10760:         $tries ++;
10761:         sleep(0.1);
10762:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10763:     }
10764:     if ($gotlock eq 'ok') {
10765:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
10766:         my ($tmp)=keys(%curr_permissions);
10767:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
10768:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
10769:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
10770:             if (ref($curr_controls) eq 'HASH') {
10771:                 foreach my $control_item (keys(%{$curr_controls})) {
10772:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
10773:                     if (defined($todelete{$itemnum})) {
10774:                         push(@deletions,$file_name."\0".$control_item);
10775:                     } else {
10776:                         if (defined($changed_items{$itemnum})) {
10777:                             $new_control{$changed_items{$itemnum}} = $now;
10778:                             push(@deletions,$file_name."\0".$control_item);
10779:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
10780:                         } else {
10781:                             $new_control{$control_item} = $$curr_controls{$control_item};
10782:                         }
10783:                     }
10784:                 }
10785:             }
10786:         }
10787:         my ($group);
10788:         if (&is_course($domain,$user)) {
10789:             ($group,my $file) = split(/\//,$file_name,2);
10790:         }
10791:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
10792:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
10793:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
10794:         #  remove lock
10795:         my @del_lock = ($file_name."\0".'locked_access_records');
10796:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
10797:         my $sqlresult =
10798:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
10799:                                     $group);
10800:     } else {
10801:         $outcome = "error: could not obtain lockfile\n";  
10802:     }
10803:     return ($outcome,$deloutcome,\%new_values,\%translation);
10804: }
10805: 
10806: sub make_public_indefinitely {
10807:     my ($requrl) = @_;
10808:     my $now = time;
10809:     my $action = 'activate';
10810:     my $aclnum = 0;
10811:     if (&is_portfolio_url($requrl)) {
10812:         my (undef,$udom,$unum,$file_name,$group) =
10813:             &parse_portfolio_url($requrl);
10814:         my $current_perms = &get_portfile_permissions($udom,$unum);
10815:         my %access_controls = &get_access_controls($current_perms,
10816:                                                    $group,$file_name);
10817:         foreach my $key (keys(%{$access_controls{$file_name}})) {
10818:             my ($num,$scope,$end,$start) = 
10819:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
10820:             if ($scope eq 'public') {
10821:                 if ($start <= $now && $end == 0) {
10822:                     $action = 'none';
10823:                 } else {
10824:                     $action = 'update';
10825:                     $aclnum = $num;
10826:                 }
10827:                 last;
10828:             }
10829:         }
10830:         if ($action eq 'none') {
10831:              return 'ok';
10832:         } else {
10833:             my %changes;
10834:             my $newend = 0;
10835:             my $newstart = $now;
10836:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
10837:             $changes{$action}{$newkey} = {
10838:                 type => 'public',
10839:                 time => {
10840:                     start => $newstart,
10841:                     end   => $newend,
10842:                 },
10843:             };
10844:             my ($outcome,$deloutcome,$new_values,$translation) =
10845:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
10846:             return $outcome;
10847:         }
10848:     } else {
10849:         return 'invalid';
10850:     }
10851: }
10852: 
10853: #------------------------------------------------------Get Marked as Read Only
10854: 
10855: sub get_marked_as_readonly {
10856:     my ($domain,$user,$what,$group) = @_;
10857:     my $current_permissions = &get_portfile_permissions($domain,$user);
10858:     my @readonly_files;
10859:     my $cmp1=$what;
10860:     if (ref($what)) { $cmp1=join('',@{$what}) };
10861:     while (my ($file_name,$value) = each(%{$current_permissions})) {
10862:         if (defined($group)) {
10863:             if ($file_name !~ m-^\Q$group\E/-) {
10864:                 next;
10865:             }
10866:         }
10867:         if (ref($value) eq "ARRAY"){
10868:             foreach my $stored_what (@{$value}) {
10869:                 my $cmp2=$stored_what;
10870:                 if (ref($stored_what) eq 'ARRAY') {
10871:                     $cmp2=join('',@{$stored_what});
10872:                 }
10873:                 if ($cmp1 eq $cmp2) {
10874:                     push(@readonly_files, $file_name);
10875:                     last;
10876:                 } elsif (!defined($what)) {
10877:                     push(@readonly_files, $file_name);
10878:                     last;
10879:                 }
10880:             }
10881:         }
10882:     }
10883:     return @readonly_files;
10884: }
10885: #-----------------------------------------------------------Get Marked as Read Only Hash
10886: 
10887: sub get_marked_as_readonly_hash {
10888:     my ($current_permissions,$group,$what) = @_;
10889:     my %readonly_files;
10890:     while (my ($file_name,$value) = each(%{$current_permissions})) {
10891:         if (defined($group)) {
10892:             if ($file_name !~ m-^\Q$group\E/-) {
10893:                 next;
10894:             }
10895:         }
10896:         if (ref($value) eq "ARRAY"){
10897:             foreach my $stored_what (@{$value}) {
10898:                 if (ref($stored_what) eq 'ARRAY') {
10899:                     foreach my $lock_descriptor(@{$stored_what}) {
10900:                         if ($lock_descriptor eq 'graded') {
10901:                             $readonly_files{$file_name} = 'graded';
10902:                         } elsif ($lock_descriptor eq 'handback') {
10903:                             $readonly_files{$file_name} = 'handback';
10904:                         } else {
10905:                             if (!exists($readonly_files{$file_name})) {
10906:                                 $readonly_files{$file_name} = 'locked';
10907:                             }
10908:                         }
10909:                     }
10910:                 } 
10911:             }
10912:         } 
10913:     }
10914:     return %readonly_files;
10915: }
10916: # ------------------------------------------------------------ Unmark as Read Only
10917: 
10918: sub unmark_as_readonly {
10919:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
10920:     # for portfolio submissions, $what contains [$symb,$crsid] 
10921:     my ($domain,$user,$what,$file_name,$group) = @_;
10922:     $file_name = &declutter_portfile($file_name);
10923:     my $symb_crs = $what;
10924:     if (ref($what)) { $symb_crs=join('',@$what); }
10925:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
10926:     my ($tmp)=keys(%current_permissions);
10927:     if ($tmp=~/^error:/) { undef(%current_permissions); }
10928:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
10929:     foreach my $file (@readonly_files) {
10930: 	my $clean_file = &declutter_portfile($file);
10931: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
10932: 	my $current_locks = $current_permissions{$file};
10933:         my @new_locks;
10934:         my @del_keys;
10935:         if (ref($current_locks) eq "ARRAY"){
10936:             foreach my $locker (@{$current_locks}) {
10937:                 my $compare=$locker;
10938:                 if (ref($locker) eq 'ARRAY') {
10939:                     $compare=join('',@{$locker});
10940:                     if ($compare ne $symb_crs) {
10941:                         push(@new_locks, $locker);
10942:                     }
10943:                 }
10944:             }
10945:             if (scalar(@new_locks) > 0) {
10946:                 $current_permissions{$file} = \@new_locks;
10947:             } else {
10948:                 push(@del_keys, $file);
10949:                 &del('file_permissions',\@del_keys, $domain, $user);
10950:                 delete($current_permissions{$file});
10951:             }
10952:         }
10953:     }
10954:     &put('file_permissions',\%current_permissions,$domain,$user);
10955:     return;
10956: }
10957: 
10958: # ------------------------------------------------------------ Directory lister
10959: 
10960: sub dirlist {
10961:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
10962:     $uri=~s/^\///;
10963:     $uri=~s/\/$//;
10964:     my ($udom, $uname);
10965:     if ($getuserdir) {
10966:         $udom = $userdomain;
10967:         $uname = $username;
10968:     } else {
10969:         (undef,$udom,$uname)=split(/\//,$uri);
10970:         if(defined($userdomain)) {
10971:             $udom = $userdomain;
10972:         }
10973:         if(defined($username)) {
10974:             $uname = $username;
10975:         }
10976:     }
10977:     my ($dirRoot,$listing,@listing_results);
10978: 
10979:     $dirRoot = $perlvar{'lonDocRoot'};
10980:     if (defined($getpropath)) {
10981:         $dirRoot = &propath($udom,$uname);
10982:         $dirRoot =~ s/\/$//;
10983:     } elsif (defined($getuserdir)) {
10984:         my $subdir=$uname.'__';
10985:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
10986:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
10987:                    ."/$udom/$subdir/$uname";
10988:     } elsif (defined($alternateRoot)) {
10989:         $dirRoot = $alternateRoot;
10990:     }
10991: 
10992:     if($udom) {
10993:         if($uname) {
10994:             my $uhome = &homeserver($uname,$udom);
10995:             if ($uhome eq 'no_host') {
10996:                 return ([],'no_host');
10997:             }
10998:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
10999:                               .$getuserdir.':'.&escape($dirRoot)
11000:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
11001:             if ($listing eq 'unknown_cmd') {
11002:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
11003:             } else {
11004:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
11005:             }
11006:             if ($listing eq 'unknown_cmd') {
11007:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
11008:                 @listing_results = split(/:/,$listing);
11009:             } else {
11010:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
11011:             }
11012:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
11013:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
11014:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11015:                 return ([],$listing);
11016:             } else {
11017:                 return (\@listing_results);
11018:             }
11019:         } elsif(!$alternateRoot) {
11020:             my (%allusers,%listerror);
11021: 	    my %servers = &get_servers($udom,'library');
11022:  	    foreach my $tryserver (keys(%servers)) {
11023:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
11024:                                   &escape($udom),$tryserver);
11025:                 if ($listing eq 'unknown_cmd') {
11026: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
11027: 				      $udom, $tryserver);
11028:                 } else {
11029:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
11030:                 }
11031: 		if ($listing eq 'unknown_cmd') {
11032: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
11033: 				      $udom, $tryserver);
11034: 		    @listing_results = split(/:/,$listing);
11035: 		} else {
11036: 		    @listing_results =
11037: 			map { &unescape($_); } split(/:/,$listing);
11038: 		}
11039:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
11040:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
11041:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11042:                     $listerror{$tryserver} = $listing;
11043:                 } else {
11044: 		    foreach my $line (@listing_results) {
11045: 			my ($entry) = split(/&/,$line,2);
11046: 			$allusers{$entry} = 1;
11047: 		    }
11048: 		}
11049:             }
11050:             my @alluserslist=();
11051:             foreach my $user (sort(keys(%allusers))) {
11052:                 push(@alluserslist,$user.'&user');
11053:             }
11054:             if (!%listerror) {
11055:                 # no errors
11056:                 return (\@alluserslist);
11057:             } elsif (scalar(keys(%servers)) == 1) {
11058:                 # one library server, one error
11059:                 my ($key) = keys(%listerror);
11060:                 return (\@alluserslist, $listerror{$key});
11061:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
11062:                 # con_lost indicates that we might miss data from at least one
11063:                 # library server
11064:                 return (\@alluserslist, 'con_lost');
11065:             } else {
11066:                 # multiple library servers and no con_lost -> data should be
11067:                 # complete.
11068:                 return (\@alluserslist);
11069:             }
11070: 
11071:         } else {
11072:             return ([],'missing username');
11073:         }
11074:     } elsif(!defined($getpropath)) {
11075:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
11076:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
11077:         return (\@all_domains);
11078:     } else {
11079:         return ([],'missing domain');
11080:     }
11081: }
11082: 
11083: # --------------------------------------------- GetFileTimestamp
11084: # This function utilizes dirlist and returns the date stamp for
11085: # when it was last modified.  It will also return an error of -1
11086: # if an error occurs
11087: 
11088: sub GetFileTimestamp {
11089:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
11090:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
11091:     $studentName   = &LONCAPA::clean_username($studentName);
11092:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
11093:                                     undef,$getuserdir);
11094:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11095:         return -1;
11096:     }
11097:     if (ref($fileref) eq 'ARRAY') {
11098:         my @stats = split('&',$fileref->[0]);
11099:         # @stats contains first the filename, then the stat output
11100:         return $stats[10]; # so this is 10 instead of 9.
11101:     } else {
11102:         return -1;
11103:     }
11104: }
11105: 
11106: sub stat_file {
11107:     my ($uri) = @_;
11108:     $uri = &clutter_with_no_wrapper($uri);
11109: 
11110:     my ($udom,$uname,$file);
11111:     if ($uri =~ m-^/(uploaded|editupload)/-) {
11112: 	($udom,$uname,$file) =
11113: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
11114: 	$file = 'userfiles/'.$file;
11115:     }
11116:     if ($uri =~ m-^/res/-) {
11117: 	($udom,$uname) = 
11118: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
11119: 	$file = $uri;
11120:     }
11121: 
11122:     if (!$udom || !$uname || !$file) {
11123: 	# unable to handle the uri
11124: 	return ();
11125:     }
11126:     my $getpropath;
11127:     if ($file =~ /^userfiles\//) {
11128:         $getpropath = 1;
11129:     }
11130:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
11131:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11132:         return ();
11133:     } else {
11134:         if (ref($listref) eq 'ARRAY') {
11135:             my @stats = split('&',$listref->[0]);
11136: 	    shift(@stats); #filename is first
11137: 	    return @stats;
11138:         }
11139:     }
11140:     return ();
11141: }
11142: 
11143: # -------------------------------------------------------- Value of a Condition
11144: 
11145: # gets the value of a specific preevaluated condition
11146: #    stored in the string  $env{user.state.<cid>}
11147: # or looks up a condition reference in the bighash and if if hasn't
11148: # already been evaluated recurses into docondval to get the value of
11149: # the condition, then memoizing it to 
11150: #   $env{user.state.<cid>.<condition>}
11151: sub directcondval {
11152:     my $number=shift;
11153:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
11154: 	&Apache::lonuserstate::evalstate();
11155:     }
11156:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
11157: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
11158:     } elsif ($number =~ /^_/) {
11159: 	my $sub_condition;
11160: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11161: 		&GDBM_READER(),0640)) {
11162: 	    $sub_condition=$bighash{'conditions'.$number};
11163: 	    untie(%bighash);
11164: 	}
11165: 	my $value = &docondval($sub_condition);
11166: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
11167: 	return $value;
11168:     }
11169:     if ($env{'user.state.'.$env{'request.course.id'}}) {
11170:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
11171:     } else {
11172:        return 2;
11173:     }
11174: }
11175: 
11176: # get the collection of conditions for this resource
11177: sub condval {
11178:     my $condidx=shift;
11179:     my $allpathcond='';
11180:     foreach my $cond (split(/\|/,$condidx)) {
11181: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
11182: 	    $allpathcond.=
11183: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
11184: 	}
11185:     }
11186:     $allpathcond=~s/\|$//;
11187:     return &docondval($allpathcond);
11188: }
11189: 
11190: #evaluates an expression of conditions
11191: sub docondval {
11192:     my ($allpathcond) = @_;
11193:     my $result=0;
11194:     if ($env{'request.course.id'}
11195: 	&& defined($allpathcond)) {
11196: 	my $operand='|';
11197: 	my @stack;
11198: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
11199: 	    if ($chunk eq '(') {
11200: 		push @stack,($operand,$result);
11201: 	    } elsif ($chunk eq ')') {
11202: 		my $before=pop @stack;
11203: 		if (pop @stack eq '&') {
11204: 		    $result=$result>$before?$before:$result;
11205: 		} else {
11206: 		    $result=$result>$before?$result:$before;
11207: 		}
11208: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
11209: 		$operand=$chunk;
11210: 	    } else {
11211: 		my $new=directcondval($chunk);
11212: 		if ($operand eq '&') {
11213: 		    $result=$result>$new?$new:$result;
11214: 		} else {
11215: 		    $result=$result>$new?$result:$new;
11216: 		}
11217: 	    }
11218: 	}
11219:     }
11220:     return $result;
11221: }
11222: 
11223: # ---------------------------------------------------- Devalidate courseresdata
11224: 
11225: sub devalidatecourseresdata {
11226:     my ($coursenum,$coursedomain)=@_;
11227:     my $hashid=$coursenum.':'.$coursedomain;
11228:     &devalidate_cache_new('courseres',$hashid);
11229: }
11230: 
11231: 
11232: # --------------------------------------------------- Course Resourcedata Query
11233: #
11234: #  Parameters:
11235: #      $coursenum    - Number of the course.
11236: #      $coursedomain - Domain at which the course was created.
11237: #  Returns:
11238: #     A hash of the course parameters along (I think) with timestamps
11239: #     and version info.
11240: 
11241: sub get_courseresdata {
11242:     my ($coursenum,$coursedomain)=@_;
11243:     my $coursehom=&homeserver($coursenum,$coursedomain);
11244:     my $hashid=$coursenum.':'.$coursedomain;
11245:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
11246:     my %dumpreply;
11247:     unless (defined($cached)) {
11248: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
11249: 	$result=\%dumpreply;
11250: 	my ($tmp) = keys(%dumpreply);
11251: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
11252: 	    &do_cache_new('courseres',$hashid,$result,600);
11253: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
11254: 	    return $tmp;
11255: 	} elsif ($tmp =~ /^(error)/) {
11256: 	    $result=undef;
11257: 	    &do_cache_new('courseres',$hashid,$result,600);
11258: 	}
11259:     }
11260:     return $result;
11261: }
11262: 
11263: sub devalidateuserresdata {
11264:     my ($uname,$udom)=@_;
11265:     my $hashid="$udom:$uname";
11266:     &devalidate_cache_new('userres',$hashid);
11267: }
11268: 
11269: sub get_userresdata {
11270:     my ($uname,$udom)=@_;
11271:     #most student don\'t have any data set, check if there is some data
11272:     if (&EXT_cache_status($udom,$uname)) { return undef; }
11273: 
11274:     my $hashid="$udom:$uname";
11275:     my ($result,$cached)=&is_cached_new('userres',$hashid);
11276:     if (!defined($cached)) {
11277: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
11278: 	$result=\%resourcedata;
11279: 	&do_cache_new('userres',$hashid,$result,600);
11280:     }
11281:     my ($tmp)=keys(%$result);
11282:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
11283: 	return $result;
11284:     }
11285:     #error 2 occurs when the .db doesn't exist
11286:     if ($tmp!~/error: 2 /) {
11287:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
11288: 	    &logthis("<font color=\"blue\">WARNING:".
11289: 		     " Trying to get resource data for ".
11290: 		     $uname." at ".$udom.": ".
11291: 		     $tmp."</font>");
11292:         }
11293:     } elsif ($tmp=~/error: 2 /) {
11294: 	#&EXT_cache_set($udom,$uname);
11295: 	&do_cache_new('userres',$hashid,undef,600);
11296: 	undef($tmp); # not really an error so don't send it back
11297:     }
11298:     return $tmp;
11299: }
11300: #----------------------------------------------- resdata - return resource data
11301: #  Purpose:
11302: #    Return resource data for either users or for a course.
11303: #  Parameters:
11304: #     $name      - Course/user name.
11305: #     $domain    - Name of the domain the user/course is registered on.
11306: #     $type      - Type of thing $name is (must be 'course' or 'user')
11307: #     @which     - Array of names of resources desired.
11308: #  Returns:
11309: #     The value of the first reasource in @which that is found in the
11310: #     resource hash.
11311: #  Exceptional Conditions:
11312: #     If the $type passed in is not valid (not the string 'course' or 
11313: #     'user', an undefined  reference is returned.
11314: #     If none of the resources are found, an undef is returned
11315: sub resdata {
11316:     my ($name,$domain,$type,@which)=@_;
11317:     my $result;
11318:     if ($type eq 'course') {
11319: 	$result=&get_courseresdata($name,$domain);
11320:     } elsif ($type eq 'user') {
11321: 	$result=&get_userresdata($name,$domain);
11322:     }
11323:     if (!ref($result)) { return $result; }    
11324:     foreach my $item (@which) {
11325:         if (ref($item) eq 'ARRAY') {
11326: 	    if (defined($result->{$item->[0]})) {
11327: 	        return [$result->{$item->[0]},$item->[1]];
11328: 	    }
11329:         }
11330:     }
11331:     return undef;
11332: }
11333: 
11334: sub get_domain_ltitools {
11335:     my ($cdom) = @_;
11336:     my %ltitools;
11337:     my ($result,$cached)=&is_cached_new('ltitools',$cdom);
11338:     if (defined($cached)) {
11339:         if (ref($result) eq 'HASH') {
11340:             %ltitools = %{$result};
11341:         }
11342:     } else {
11343:         my %domconfig = &get_dom('configuration',['ltitools'],$cdom);
11344:         if (ref($domconfig{'ltitools'}) eq 'HASH') {
11345:             %ltitools = %{$domconfig{'ltitools'}};
11346:             my %encdomconfig = &get_dom('encconfig',['ltitools'],$cdom);
11347:             if (ref($encdomconfig{'ltitools'}) eq 'HASH') {
11348:                 foreach my $id (keys(%ltitools)) {
11349:                     if (ref($encdomconfig{'ltitools'}{$id}) eq 'HASH') {
11350:                         foreach my $item ('key','secret') {
11351:                             $ltitools{$id}{$item} = $encdomconfig{'ltitools'}{$id}{$item};
11352:                         }
11353:                     }
11354:                 }
11355:             }
11356:         }
11357:         my $cachetime = 24*60*60;
11358:         &do_cache_new('ltitools',$cdom,\%ltitools,$cachetime);
11359:     }
11360:     return %ltitools;
11361: }
11362: 
11363: sub get_numsuppfiles {
11364:     my ($cnum,$cdom,$ignorecache)=@_;
11365:     my $hashid=$cnum.':'.$cdom;
11366:     my ($suppcount,$cached);
11367:     unless ($ignorecache) {
11368:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
11369:     }
11370:     unless (defined($cached)) {
11371:         my $chome=&homeserver($cnum,$cdom);
11372:         unless ($chome eq 'no_host') {
11373:             ($suppcount,my $errors) = (0,0);
11374:             my $suppmap = 'supplemental.sequence';
11375:             ($suppcount,$errors) =
11376:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
11377:         }
11378:         &do_cache_new('suppcount',$hashid,$suppcount,600);
11379:     }
11380:     return $suppcount;
11381: }
11382: 
11383: #
11384: # EXT resource caching routines
11385: #
11386: 
11387: sub clear_EXT_cache_status {
11388:     &delenv('cache.EXT.');
11389: }
11390: 
11391: sub EXT_cache_status {
11392:     my ($target_domain,$target_user) = @_;
11393:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
11394:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
11395:         # We know already the user has no data
11396:         return 1;
11397:     } else {
11398:         return 0;
11399:     }
11400: }
11401: 
11402: sub EXT_cache_set {
11403:     my ($target_domain,$target_user) = @_;
11404:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
11405:     #&appenv({$cachename => time});
11406: }
11407: 
11408: # --------------------------------------------------------- Value of a Variable
11409: sub EXT {
11410: 
11411:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
11412:     unless ($varname) { return ''; }
11413:     #get real user name/domain, courseid and symb
11414:     my $courseid;
11415:     my $publicuser;
11416:     if ($symbparm) {
11417: 	$symbparm=&get_symb_from_alias($symbparm);
11418:     }
11419:     if (!($uname && $udom)) {
11420:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
11421:       if (!$symbparm) {	$symbparm=$cursymb; }
11422:     } else {
11423: 	$courseid=$env{'request.course.id'};
11424:     }
11425:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
11426:     my $rest;
11427:     if (defined($therest[0])) {
11428:        $rest=join('.',@therest);
11429:     } else {
11430:        $rest='';
11431:     }
11432: 
11433:     my $qualifierrest=$qualifier;
11434:     if ($rest) { $qualifierrest.='.'.$rest; }
11435:     my $spacequalifierrest=$space;
11436:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
11437:     if ($realm eq 'user') {
11438: # --------------------------------------------------------------- user.resource
11439: 	if ($space eq 'resource') {
11440: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
11441: 		  || defined($Apache::lonhomework::parsing_a_task))
11442: 		 &&
11443: 		 ($symbparm eq &symbread()) ) {	
11444: 		# if we are in the middle of processing the resource the
11445: 		# get the value we are planning on committing
11446:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
11447:                     return $Apache::lonhomework::results{$qualifierrest};
11448:                 } else {
11449:                     return $Apache::lonhomework::history{$qualifierrest};
11450:                 }
11451: 	    } else {
11452: 		my %restored;
11453: 		if ($publicuser || $env{'request.state'} eq 'construct') {
11454: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
11455: 		} else {
11456: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
11457: 		}
11458: 		return $restored{$qualifierrest};
11459: 	    }
11460: # ----------------------------------------------------------------- user.access
11461:         } elsif ($space eq 'access') {
11462: 	    # FIXME - not supporting calls for a specific user
11463:             return &allowed($qualifier,$rest);
11464: # ------------------------------------------ user.preferences, user.environment
11465:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
11466: 	    if (($uname eq $env{'user.name'}) &&
11467: 		($udom eq $env{'user.domain'})) {
11468: 		return $env{join('.',('environment',$qualifierrest))};
11469: 	    } else {
11470: 		my %returnhash;
11471: 		if (!$publicuser) {
11472: 		    %returnhash=&userenvironment($udom,$uname,
11473: 						 $qualifierrest);
11474: 		}
11475: 		return $returnhash{$qualifierrest};
11476: 	    }
11477: # ----------------------------------------------------------------- user.course
11478:         } elsif ($space eq 'course') {
11479: 	    # FIXME - not supporting calls for a specific user
11480:             return $env{join('.',('request.course',$qualifier))};
11481: # ------------------------------------------------------------------- user.role
11482:         } elsif ($space eq 'role') {
11483: 	    # FIXME - not supporting calls for a specific user
11484:             my ($role,$where)=split(/\./,$env{'request.role'});
11485:             if ($qualifier eq 'value') {
11486: 		return $role;
11487:             } elsif ($qualifier eq 'extent') {
11488:                 return $where;
11489:             }
11490: # ----------------------------------------------------------------- user.domain
11491:         } elsif ($space eq 'domain') {
11492:             return $udom;
11493: # ------------------------------------------------------------------- user.name
11494:         } elsif ($space eq 'name') {
11495:             return $uname;
11496: # ---------------------------------------------------- Any other user namespace
11497:         } else {
11498: 	    my %reply;
11499: 	    if (!$publicuser) {
11500: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
11501: 	    }
11502: 	    return $reply{$qualifierrest};
11503:         }
11504:     } elsif ($realm eq 'query') {
11505: # ---------------------------------------------- pull stuff out of query string
11506:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
11507: 						[$spacequalifierrest]);
11508: 	return $env{'form.'.$spacequalifierrest}; 
11509:    } elsif ($realm eq 'request') {
11510: # ------------------------------------------------------------- request.browser
11511:         if ($space eq 'browser') {
11512:             return $env{'browser.'.$qualifier};
11513: # ------------------------------------------------------------ request.filename
11514:         } else {
11515:             return $env{'request.'.$spacequalifierrest};
11516:         }
11517:     } elsif ($realm eq 'course') {
11518: # ---------------------------------------------------------- course.description
11519:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
11520:     } elsif ($realm eq 'resource') {
11521: 
11522: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
11523: 	    if (!$symbparm) { $symbparm=&symbread(); }
11524: 	}
11525: 
11526:         if ($qualifier eq '') {
11527: 	    if ($space eq 'title') {
11528: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
11529: 	        return &gettitle($symbparm);
11530: 	    }
11531: 	
11532: 	    if ($space eq 'map') {
11533: 	        my ($map) = &decode_symb($symbparm);
11534: 	        return &symbread($map);
11535: 	    }
11536:             if ($space eq 'maptitle') {
11537:                 my ($map) = &decode_symb($symbparm);
11538:                 return &gettitle($map);
11539:             }
11540: 	    if ($space eq 'filename') {
11541: 	        if ($symbparm) {
11542: 		    return &clutter((&decode_symb($symbparm))[2]);
11543: 	        }
11544: 	        return &hreflocation('',$env{'request.filename'});
11545: 	    }
11546: 
11547:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
11548:                 if ($space eq 'visibleparts') {
11549:                     my $navmap = Apache::lonnavmaps::navmap->new();
11550:                     my $item;
11551:                     if (ref($navmap)) {
11552:                         my $res = $navmap->getBySymb($symbparm);
11553:                         my $parts = $res->parts();
11554:                         if (ref($parts) eq 'ARRAY') {
11555:                             $item = join(',',@{$parts});
11556:                         }
11557:                         undef($navmap);
11558:                     }
11559:                     return $item;
11560:                 }
11561:             }
11562:         }
11563: 
11564: 	my ($section, $group, @groups);
11565: 	my ($courselevelm,$courselevel);
11566:         if (($courseid eq '') && ($cid)) {
11567:             $courseid = $cid;
11568:         }
11569: 	if (($symbparm && $courseid) && 
11570: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
11571: 
11572: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
11573: 
11574: # ----------------------------------------------------- Cascading lookup scheme
11575: 	    my $symbp=$symbparm;
11576: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
11577: 
11578: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
11579: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
11580: 
11581: 	    if (($env{'user.name'} eq $uname) &&
11582: 		($env{'user.domain'} eq $udom)) {
11583: 		$section=$env{'request.course.sec'};
11584:                 @groups = split(/:/,$env{'request.course.groups'});  
11585:                 @groups=&sort_course_groups($courseid,@groups); 
11586: 	    } else {
11587: 		if (! defined($usection)) {
11588: 		    $section=&getsection($udom,$uname,$courseid);
11589: 		} else {
11590: 		    $section = $usection;
11591: 		}
11592:                 @groups = &get_users_groups($udom,$uname,$courseid);
11593: 	    }
11594: 
11595: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
11596: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
11597: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
11598: 
11599: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
11600: 	    my $courselevelr=$courseid.'.'.$symbparm;
11601: 	    $courselevelm=$courseid.'.'.$mapparm;
11602: 
11603: # ----------------------------------------------------------- first, check user
11604: 
11605: 	    my $userreply=&resdata($uname,$udom,'user',
11606: 				       ([$courselevelr,'resource'],
11607: 					[$courselevelm,'map'     ],
11608: 					[$courselevel, 'course'  ]));
11609: 	    if (defined($userreply)) { return &get_reply($userreply); }
11610: 
11611: # ------------------------------------------------ second, check some of course
11612:             my $coursereply;
11613:             if (@groups > 0) {
11614:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
11615:                                        $mapparm,$spacequalifierrest);
11616:                 if (defined($coursereply)) { return &get_reply($coursereply); }
11617:             }
11618: 
11619: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
11620: 				  $env{'course.'.$courseid.'.domain'},
11621: 				  'course',
11622: 				  ([$seclevelr,   'resource'],
11623: 				   [$seclevelm,   'map'     ],
11624: 				   [$seclevel,    'course'  ],
11625: 				   [$courselevelr,'resource']));
11626: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
11627: 
11628: # ------------------------------------------------------ third, check map parms
11629: 	    my %parmhash=();
11630: 	    my $thisparm='';
11631: 	    if (tie(%parmhash,'GDBM_File',
11632: 		    $env{'request.course.fn'}.'_parms.db',
11633: 		    &GDBM_READER(),0640)) {
11634: 		$thisparm=$parmhash{$symbparm};
11635: 		untie(%parmhash);
11636: 	    }
11637: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
11638: 	}
11639: # ------------------------------------------ fourth, look in resource metadata
11640: 
11641: 	$spacequalifierrest=~s/\./\_/;
11642: 	my $filename;
11643: 	if (!$symbparm) { $symbparm=&symbread(); }
11644: 	if ($symbparm) {
11645: 	    $filename=(&decode_symb($symbparm))[2];
11646: 	} else {
11647: 	    $filename=$env{'request.filename'};
11648: 	}
11649: 	my $metadata=&metadata($filename,$spacequalifierrest);
11650: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
11651: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
11652: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
11653: 
11654: # ---------------------------------------------- fourth, look in rest of course
11655: 	if ($symbparm && defined($courseid) && 
11656: 	    $courseid eq $env{'request.course.id'}) {
11657: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
11658: 				     $env{'course.'.$courseid.'.domain'},
11659: 				     'course',
11660: 				     ([$courselevelm,'map'   ],
11661: 				      [$courselevel, 'course']));
11662: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
11663: 	}
11664: # ------------------------------------------------------------------ Cascade up
11665: 	unless ($space eq '0') {
11666: 	    my @parts=split(/_/,$space);
11667: 	    my $id=pop(@parts);
11668: 	    my $part=join('_',@parts);
11669: 	    if ($part eq '') { $part='0'; }
11670: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
11671: 				 $symbparm,$udom,$uname,$section,1);
11672: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
11673: 	}
11674: 	if ($recurse) { return undef; }
11675: 	my $pack_def=&packages_tab_default($filename,$varname);
11676: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
11677: # ---------------------------------------------------- Any other user namespace
11678:     } elsif ($realm eq 'environment') {
11679: # ----------------------------------------------------------------- environment
11680: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
11681: 	    return $env{'environment.'.$spacequalifierrest};
11682: 	} else {
11683: 	    if ($uname eq 'anonymous' && $udom eq '') {
11684: 		return '';
11685: 	    }
11686: 	    my %returnhash=&userenvironment($udom,$uname,
11687: 					    $spacequalifierrest);
11688: 	    return $returnhash{$spacequalifierrest};
11689: 	}
11690:     } elsif ($realm eq 'system') {
11691: # ----------------------------------------------------------------- system.time
11692: 	if ($space eq 'time') {
11693: 	    return time;
11694:         }
11695:     } elsif ($realm eq 'server') {
11696: # ----------------------------------------------------------------- system.time
11697: 	if ($space eq 'name') {
11698: 	    return $ENV{'SERVER_NAME'};
11699:         }
11700:     }
11701:     return '';
11702: }
11703: 
11704: sub get_reply {
11705:     my ($reply_value) = @_;
11706:     if (ref($reply_value) eq 'ARRAY') {
11707:         if (wantarray) {
11708: 	    return @$reply_value;
11709:         }
11710:         return $reply_value->[0];
11711:     } else {
11712:         return $reply_value;
11713:     }
11714: }
11715: 
11716: sub check_group_parms {
11717:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
11718:     my @groupitems = ();
11719:     my $resultitem;
11720:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
11721:     foreach my $group (@{$groups}) {
11722:         foreach my $level (@levels) {
11723:              my $item = $courseid.'.['.$group.'].'.$level->[0];
11724:              push(@groupitems,[$item,$level->[1]]);
11725:         }
11726:     }
11727:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
11728:                             $env{'course.'.$courseid.'.domain'},
11729:                                      'course',@groupitems);
11730:     return $coursereply;
11731: }
11732: 
11733: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
11734:     my ($courseid,@groups) = @_;
11735:     @groups = sort(@groups);
11736:     return @groups;
11737: }
11738: 
11739: sub packages_tab_default {
11740:     my ($uri,$varname)=@_;
11741:     my (undef,$part,$name)=split(/\./,$varname);
11742: 
11743:     my (@extension,@specifics,$do_default);
11744:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
11745: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
11746: 	if ($pack_type eq 'default') {
11747: 	    $do_default=1;
11748: 	} elsif ($pack_type eq 'extension') {
11749: 	    push(@extension,[$package,$pack_type,$pack_part]);
11750: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
11751: 	    # only look at packages defaults for packages that this id is
11752: 	    push(@specifics,[$package,$pack_type,$pack_part]);
11753: 	}
11754:     }
11755:     # first look for a package that matches the requested part id
11756:     foreach my $package (@specifics) {
11757: 	my (undef,$pack_type,$pack_part)=@{$package};
11758: 	next if ($pack_part ne $part);
11759: 	if (defined($packagetab{"$pack_type&$name&default"})) {
11760: 	    return $packagetab{"$pack_type&$name&default"};
11761: 	}
11762:     }
11763:     # look for any possible matching non extension_ package
11764:     foreach my $package (@specifics) {
11765: 	my (undef,$pack_type,$pack_part)=@{$package};
11766: 	if (defined($packagetab{"$pack_type&$name&default"})) {
11767: 	    return $packagetab{"$pack_type&$name&default"};
11768: 	}
11769: 	if ($pack_type eq 'part') { $pack_part='0'; }
11770: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
11771: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
11772: 	}
11773:     }
11774:     # look for any posible extension_ match
11775:     foreach my $package (@extension) {
11776: 	my ($package,$pack_type)=@{$package};
11777: 	if (defined($packagetab{"$pack_type&$name&default"})) {
11778: 	    return $packagetab{"$pack_type&$name&default"};
11779: 	}
11780: 	if (defined($packagetab{$package."&$name&default"})) {
11781: 	    return $packagetab{$package."&$name&default"};
11782: 	}
11783:     }
11784:     # look for a global default setting
11785:     if ($do_default && defined($packagetab{"default&$name&default"})) {
11786: 	return $packagetab{"default&$name&default"};
11787:     }
11788:     return undef;
11789: }
11790: 
11791: sub add_prefix_and_part {
11792:     my ($prefix,$part)=@_;
11793:     my $keyroot;
11794:     if (defined($prefix) && $prefix !~ /^__/) {
11795: 	# prefix that has a part already
11796: 	$keyroot=$prefix;
11797:     } elsif (defined($prefix)) {
11798: 	# prefix that is missing a part
11799: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
11800:     } else {
11801: 	# no prefix at all
11802: 	if (defined($part)) { $keyroot='_'.$part; }
11803:     }
11804:     return $keyroot;
11805: }
11806: 
11807: # ---------------------------------------------------------------- Get metadata
11808: 
11809: my %metaentry;
11810: my %importedpartids;
11811: my %importedrespids;
11812: sub metadata {
11813:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
11814:     $uri=&declutter($uri);
11815:     # if it is a non metadata possible uri return quickly
11816:     if (($uri eq '') || 
11817: 	(($uri =~ m|^/*adm/|) && 
11818: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
11819:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
11820: 	return undef;
11821:     }
11822:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
11823: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
11824: 	return undef;
11825:     }
11826:     my $filename=$uri;
11827:     $uri=~s/\.meta$//;
11828: #
11829: # Is the metadata already cached?
11830: # Look at timestamp of caching
11831: # Everything is cached by the main uri, libraries are never directly cached
11832: #
11833:     if (!defined($liburi)) {
11834: 	my ($result,$cached)=&is_cached_new('meta',$uri);
11835: 	if (defined($cached)) { return $result->{':'.$what}; }
11836:     }
11837:     {
11838: # Imported parts would go here
11839:         my @origfiletagids=();
11840:         my $importedparts=0;
11841: 
11842: # Imported responseids would go here
11843:         my $importedresponses=0;
11844: #
11845: # Is this a recursive call for a library?
11846: #
11847: #	if (! exists($metacache{$uri})) {
11848: #	    $metacache{$uri}={};
11849: #	}
11850: 	my $cachetime = 60*60;
11851:         if ($liburi) {
11852: 	    $liburi=&declutter($liburi);
11853:             $filename=$liburi;
11854:         } else {
11855: 	    &devalidate_cache_new('meta',$uri);
11856: 	    undef(%metaentry);
11857: 	}
11858:         my %metathesekeys=();
11859:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
11860: 	my $metastring;
11861: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
11862: 	    my $which = &hreflocation('','/'.($liburi || $uri));
11863: 	    $metastring = 
11864: 		&Apache::lonnet::ssi_body($which,
11865: 					  ('grade_target' => 'meta'));
11866: 	    $cachetime = 1; # only want this cached in the child not long term
11867: 	} elsif (($uri !~ m -^(editupload)/-) && 
11868:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
11869: 	    my $file=&filelocation('',&clutter($filename));
11870: 	    #push(@{$metaentry{$uri.'.file'}},$file);
11871: 	    $metastring=&getfile($file);
11872: 	}
11873:         my $parser=HTML::LCParser->new(\$metastring);
11874:         my $token;
11875:         undef %metathesekeys;
11876:         while ($token=$parser->get_token) {
11877: 	    if ($token->[0] eq 'S') {
11878: 		if (defined($token->[2]->{'package'})) {
11879: #
11880: # This is a package - get package info
11881: #
11882: 		    my $package=$token->[2]->{'package'};
11883: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11884: 		    if (defined($token->[2]->{'id'})) { 
11885: 			$keyroot.='_'.$token->[2]->{'id'}; 
11886: 		    }
11887: 		    if ($metaentry{':packages'}) {
11888: 			$metaentry{':packages'}.=','.$package.$keyroot;
11889: 		    } else {
11890: 			$metaentry{':packages'}=$package.$keyroot;
11891: 		    }
11892: 		    foreach my $pack_entry (keys(%packagetab)) {
11893: 			my $part=$keyroot;
11894: 			$part=~s/^\_//;
11895: 			if ($pack_entry=~/^\Q$package\E\&/ || 
11896: 			    $pack_entry=~/^\Q$package\E_0\&/) {
11897: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
11898: 			    # ignore package.tab specified default values
11899:                             # here &package_tab_default() will fetch those
11900: 			    if ($subp eq 'default') { next; }
11901: 			    my $value=$packagetab{$pack_entry};
11902: 			    my $unikey;
11903: 			    if ($pack =~ /_0$/) {
11904: 				$unikey='parameter_0_'.$name;
11905: 				$part=0;
11906: 			    } else {
11907: 				$unikey='parameter'.$keyroot.'_'.$name;
11908: 			    }
11909: 			    if ($subp eq 'display') {
11910: 				$value.=' [Part: '.$part.']';
11911: 			    }
11912: 			    $metaentry{':'.$unikey.'.part'}=$part;
11913: 			    $metathesekeys{$unikey}=1;
11914: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
11915: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
11916: 			    }
11917: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
11918: 				$metaentry{':'.$unikey}=
11919: 				    $metaentry{':'.$unikey.'.default'};
11920: 			    }
11921: 			}
11922: 		    }
11923: 		} else {
11924: #
11925: # This is not a package - some other kind of start tag
11926: #
11927: 		    my $entry=$token->[1];
11928: 		    my $unikey='';
11929: 
11930: 		    if ($entry eq 'import') {
11931: #
11932: # Importing a library here
11933: #
11934:                         my $location=$parser->get_text('/import');
11935:                         my $dir=$filename;
11936:                         $dir=~s|[^/]*$||;
11937:                         $location=&filelocation($dir,$location);
11938: 
11939:                         my $importid=$token->[2]->{'id'};
11940:                         my $importmode=$token->[2]->{'importmode'};
11941: #
11942: # Check metadata for imported file to
11943: # see if it contained response items
11944: #
11945:                         my %currmetaentry = %metaentry;
11946:                         my $libresponseorder = &metadata($location,'responseorder');
11947:                         my $origfile;
11948:                         if ($libresponseorder ne '') {
11949:                             if ($#origfiletagids<0) {
11950:                                 undef(%importedrespids);
11951:                                 undef(%importedpartids);
11952:                             }
11953:                             @{$importedrespids{$importid}} = split(/\s*,\s*/,$libresponseorder);
11954:                             if (@{$importedrespids{$importid}} > 0) {
11955:                                 $importedresponses = 1;
11956: # We need to get the original file and the imported file to get the response order correct
11957: # Load and inspect original file
11958:                                 if ($#origfiletagids<0) {
11959:                                     my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
11960:                                     $origfile=&getfile($origfilelocation);
11961:                                     @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11962:                                 }
11963:                             }
11964:                         }
11965: # Do not overwrite contents of %metaentry hash for resource itself with 
11966: # hash populated for imported library file
11967:                         %metaentry = %currmetaentry;
11968:                         undef(%currmetaentry);
11969:                         if ($importmode eq 'problem') {
11970: # Import as problem/response
11971:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11972:                         } elsif ($importmode eq 'part') {
11973: # Import as part(s)
11974:                            $importedparts=1;
11975: # We need to get the original file and the imported file to get the part order correct
11976: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
11977: # Load and inspect original file if we didn't do that already
11978:                            if ($#origfiletagids<0) {
11979:                                undef(%importedrespids);
11980:                                undef(%importedpartids);
11981:                                if ($origfile eq '') {
11982:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
11983:                                    $origfile=&getfile($origfilelocation);
11984:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11985:                                }
11986:                            }
11987: 
11988: # Load and inspect imported file
11989:                            my $impfile=&getfile($location);
11990:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11991:                            if ($#impfilepartids>=0) {
11992: # This problem had parts
11993:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
11994:                            } else {
11995: # Importing by turning a single problem into a problem part
11996: # It gets the import-tags ID as part-ID
11997:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
11998:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
11999:                            }
12000:                         } else {
12001: # Normal import
12002:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
12003:                            if (defined($token->[2]->{'id'})) {
12004:                               $unikey.='_'.$token->[2]->{'id'};
12005:                            }
12006:                         }
12007: 
12008: 			if ($depthcount<20) {
12009: 			    my $metadata = 
12010: 				&metadata($uri,'keys', $location,$unikey,
12011: 					  $depthcount+1);
12012: 			    foreach my $meta (split(',',$metadata)) {
12013: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
12014: 				$metathesekeys{$meta}=1;
12015: 			    }
12016: 			
12017:                         }
12018: 		    } else {
12019: #
12020: # Not importing, some other kind of non-package, non-library start tag
12021: # 
12022:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
12023:                         if (defined($token->[2]->{'id'})) {
12024:                             $unikey.='_'.$token->[2]->{'id'};
12025:                         }
12026: 			if (defined($token->[2]->{'name'})) { 
12027: 			    $unikey.='_'.$token->[2]->{'name'}; 
12028: 			}
12029: 			$metathesekeys{$unikey}=1;
12030: 			foreach my $param (@{$token->[3]}) {
12031: 			    $metaentry{':'.$unikey.'.'.$param} =
12032: 				$token->[2]->{$param};
12033: 			}
12034: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
12035: 			my $default=$metaentry{':'.$unikey.'.default'};
12036: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
12037: 		 # only ws inside the tag, and not in default, so use default
12038: 		 # as value
12039: 			    $metaentry{':'.$unikey}=$default;
12040: 			} elsif ( $internaltext =~ /\S/ ) {
12041: 		  # something interesting inside the tag
12042: 			    $metaentry{':'.$unikey}=$internaltext;
12043: 			} else {
12044: 		  # no interesting values, don't set a default
12045: 			}
12046: # end of not-a-package not-a-library import
12047: 		    }
12048: # end of not-a-package start tag
12049: 		}
12050: # the next is the end of "start tag"
12051: 	    }
12052: 	}
12053: 	my ($extension) = ($uri =~ /\.(\w+)$/);
12054: 	$extension = lc($extension);
12055: 	if ($extension eq 'htm') { $extension='html'; }
12056: 
12057: 	foreach my $key (keys(%packagetab)) {
12058: 	    #no specific packages #how's our extension
12059: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
12060: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
12061: 					 \%metathesekeys);
12062: 	}
12063: 
12064: 	if (!exists($metaentry{':packages'})
12065: 	    || $packagetab{"import_defaults&extension_$extension"}) {
12066: 	    foreach my $key (keys(%packagetab)) {
12067: 		#no specific packages well let's get default then
12068: 		if ($key!~/^default&/) { next; }
12069: 		&metadata_create_package_def($uri,$key,'default',
12070: 					     \%metathesekeys);
12071: 	    }
12072: 	}
12073: # are there custom rights to evaluate
12074: 	if ($metaentry{':copyright'} eq 'custom') {
12075: 
12076:     #
12077:     # Importing a rights file here
12078:     #
12079: 	    unless ($depthcount) {
12080: 		my $location=$metaentry{':customdistributionfile'};
12081: 		my $dir=$filename;
12082: 		$dir=~s|[^/]*$||;
12083: 		$location=&filelocation($dir,$location);
12084: 		my $rights_metadata =
12085: 		    &metadata($uri,'keys',$location,'_rights',
12086: 			      $depthcount+1);
12087: 		foreach my $rights (split(',',$rights_metadata)) {
12088: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
12089: 		    $metathesekeys{$rights}=1;
12090: 		}
12091: 	    }
12092: 	}
12093: 	# uniqifiy package listing
12094: 	my %seen;
12095: 	my @uniq_packages =
12096: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
12097: 	$metaentry{':packages'} = join(',',@uniq_packages);
12098: 
12099:         if (($importedresponses) || ($importedparts)) {
12100:             if ($importedparts) {
12101: # We had imported parts and need to rebuild partorder
12102:                 $metaentry{':partorder'}='';
12103:                 $metathesekeys{'partorder'}=1;
12104:             }
12105:             if ($importedresponses) {
12106: # We had imported responses and need to rebuild responseorder
12107:                 $metaentry{':responseorder'}='';
12108:                 $metathesekeys{'responseorder'}=1;
12109:             }
12110:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
12111:                 my $origid = $origfiletagids[$index+1];
12112:                 if ($origfiletagids[$index] eq 'part') {
12113: # Original part, part of the problem
12114:                     if ($importedparts) {
12115:                         $metaentry{':partorder'}.=','.$origid;
12116:                     }
12117:                 } elsif ($origfiletagids[$index] eq 'import') {
12118:                     if ($importedparts) {
12119: # We have imported parts at this position
12120:                         $metaentry{':partorder'}.=','.$importedpartids{$origid};
12121:                     }
12122:                     if ($importedresponses) {
12123: # We have imported responses at this position
12124:                         if (ref($importedrespids{$origid}) eq 'ARRAY') {
12125:                             $metaentry{':responseorder'}.=','.join(',',map { $origid.'_'.$_ } @{$importedrespids{$origid}});
12126:                         }
12127:                     }
12128:                 } else {
12129: # Original response item, part of the problem
12130:                     if ($importedresponses) {
12131:                         $metaentry{':responseorder'}.=','.$origid;
12132:                     }
12133:                 }
12134:             }
12135:             if ($importedparts) {
12136:                 $metaentry{':partorder'}=~s/^\,//;
12137:             }
12138:             if ($importedresponses) {
12139:                 $metaentry{':responseorder'}=~s/^\,//;
12140:             }
12141:         }
12142: 
12143: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
12144: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
12145: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
12146: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
12147: # this is the end of "was not already recently cached
12148:     }
12149:     return $metaentry{':'.$what};
12150: }
12151: 
12152: sub metadata_create_package_def {
12153:     my ($uri,$key,$package,$metathesekeys)=@_;
12154:     my ($pack,$name,$subp)=split(/\&/,$key);
12155:     if ($subp eq 'default') { next; }
12156:     
12157:     if (defined($metaentry{':packages'})) {
12158: 	$metaentry{':packages'}.=','.$package;
12159:     } else {
12160: 	$metaentry{':packages'}=$package;
12161:     }
12162:     my $value=$packagetab{$key};
12163:     my $unikey;
12164:     $unikey='parameter_0_'.$name;
12165:     $metaentry{':'.$unikey.'.part'}=0;
12166:     $$metathesekeys{$unikey}=1;
12167:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
12168: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
12169:     }
12170:     if (defined($metaentry{':'.$unikey.'.default'})) {
12171: 	$metaentry{':'.$unikey}=
12172: 	    $metaentry{':'.$unikey.'.default'};
12173:     }
12174: }
12175: 
12176: sub metadata_generate_part0 {
12177:     my ($metadata,$metacache,$uri) = @_;
12178:     my %allnames;
12179:     foreach my $metakey (keys(%$metadata)) {
12180: 	if ($metakey=~/^parameter\_(.*)/) {
12181: 	  my $part=$$metacache{':'.$metakey.'.part'};
12182: 	  my $name=$$metacache{':'.$metakey.'.name'};
12183: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
12184: 	    $allnames{$name}=$part;
12185: 	  }
12186: 	}
12187:     }
12188:     foreach my $name (keys(%allnames)) {
12189:       $$metadata{"parameter_0_$name"}=1;
12190:       my $key=":parameter_0_$name";
12191:       $$metacache{"$key.part"}='0';
12192:       $$metacache{"$key.name"}=$name;
12193:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
12194: 					   $allnames{$name}.'_'.$name.
12195: 					   '.type'};
12196:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
12197: 			     '.display'};
12198:       my $expr='[Part: '.$allnames{$name}.']';
12199:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
12200:       $$metacache{"$key.display"}=$olddis;
12201:     }
12202: }
12203: 
12204: # ------------------------------------------------------ Devalidate title cache
12205: 
12206: sub devalidate_title_cache {
12207:     my ($url)=@_;
12208:     if (!$env{'request.course.id'}) { return; }
12209:     my $symb=&symbread($url);
12210:     if (!$symb) { return; }
12211:     my $key=$env{'request.course.id'}."\0".$symb;
12212:     &devalidate_cache_new('title',$key);
12213: }
12214: 
12215: # ------------------------------------------------- Get the title of a course
12216: 
12217: sub current_course_title {
12218:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
12219: }
12220: # ------------------------------------------------- Get the title of a resource
12221: 
12222: sub gettitle {
12223:     my $urlsymb=shift;
12224:     my $symb=&symbread($urlsymb);
12225:     if ($symb) {
12226: 	my $key=$env{'request.course.id'}."\0".$symb;
12227: 	my ($result,$cached)=&is_cached_new('title',$key);
12228: 	if (defined($cached)) { 
12229: 	    return $result;
12230: 	}
12231: 	my ($map,$resid,$url)=&decode_symb($symb);
12232: 	my $title='';
12233: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
12234: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
12235: 	} else {
12236: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12237: 		    &GDBM_READER(),0640)) {
12238: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
12239: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
12240: 		untie(%bighash);
12241: 	    }
12242: 	}
12243: 	$title=~s/\&colon\;/\:/gs;
12244: 	if ($title) {
12245: # Remember both $symb and $title for dynamic metadata
12246:             $accesshash{$symb.'___crstitle'}=$title;
12247:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
12248: # Cache this title and then return it
12249: 	    return &do_cache_new('title',$key,$title,600);
12250: 	}
12251: 	$urlsymb=$url;
12252:     }
12253:     my $title=&metadata($urlsymb,'title');
12254:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
12255:     return $title;
12256: }
12257: 
12258: sub get_slot {
12259:     my ($which,$cnum,$cdom)=@_;
12260:     if (!$cnum || !$cdom) {
12261: 	(undef,my $courseid)=&whichuser();
12262: 	$cdom=$env{'course.'.$courseid.'.domain'};
12263: 	$cnum=$env{'course.'.$courseid.'.num'};
12264:     }
12265:     my $key=join("\0",'slots',$cdom,$cnum,$which);
12266:     my %slotinfo;
12267:     if (exists($remembered{$key})) {
12268: 	$slotinfo{$which} = $remembered{$key};
12269:     } else {
12270: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
12271: 	&Apache::lonhomework::showhash(%slotinfo);
12272: 	my ($tmp)=keys(%slotinfo);
12273: 	if ($tmp=~/^error:/) { return (); }
12274: 	$remembered{$key} = $slotinfo{$which};
12275:     }
12276:     if (ref($slotinfo{$which}) eq 'HASH') {
12277: 	return %{$slotinfo{$which}};
12278:     }
12279:     return $slotinfo{$which};
12280: }
12281: 
12282: sub get_reservable_slots {
12283:     my ($cnum,$cdom,$uname,$udom) = @_;
12284:     my $now = time;
12285:     my $reservable_info;
12286:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
12287:     if (exists($remembered{$key})) {
12288:         $reservable_info = $remembered{$key};
12289:     } else {
12290:         my %resv;
12291:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
12292:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
12293:         $reservable_info = \%resv;
12294:         $remembered{$key} = $reservable_info;
12295:     }
12296:     return $reservable_info;
12297: }
12298: 
12299: sub get_course_slots {
12300:     my ($cnum,$cdom) = @_;
12301:     my $hashid=$cnum.':'.$cdom;
12302:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
12303:     if (defined($cached)) {
12304:         if (ref($result) eq 'HASH') {
12305:             return %{$result};
12306:         }
12307:     } else {
12308:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
12309:         my ($tmp) = keys(%slots);
12310:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
12311:             &do_cache_new('allslots',$hashid,\%slots,600);
12312:             return %slots;
12313:         }
12314:     }
12315:     return;
12316: }
12317: 
12318: sub devalidate_slots_cache {
12319:     my ($cnum,$cdom)=@_;
12320:     my $hashid=$cnum.':'.$cdom;
12321:     &devalidate_cache_new('allslots',$hashid);
12322: }
12323: 
12324: sub get_coursechange {
12325:     my ($cdom,$cnum) = @_;
12326:     if ($cdom eq '' || $cnum eq '') {
12327:         return unless ($env{'request.course.id'});
12328:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
12329:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
12330:     }
12331:     my $hashid=$cdom.'_'.$cnum;
12332:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
12333:     if ((defined($cached)) && ($change ne '')) {
12334:         return $change;
12335:     } else {
12336:         my %crshash;
12337:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
12338:         if ($crshash{'internal.contentchange'} eq '') {
12339:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
12340:             if ($change eq '') {
12341:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
12342:                 $change = $crshash{'internal.created'};
12343:             }
12344:         } else {
12345:             $change = $crshash{'internal.contentchange'};
12346:         }
12347:         my $cachetime = 600;
12348:         &do_cache_new('crschange',$hashid,$change,$cachetime);
12349:     }
12350:     return $change;
12351: }
12352: 
12353: sub devalidate_coursechange_cache {
12354:     my ($cnum,$cdom)=@_;
12355:     my $hashid=$cnum.':'.$cdom;
12356:     &devalidate_cache_new('crschange',$hashid);
12357: }
12358: 
12359: # ------------------------------------------------- Update symbolic store links
12360: 
12361: sub symblist {
12362:     my ($mapname,%newhash)=@_;
12363:     $mapname=&deversion(&declutter($mapname));
12364:     my %hash;
12365:     if (($env{'request.course.fn'}) && (%newhash)) {
12366:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
12367:                       &GDBM_WRCREAT(),0640)) {
12368: 	    foreach my $url (keys(%newhash)) {
12369: 		next if ($url eq 'last_known'
12370: 			 && $env{'form.no_update_last_known'});
12371: 		$hash{declutter($url)}=&encode_symb($mapname,
12372: 						    $newhash{$url}->[1],
12373: 						    $newhash{$url}->[0]);
12374:             }
12375:             if (untie(%hash)) {
12376: 		return 'ok';
12377:             }
12378:         }
12379:     }
12380:     return 'error';
12381: }
12382: 
12383: # --------------------------------------------------------------- Verify a symb
12384: 
12385: sub symbverify {
12386:     my ($symb,$thisurl,$encstate)=@_;
12387:     my $thisfn=$thisurl;
12388:     $thisfn=&declutter($thisfn);
12389: # direct jump to resource in page or to a sequence - will construct own symbs
12390:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
12391: # check URL part
12392:     my ($map,$resid,$url)=&decode_symb($symb);
12393: 
12394:     unless ($url eq $thisfn) { return 0; }
12395: 
12396:     $symb=&symbclean($symb);
12397:     $thisurl=&deversion($thisurl);
12398:     $thisfn=&deversion($thisfn);
12399: 
12400:     my %bighash;
12401:     my $okay=0;
12402: 
12403:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12404:                             &GDBM_READER(),0640)) {
12405:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
12406:             $thisurl =~ s/\?.+$//;
12407:             if ($map =~ m{^uploaded/.+\.page$}) {
12408:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
12409:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
12410:             }
12411:         }
12412:         my $ids;
12413:         if ($map =~ m{^uploaded/.+\.page$}) {
12414:             $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
12415:         } else {
12416:             $ids=$bighash{'ids_'.&clutter($thisurl)};
12417:         }
12418:         unless ($ids) {
12419:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
12420:             $ids=$bighash{$idkey};
12421:         }
12422:         if ($ids) {
12423: # ------------------------------------------------------------------- Has ID(s)
12424:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
12425:                 $symb =~ s/\?.+$//;
12426:             }
12427: 	    foreach my $id (split(/\,/,$ids)) {
12428: 	       my ($mapid,$resid)=split(/\./,$id);
12429:                if (
12430:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
12431:    eq $symb) {
12432:                    if (ref($encstate)) {
12433:                        $$encstate = $bighash{'encrypted_'.$id};
12434:                    }
12435:                    if (($env{'request.role.adv'}) ||
12436:                        ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
12437:                        ($thisurl eq '/adm/navmaps')) {
12438:                        $okay=1;
12439:                        last;
12440:                    }
12441:                }
12442:            }
12443:         }
12444: 	untie(%bighash);
12445:     }
12446:     return $okay;
12447: }
12448: 
12449: # --------------------------------------------------------------- Clean-up symb
12450: 
12451: sub symbclean {
12452:     my $symb=shift;
12453:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
12454: # remove version from map
12455:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
12456: 
12457: # remove version from URL
12458:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
12459: 
12460: # remove wrapper
12461: 
12462:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
12463:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
12464:     return $symb;
12465: }
12466: 
12467: # ---------------------------------------------- Split symb to find map and url
12468: 
12469: sub encode_symb {
12470:     my ($map,$resid,$url)=@_;
12471:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
12472: }
12473: 
12474: sub decode_symb {
12475:     my $symb=shift;
12476:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
12477:     my ($map,$resid,$url)=split(/___/,$symb);
12478:     return (&fixversion($map),$resid,&fixversion($url));
12479: }
12480: 
12481: sub fixversion {
12482:     my $fn=shift;
12483:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
12484:     my %bighash;
12485:     my $uri=&clutter($fn);
12486:     my $key=$env{'request.course.id'}.'_'.$uri;
12487: # is this cached?
12488:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
12489:     if (defined($cached)) { return $result; }
12490: # unfortunately not cached, or expired
12491:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12492: 	    &GDBM_READER(),0640)) {
12493:  	if ($bighash{'version_'.$uri}) {
12494:  	    my $version=$bighash{'version_'.$uri};
12495:  	    unless (($version eq 'mostrecent') || 
12496: 		    ($version==&getversion($uri))) {
12497:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
12498:  	    }
12499:  	}
12500:  	untie %bighash;
12501:     }
12502:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
12503: }
12504: 
12505: sub deversion {
12506:     my $url=shift;
12507:     $url=~s/\.\d+\.(\w+)$/\.$1/;
12508:     return $url;
12509: }
12510: 
12511: # ------------------------------------------------------ Return symb list entry
12512: 
12513: sub symbread {
12514:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
12515:     my $cache_str='request.symbread.cached.'.$thisfn;
12516:     if (defined($env{$cache_str})) {
12517:         if ($ignorecachednull) {
12518:             return $env{$cache_str} unless ($env{$cache_str} eq '');
12519:         } else {
12520:             return $env{$cache_str};
12521:         }
12522:     }
12523: # no filename provided? try from environment
12524:     unless ($thisfn) {
12525:         if ($env{'request.symb'}) {
12526:             return $env{$cache_str}=&symbclean($env{'request.symb'});
12527:         }
12528:         $thisfn=$env{'request.filename'};
12529:     }
12530:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
12531: # is that filename actually a symb? Verify, clean, and return
12532:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
12533: 	if (&symbverify($thisfn,$1)) {
12534: 	    return $env{$cache_str}=&symbclean($thisfn);
12535: 	}
12536:     }
12537:     $thisfn=declutter($thisfn);
12538:     my %hash;
12539:     my %bighash;
12540:     my $syval='';
12541:     if (($env{'request.course.fn'}) && ($thisfn)) {
12542:         my $targetfn = $thisfn;
12543:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
12544:             $targetfn = 'adm/wrapper/'.$thisfn;
12545:         }
12546: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
12547: 	    $targetfn=$1;
12548: 	}
12549:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
12550:                       &GDBM_READER(),0640)) {
12551: 	    $syval=$hash{$targetfn};
12552:             untie(%hash);
12553:         }
12554: # ---------------------------------------------------------- There was an entry
12555:         if ($syval) {
12556: 	    #unless ($syval=~/\_\d+$/) {
12557: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
12558: 		    #&appenv({'request.ambiguous' => $thisfn});
12559: 		    #return $env{$cache_str}='';
12560: 		#}    
12561: 		#$syval.=$1;
12562: 	    #}
12563:         } else {
12564: # ------------------------------------------------------- Was not in symb table
12565:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12566:                             &GDBM_READER(),0640)) {
12567: # ---------------------------------------------- Get ID(s) for current resource
12568:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
12569:               unless ($ids) { 
12570:                  $ids=$bighash{'ids_/'.$thisfn};
12571:               }
12572:               unless ($ids) {
12573: # alias?
12574: 		  $ids=$bighash{'mapalias_'.$thisfn};
12575:               }
12576:               if ($ids) {
12577: # ------------------------------------------------------------------- Has ID(s)
12578:                  my @possibilities=split(/\,/,$ids);
12579:                  if ($#possibilities==0) {
12580: # ----------------------------------------------- There is only one possibility
12581: 		     my ($mapid,$resid)=split(/\./,$ids);
12582: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
12583: 						    $resid,$thisfn);
12584:                      if (ref($possibles) eq 'HASH') {
12585:                          $possibles->{$syval} = 1;
12586:                      }
12587:                      if ($checkforblock) {
12588:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
12589:                          if (@blockers) {
12590:                              $syval = '';
12591:                              return;
12592:                          }
12593:                      }
12594:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
12595: # ------------------------------------------ There is more than one possibility
12596:                      my $realpossible=0;
12597:                      foreach my $id (@possibilities) {
12598: 			 my $file=$bighash{'src_'.$id};
12599:                          my $canaccess;
12600:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
12601:                              $canaccess = 1;
12602:                          } else {
12603:                              $canaccess = &allowed('bre',$file);
12604:                          }
12605:                          if ($canaccess) {
12606:          		     my ($mapid,$resid)=split(/\./,$id);
12607:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
12608:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
12609:                                                              $resid,$thisfn);
12610:                                  if (ref($possibles) eq 'HASH') {
12611:                                      $possibles->{$syval} = 1;
12612:                                  }
12613:                                  if ($checkforblock) {
12614:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
12615:                                      unless (@blockers > 0) {
12616:                                          $syval = $poss_syval;
12617:                                          $realpossible++;
12618:                                      }
12619:                                  } else {
12620:                                      $syval = $poss_syval;
12621:                                      $realpossible++;
12622:                                  }
12623:                              }
12624: 			 }
12625:                      }
12626: 		     if ($realpossible!=1) { $syval=''; }
12627:                  } else {
12628:                      $syval='';
12629:                  }
12630: 	      }
12631:               untie(%bighash);
12632:            }
12633:         }
12634:         if ($syval) {
12635: 	    return $env{$cache_str}=$syval;
12636:         }
12637:     }
12638:     &appenv({'request.ambiguous' => $thisfn});
12639:     return $env{$cache_str}='';
12640: }
12641: 
12642: # ---------------------------------------------------------- Return random seed
12643: 
12644: sub numval {
12645:     my $txt=shift;
12646:     $txt=~tr/A-J/0-9/;
12647:     $txt=~tr/a-j/0-9/;
12648:     $txt=~tr/K-T/0-9/;
12649:     $txt=~tr/k-t/0-9/;
12650:     $txt=~tr/U-Z/0-5/;
12651:     $txt=~tr/u-z/0-5/;
12652:     $txt=~s/\D//g;
12653:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
12654:     return int($txt);
12655: }
12656: 
12657: sub numval2 {
12658:     my $txt=shift;
12659:     $txt=~tr/A-J/0-9/;
12660:     $txt=~tr/a-j/0-9/;
12661:     $txt=~tr/K-T/0-9/;
12662:     $txt=~tr/k-t/0-9/;
12663:     $txt=~tr/U-Z/0-5/;
12664:     $txt=~tr/u-z/0-5/;
12665:     $txt=~s/\D//g;
12666:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12667:     my $total;
12668:     foreach my $val (@txts) { $total+=$val; }
12669:     if ($_64bit) { if ($total > 2**32) { return -1; } }
12670:     return int($total);
12671: }
12672: 
12673: sub numval3 {
12674:     use integer;
12675:     my $txt=shift;
12676:     $txt=~tr/A-J/0-9/;
12677:     $txt=~tr/a-j/0-9/;
12678:     $txt=~tr/K-T/0-9/;
12679:     $txt=~tr/k-t/0-9/;
12680:     $txt=~tr/U-Z/0-5/;
12681:     $txt=~tr/u-z/0-5/;
12682:     $txt=~s/\D//g;
12683:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12684:     my $total;
12685:     foreach my $val (@txts) { $total+=$val; }
12686:     if ($_64bit) { $total=(($total<<32)>>32); }
12687:     return $total;
12688: }
12689: 
12690: sub digest {
12691:     my ($data)=@_;
12692:     my $digest=&Digest::MD5::md5($data);
12693:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
12694:     my ($e,$f);
12695:     {
12696:         use integer;
12697:         $e=($a+$b);
12698:         $f=($c+$d);
12699:         if ($_64bit) {
12700:             $e=(($e<<32)>>32);
12701:             $f=(($f<<32)>>32);
12702:         }
12703:     }
12704:     if (wantarray) {
12705: 	return ($e,$f);
12706:     } else {
12707: 	my $g;
12708: 	{
12709: 	    use integer;
12710: 	    $g=($e+$f);
12711: 	    if ($_64bit) {
12712: 		$g=(($g<<32)>>32);
12713: 	    }
12714: 	}
12715: 	return $g;
12716:     }
12717: }
12718: 
12719: sub latest_rnd_algorithm_id {
12720:     return '64bit5';
12721: }
12722: 
12723: sub get_rand_alg {
12724:     my ($courseid)=@_;
12725:     if (!$courseid) { $courseid=(&whichuser())[1]; }
12726:     if ($courseid) {
12727: 	return $env{"course.$courseid.rndseed"};
12728:     }
12729:     return &latest_rnd_algorithm_id();
12730: }
12731: 
12732: sub validCODE {
12733:     my ($CODE)=@_;
12734:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
12735:     return 0;
12736: }
12737: 
12738: sub getCODE {
12739:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
12740:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
12741: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
12742: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
12743: 	return $Apache::lonhomework::history{'resource.CODE'};
12744:     }
12745:     return undef;
12746: }
12747: #
12748: #  Determines the random seed for a specific context:
12749: #
12750: # parameters:
12751: #   symb      - in course context the symb for the seed.
12752: #   course_id - The course id of the form domain_coursenum.
12753: #   domain    - Domain for the user.
12754: #   course    - Course for the user.
12755: #   cenv      - environment of the course.
12756: #
12757: # NOTE:
12758: #   All parameters are picked out of the environment if missing
12759: #   or not defined.
12760: #   If a symb cannot be determined the current time is used instead.
12761: #
12762: #  For a given well defined symb, courside, domain, username,
12763: #  and course environment, the seed is reproducible.
12764: #
12765: sub rndseed {
12766:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
12767:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
12768:     if (!defined($symb)) {
12769: 	unless ($symb=$wsymb) { return time; }
12770:     }
12771:     if (!defined $courseid) { 
12772: 	$courseid=$wcourseid; 
12773:     }
12774:     if (!defined $domain) { $domain=$wdomain; }
12775:     if (!defined $username) { $username=$wusername }
12776: 
12777:     my $which;
12778:     if (defined($cenv->{'rndseed'})) {
12779: 	$which = $cenv->{'rndseed'};
12780:     } else {
12781: 	$which =&get_rand_alg($courseid);
12782:     }
12783:     if (defined(&getCODE())) {
12784: 	if ($which eq '64bit5') {
12785: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
12786: 	} elsif ($which eq '64bit4') {
12787: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
12788: 	} else {
12789: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
12790: 	}
12791:     } elsif ($which eq '64bit5') {
12792: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
12793:     } elsif ($which eq '64bit4') {
12794: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
12795:     } elsif ($which eq '64bit3') {
12796: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
12797:     } elsif ($which eq '64bit2') {
12798: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
12799:     } elsif ($which eq '64bit') {
12800: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
12801:     }
12802:     return &rndseed_32bit($symb,$courseid,$domain,$username);
12803: }
12804: 
12805: sub rndseed_32bit {
12806:     my ($symb,$courseid,$domain,$username)=@_;
12807:     {
12808: 	use integer;
12809: 	my $symbchck=unpack("%32C*",$symb) << 27;
12810: 	my $symbseed=numval($symb) << 22;
12811: 	my $namechck=unpack("%32C*",$username) << 17;
12812: 	my $nameseed=numval($username) << 12;
12813: 	my $domainseed=unpack("%32C*",$domain) << 7;
12814: 	my $courseseed=unpack("%32C*",$courseid);
12815: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
12816: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12817: 	#&logthis("rndseed :$num:$symb");
12818: 	if ($_64bit) { $num=(($num<<32)>>32); }
12819: 	return $num;
12820:     }
12821: }
12822: 
12823: sub rndseed_64bit {
12824:     my ($symb,$courseid,$domain,$username)=@_;
12825:     {
12826: 	use integer;
12827: 	my $symbchck=unpack("%32S*",$symb) << 21;
12828: 	my $symbseed=numval($symb) << 10;
12829: 	my $namechck=unpack("%32S*",$username);
12830: 	
12831: 	my $nameseed=numval($username) << 21;
12832: 	my $domainseed=unpack("%32S*",$domain) << 10;
12833: 	my $courseseed=unpack("%32S*",$courseid);
12834: 	
12835: 	my $num1=$symbchck+$symbseed+$namechck;
12836: 	my $num2=$nameseed+$domainseed+$courseseed;
12837: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12838: 	#&logthis("rndseed :$num:$symb");
12839: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
12840: 	return "$num1,$num2";
12841:     }
12842: }
12843: 
12844: sub rndseed_64bit2 {
12845:     my ($symb,$courseid,$domain,$username)=@_;
12846:     {
12847: 	use integer;
12848: 	# strings need to be an even # of cahracters long, it it is odd the
12849:         # last characters gets thrown away
12850: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
12851: 	my $symbseed=numval($symb) << 10;
12852: 	my $namechck=unpack("%32S*",$username.' ');
12853: 	
12854: 	my $nameseed=numval($username) << 21;
12855: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
12856: 	my $courseseed=unpack("%32S*",$courseid.' ');
12857: 	
12858: 	my $num1=$symbchck+$symbseed+$namechck;
12859: 	my $num2=$nameseed+$domainseed+$courseseed;
12860: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12861: 	#&logthis("rndseed :$num:$symb");
12862: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
12863: 	return "$num1,$num2";
12864:     }
12865: }
12866: 
12867: sub rndseed_64bit3 {
12868:     my ($symb,$courseid,$domain,$username)=@_;
12869:     {
12870: 	use integer;
12871: 	# strings need to be an even # of cahracters long, it it is odd the
12872:         # last characters gets thrown away
12873: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
12874: 	my $symbseed=numval2($symb) << 10;
12875: 	my $namechck=unpack("%32S*",$username.' ');
12876: 	
12877: 	my $nameseed=numval2($username) << 21;
12878: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
12879: 	my $courseseed=unpack("%32S*",$courseid.' ');
12880: 	
12881: 	my $num1=$symbchck+$symbseed+$namechck;
12882: 	my $num2=$nameseed+$domainseed+$courseseed;
12883: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12884: 	#&logthis("rndseed :$num1:$num2:$_64bit");
12885: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
12886: 	
12887: 	return "$num1:$num2";
12888:     }
12889: }
12890: 
12891: sub rndseed_64bit4 {
12892:     my ($symb,$courseid,$domain,$username)=@_;
12893:     {
12894: 	use integer;
12895: 	# strings need to be an even # of cahracters long, it it is odd the
12896:         # last characters gets thrown away
12897: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
12898: 	my $symbseed=numval3($symb) << 10;
12899: 	my $namechck=unpack("%32S*",$username.' ');
12900: 	
12901: 	my $nameseed=numval3($username) << 21;
12902: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
12903: 	my $courseseed=unpack("%32S*",$courseid.' ');
12904: 	
12905: 	my $num1=$symbchck+$symbseed+$namechck;
12906: 	my $num2=$nameseed+$domainseed+$courseseed;
12907: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12908: 	#&logthis("rndseed :$num1:$num2:$_64bit");
12909: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
12910: 	
12911: 	return "$num1:$num2";
12912:     }
12913: }
12914: 
12915: sub rndseed_64bit5 {
12916:     my ($symb,$courseid,$domain,$username)=@_;
12917:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
12918:     return "$num1:$num2";
12919: }
12920: 
12921: sub rndseed_CODE_64bit {
12922:     my ($symb,$courseid,$domain,$username)=@_;
12923:     {
12924: 	use integer;
12925: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
12926: 	my $symbseed=numval2($symb);
12927: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
12928: 	my $CODEseed=numval(&getCODE());
12929: 	my $courseseed=unpack("%32S*",$courseid.' ');
12930: 	my $num1=$symbseed+$CODEchck;
12931: 	my $num2=$CODEseed+$courseseed+$symbchck;
12932: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
12933: 	#&logthis("rndseed :$num1:$num2:$symb");
12934: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
12935: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
12936: 	return "$num1:$num2";
12937:     }
12938: }
12939: 
12940: sub rndseed_CODE_64bit4 {
12941:     my ($symb,$courseid,$domain,$username)=@_;
12942:     {
12943: 	use integer;
12944: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
12945: 	my $symbseed=numval3($symb);
12946: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
12947: 	my $CODEseed=numval3(&getCODE());
12948: 	my $courseseed=unpack("%32S*",$courseid.' ');
12949: 	my $num1=$symbseed+$CODEchck;
12950: 	my $num2=$CODEseed+$courseseed+$symbchck;
12951: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
12952: 	#&logthis("rndseed :$num1:$num2:$symb");
12953: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
12954: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
12955: 	return "$num1:$num2";
12956:     }
12957: }
12958: 
12959: sub rndseed_CODE_64bit5 {
12960:     my ($symb,$courseid,$domain,$username)=@_;
12961:     my $code = &getCODE();
12962:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
12963:     return "$num1:$num2";
12964: }
12965: 
12966: sub setup_random_from_rndseed {
12967:     my ($rndseed)=@_;
12968:     if ($rndseed =~/([,:])/) {
12969: 	my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
12970:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
12971:             &Math::Random::random_set_seed_from_phrase($rndseed);
12972:         } else {
12973:             &Math::Random::random_set_seed($num1,$num2);
12974:         }
12975:     } else {
12976: 	&Math::Random::random_set_seed_from_phrase($rndseed);
12977:     }
12978: }
12979: 
12980: sub latest_receipt_algorithm_id {
12981:     return 'receipt3';
12982: }
12983: 
12984: sub recunique {
12985:     my $fucourseid=shift;
12986:     my $unique;
12987:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
12988: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
12989: 	$unique=$env{"course.$fucourseid.internal.encseed"};
12990:     } else {
12991: 	$unique=$perlvar{'lonReceipt'};
12992:     }
12993:     return unpack("%32C*",$unique);
12994: }
12995: 
12996: sub recprefix {
12997:     my $fucourseid=shift;
12998:     my $prefix;
12999:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
13000: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
13001: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
13002:     } else {
13003: 	$prefix=$perlvar{'lonHostID'};
13004:     }
13005:     return unpack("%32C*",$prefix);
13006: }
13007: 
13008: sub ireceipt {
13009:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
13010: 
13011:     my $return =&recprefix($fucourseid).'-';
13012: 
13013:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
13014: 	$env{'request.state'} eq 'construct') {
13015: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
13016: 	return $return;
13017:     }
13018: 
13019:     my $cuname=unpack("%32C*",$funame);
13020:     my $cudom=unpack("%32C*",$fudom);
13021:     my $cucourseid=unpack("%32C*",$fucourseid);
13022:     my $cusymb=unpack("%32C*",$fusymb);
13023:     my $cunique=&recunique($fucourseid);
13024:     my $cpart=unpack("%32S*",$part);
13025:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
13026: 
13027: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
13028: 			       
13029: 	$return.= ($cunique%$cuname+
13030: 		   $cunique%$cudom+
13031: 		   $cusymb%$cuname+
13032: 		   $cusymb%$cudom+
13033: 		   $cucourseid%$cuname+
13034: 		   $cucourseid%$cudom+
13035: 		   $cpart%$cuname+
13036: 		   $cpart%$cudom);
13037:     } else {
13038: 	$return.= ($cunique%$cuname+
13039: 		   $cunique%$cudom+
13040: 		   $cusymb%$cuname+
13041: 		   $cusymb%$cudom+
13042: 		   $cucourseid%$cuname+
13043: 		   $cucourseid%$cudom);
13044:     }
13045:     return $return;
13046: }
13047: 
13048: sub receipt {
13049:     my ($part)=@_;
13050:     my ($symb,$courseid,$domain,$name) = &whichuser();
13051:     return &ireceipt($name,$domain,$courseid,$symb,$part);
13052: }
13053: 
13054: sub whichuser {
13055:     my ($passedsymb)=@_;
13056:     my ($symb,$courseid,$domain,$name,$publicuser);
13057:     if (defined($env{'form.grade_symb'})) {
13058: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
13059: 	my $allowed=&allowed('vgr',$tmp_courseid);
13060: 	if (!$allowed &&
13061: 	    exists($env{'request.course.sec'}) &&
13062: 	    $env{'request.course.sec'} !~ /^\s*$/) {
13063: 	    $allowed=&allowed('vgr',$tmp_courseid.
13064: 			      '/'.$env{'request.course.sec'});
13065: 	}
13066: 	if ($allowed) {
13067: 	    ($symb)=&get_env_multiple('form.grade_symb');
13068: 	    $courseid=$tmp_courseid;
13069: 	    ($domain)=&get_env_multiple('form.grade_domain');
13070: 	    ($name)=&get_env_multiple('form.grade_username');
13071: 	    return ($symb,$courseid,$domain,$name,$publicuser);
13072: 	}
13073:     }
13074:     if (!$passedsymb) {
13075: 	$symb=&symbread();
13076:     } else {
13077: 	$symb=$passedsymb;
13078:     }
13079:     $courseid=$env{'request.course.id'};
13080:     $domain=$env{'user.domain'};
13081:     $name=$env{'user.name'};
13082:     if ($name eq 'public' && $domain eq 'public') {
13083: 	if (!defined($env{'form.username'})) {
13084: 	    $env{'form.username'}.=time.rand(10000000);
13085: 	}
13086: 	$name.=$env{'form.username'};
13087:     }
13088:     return ($symb,$courseid,$domain,$name,$publicuser);
13089: 
13090: }
13091: 
13092: # ------------------------------------------------------------ Serves up a file
13093: # returns either the contents of the file or 
13094: # -1 if the file doesn't exist
13095: #
13096: # if the target is a file that was uploaded via DOCS, 
13097: # a check will be made to see if a current copy exists on the local server,
13098: # if it does this will be served, otherwise a copy will be retrieved from
13099: # the home server for the course and stored in /home/httpd/html/userfiles on
13100: # the local server.   
13101: 
13102: sub getfile {
13103:     my ($file) = @_;
13104:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
13105:     &repcopy($file);
13106:     return &readfile($file);
13107: }
13108: 
13109: sub repcopy_userfile {
13110:     my ($file)=@_;
13111:     my $londocroot = $perlvar{'lonDocRoot'};
13112:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
13113:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
13114:     my ($cdom,$cnum,$filename) = 
13115: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
13116:     my $uri="/uploaded/$cdom/$cnum/$filename";
13117:     if (-e "$file") {
13118: # we already have a local copy, check it out
13119: 	my @fileinfo = stat($file);
13120: 	my $rtncode;
13121: 	my $info;
13122: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
13123: 	if ($lwpresp ne 'ok') {
13124: # there is no such file anymore, even though we had a local copy
13125: 	    if ($rtncode eq '404') {
13126: 		unlink($file);
13127: 	    }
13128: 	    return -1;
13129: 	}
13130: 	if ($info < $fileinfo[9]) {
13131: # nice, the file we have is up-to-date, just say okay
13132: 	    return 'ok';
13133: 	} else {
13134: # the file is outdated, get rid of it
13135: 	    unlink($file);
13136: 	}
13137:     }
13138: # one way or the other, at this point, we don't have the file
13139: # construct the correct path for the file
13140:     my @parts = ($cdom,$cnum); 
13141:     if ($filename =~ m|^(.+)/[^/]+$|) {
13142: 	push @parts, split(/\//,$1);
13143:     }
13144:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
13145:     foreach my $part (@parts) {
13146: 	$path .= '/'.$part;
13147: 	if (!-e $path) {
13148: 	    mkdir($path,0770);
13149: 	}
13150:     }
13151: # now the path exists for sure
13152: # get a user agent
13153:     my $ua=new LWP::UserAgent;
13154:     my $transferfile=$file.'.in.transfer';
13155: # FIXME: this should flock
13156:     if (-e $transferfile) { return 'ok'; }
13157:     my $request;
13158:     $uri=~s/^\///;
13159:     my $homeserver = &homeserver($cnum,$cdom);
13160:     my $hostname = &hostname($homeserver);
13161:     my $protocol = $protocol{$homeserver};
13162:     $protocol = 'http' if ($protocol ne 'https');
13163:     $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
13164:     my $response=$ua->request($request,$transferfile);
13165: # did it work?
13166:     if ($response->is_error()) {
13167: 	unlink($transferfile);
13168: 	&logthis("Userfile repcopy failed for $uri");
13169: 	return -1;
13170:     }
13171: # worked, rename the transfer file
13172:     rename($transferfile,$file);
13173:     return 'ok';
13174: }
13175: 
13176: sub tokenwrapper {
13177:     my $uri=shift;
13178:     $uri=~s|^https?\://([^/]+)||;
13179:     $uri=~s|^/||;
13180:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
13181:     my $token=$1;
13182:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
13183:     if ($udom && $uname && $file) {
13184: 	$file=~s|(\?\.*)*$||;
13185:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
13186:         my $homeserver = &homeserver($uname,$udom);
13187:         my $hostname = &hostname($homeserver);
13188:         my $protocol = $protocol{$homeserver};
13189:         $protocol = 'http' if ($protocol ne 'https');
13190:         return $protocol.'://'.$hostname.'/'.$uri.
13191:                (($uri=~/\?/)?'&':'?').'token='.$token.
13192:                                '&tokenissued='.$perlvar{'lonHostID'};
13193:     } else {
13194:         return '/adm/notfound.html';
13195:     }
13196: }
13197: 
13198: # call with reqtype HEAD: get last modification time
13199: # call with reqtype GET: get the file contents
13200: # Do not call this with reqtype GET for large files! It loads everything into memory
13201: #
13202: sub getuploaded {
13203:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
13204:     $uri=~s/^\///;
13205:     my $homeserver = &homeserver($cnum,$cdom);
13206:     my $hostname = &hostname($homeserver);
13207:     my $protocol = $protocol{$homeserver};
13208:     $protocol = 'http' if ($protocol ne 'https');
13209:     $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
13210:     my $ua=new LWP::UserAgent;
13211:     my $request=new HTTP::Request($reqtype,$uri);
13212:     my $response=$ua->request($request);
13213:     $$rtncode = $response->code;
13214:     if (! $response->is_success()) {
13215: 	return 'failed';
13216:     }      
13217:     if ($reqtype eq 'HEAD') {
13218: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
13219:     } elsif ($reqtype eq 'GET') {
13220: 	$$info = $response->content;
13221:     }
13222:     return 'ok';
13223: }
13224: 
13225: sub readfile {
13226:     my $file = shift;
13227:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
13228:     my $fh;
13229:     open($fh,"<",$file);
13230:     my $a='';
13231:     while (my $line = <$fh>) { $a .= $line; }
13232:     return $a;
13233: }
13234: 
13235: sub filelocation {
13236:     my ($dir,$file) = @_;
13237:     my $location;
13238:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
13239: 
13240:     if ($file =~ m-^/adm/-) {
13241: 	$file=~s-^/adm/wrapper/-/-;
13242: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
13243:     }
13244: 
13245:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
13246:         $location = $file;
13247:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
13248:         my ($udom,$uname,$filename)=
13249:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
13250:         my $home=&homeserver($uname,$udom);
13251:         my $is_me=0;
13252:         my @ids=&current_machine_ids();
13253:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
13254:         if ($is_me) {
13255:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
13256:         } else {
13257:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
13258:   	      $udom.'/'.$uname.'/'.$filename;
13259:         }
13260:     } elsif ($file =~ m-^/adm/-) {
13261: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
13262:     } else {
13263:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
13264:         $file=~s:^/(res|priv)/:/:;
13265:         my $space=$1;
13266:         if ( !( $file =~ m:^/:) ) {
13267:             $location = $dir. '/'.$file;
13268:         } else {
13269:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
13270:         }
13271:     }
13272:     $location=~s://+:/:g; # remove duplicate /
13273:     while ($location=~m{/\.\./}) {
13274: 	if ($location =~ m{/[^/]+/\.\./}) {
13275: 	    $location=~ s{/[^/]+/\.\./}{/}g;
13276: 	} else {
13277: 	    $location=~ s{/\.\./}{/}g;
13278: 	}
13279:     } #remove dir/..
13280:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
13281:     return $location;
13282: }
13283: 
13284: sub hreflocation {
13285:     my ($dir,$file)=@_;
13286:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
13287: 	$file=filelocation($dir,$file);
13288:     } elsif ($file=~m-^/adm/-) {
13289: 	$file=~s-^/adm/wrapper/-/-;
13290: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
13291:     }
13292:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
13293: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
13294:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
13295: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
13296: 	        {/uploaded/$1/$2/}x;
13297:     }
13298:     if ($file=~ m{^/userfiles/}) {
13299: 	$file =~ s{^/userfiles/}{/uploaded/};
13300:     }
13301:     return $file;
13302: }
13303: 
13304: 
13305: 
13306: 
13307: 
13308: sub current_machine_domains {
13309:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
13310: }
13311: 
13312: sub machine_domains {
13313:     my ($hostname) = @_;
13314:     my @domains;
13315:     my %hostname = &all_hostnames();
13316:     while( my($id, $name) = each(%hostname)) {
13317: #	&logthis("-$id-$name-$hostname-");
13318: 	if ($hostname eq $name) {
13319: 	    push(@domains,&host_domain($id));
13320: 	}
13321:     }
13322:     return @domains;
13323: }
13324: 
13325: sub current_machine_ids {
13326:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
13327: }
13328: 
13329: sub machine_ids {
13330:     my ($hostname) = @_;
13331:     $hostname ||= &hostname($perlvar{'lonHostID'});
13332:     my @ids;
13333:     my %name_to_host = &all_names();
13334:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
13335: 	return @{ $name_to_host{$hostname} };
13336:     }
13337:     return;
13338: }
13339: 
13340: sub additional_machine_domains {
13341:     my @domains;
13342:     open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
13343:     while( my $line = <$fh>) {
13344:         $line =~ s/\s//g;
13345:         push(@domains,$line);
13346:     }
13347:     return @domains;
13348: }
13349: 
13350: sub default_login_domain {
13351:     my $domain = $perlvar{'lonDefDomain'};
13352:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
13353:     foreach my $posdom (&current_machine_domains(),
13354:                         &additional_machine_domains()) {
13355:         if (lc($posdom) eq lc($testdomain)) {
13356:             $domain=$posdom;
13357:             last;
13358:         }
13359:     }
13360:     return $domain;
13361: }
13362: 
13363: sub shared_institution {
13364:     my ($dom) = @_;
13365:     my $same_intdom;
13366:     my $hostintdom = &internet_dom($perlvar{'lonHostID'});
13367:     if ($hostintdom ne '') {
13368:         my %iphost = &get_iphost();
13369:         my $primary_id = &domain($dom,'primary');
13370:         my $primary_ip = &get_host_ip($primary_id);
13371:         if (ref($iphost{$primary_ip}) eq 'ARRAY') {
13372:             foreach my $id (@{$iphost{$primary_ip}}) {
13373:                 my $intdom = &internet_dom($id);
13374:                 if ($intdom eq $hostintdom) {
13375:                     $same_intdom = 1;
13376:                     last;
13377:                 }
13378:             }
13379:         }
13380:     }
13381:     return $same_intdom;
13382: }
13383: 
13384: sub uses_sts {
13385:     my ($ignore_cache) = @_;
13386:     my $lonhost = $perlvar{'lonHostID'};
13387:     my $hostname = &hostname($lonhost);
13388:     my $sts_on;
13389:     if ($protocol{$lonhost} eq 'https') {
13390:         my $cachetime = 12*3600;
13391:         if (!$ignore_cache) {
13392:             ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
13393:             if (defined($cached)) {
13394:                 return $sts_on;
13395:             }
13396:         }
13397:         my $ua=new LWP::UserAgent;
13398:         my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
13399:         my $request=new HTTP::Request('HEAD',$url);
13400:         my $response=$ua->request($request);
13401:         if ($response->is_success) {
13402:             my $has_sts = $response->header('Strict-Transport-Security');
13403:             if ($has_sts eq '') {
13404:                 $sts_on = 0;
13405:             } else {
13406:                 if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
13407:                     my $maxage = $1;
13408:                     if ($maxage) {
13409:                         $sts_on = 1;
13410:                     } else {
13411:                         $sts_on = 0;
13412:                     }
13413:                 } else {
13414:                     $sts_on = 0;
13415:                 }
13416:             }
13417:             return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
13418:         }
13419:     }
13420:     return;
13421: }
13422: 
13423: # ------------------------------------------------------------- Declutters URLs
13424: 
13425: sub declutter {
13426:     my $thisfn=shift;
13427:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
13428:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
13429:         $thisfn=~s{^/home/httpd/html}{};
13430:     }
13431:     $thisfn=~s/^\///;
13432:     $thisfn=~s|^adm/wrapper/||;
13433:     $thisfn=~s|^adm/coursedocs/showdoc/||;
13434:     $thisfn=~s/^res\///;
13435:     $thisfn=~s/^priv\///;
13436:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
13437:         $thisfn=~s/\?.+$//;
13438:     }
13439:     return $thisfn;
13440: }
13441: 
13442: # ------------------------------------------------------------- Clutter up URLs
13443: 
13444: sub clutter {
13445:     my $thisfn='/'.&declutter(shift);
13446:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
13447: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
13448:        $thisfn='/res'.$thisfn; 
13449:     }
13450:     if ($thisfn !~m|^/adm|) {
13451: 	if ($thisfn =~ m|^/ext/|) {
13452: 	    $thisfn='/adm/wrapper'.$thisfn;
13453: 	} else {
13454: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
13455: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
13456: 	    if ($embstyle eq 'ssi'
13457: 		|| ($embstyle eq 'hdn')
13458: 		|| ($embstyle eq 'rat')
13459: 		|| ($embstyle eq 'prv')
13460: 		|| ($embstyle eq 'ign')) {
13461: 		#do nothing with these
13462: 	    } elsif (($embstyle eq 'img') 
13463: 		|| ($embstyle eq 'emb')
13464: 		|| ($embstyle eq 'wrp')) {
13465: 		$thisfn='/adm/wrapper'.$thisfn;
13466: 	    } elsif ($embstyle eq 'unk'
13467: 		     && $thisfn!~/\.(sequence|page)$/) {
13468: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
13469: 	    } else {
13470: #		&logthis("Got a blank emb style");
13471: 	    }
13472: 	}
13473:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
13474:         $thisfn='/adm/wrapper'.$thisfn;
13475:     }
13476:     return $thisfn;
13477: }
13478: 
13479: sub clutter_with_no_wrapper {
13480:     my $uri = &clutter(shift);
13481:     if ($uri =~ m-^/adm/-) {
13482: 	$uri =~ s-^/adm/wrapper/-/-;
13483: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
13484:     }
13485:     return $uri;
13486: }
13487: 
13488: sub freeze_escape {
13489:     my ($value)=@_;
13490:     if (ref($value)) {
13491: 	$value=&nfreeze($value);
13492: 	return '__FROZEN__'.&escape($value);
13493:     }
13494:     return &escape($value);
13495: }
13496: 
13497: 
13498: sub thaw_unescape {
13499:     my ($value)=@_;
13500:     if ($value =~ /^__FROZEN__/) {
13501: 	substr($value,0,10,undef);
13502: 	$value=&unescape($value);
13503: 	return &thaw($value);
13504:     }
13505:     return &unescape($value);
13506: }
13507: 
13508: sub correct_line_ends {
13509:     my ($result)=@_;
13510:     $$result =~s/\r\n/\n/mg;
13511:     $$result =~s/\r/\n/mg;
13512: }
13513: # ================================================================ Main Program
13514: 
13515: sub goodbye {
13516:    &logthis("Starting Shut down");
13517: #not converted to using infrastruture and probably shouldn't be
13518:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
13519: #converted
13520: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
13521:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
13522: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
13523: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
13524: #1.1 only
13525: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
13526: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
13527: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
13528: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
13529:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
13530:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
13531:    &logthis(sprintf("%-20s is %s",'hits',$hits));
13532:    &flushcourselogs();
13533:    &logthis("Shutting down");
13534: }
13535: 
13536: sub get_dns {
13537:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
13538:     if (!$ignore_cache) {
13539: 	my ($content,$cached)=
13540: 	    &Apache::lonnet::is_cached_new('dns',$url);
13541: 	if ($cached) {
13542: 	    &$func($content,$hashref);
13543: 	    return;
13544: 	}
13545:     }
13546: 
13547:     my %alldns;
13548:     if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
13549:         foreach my $dns (<$config>) {
13550: 	    next if ($dns !~ /^\^(\S*)/x);
13551:             my $line = $1;
13552:             my ($host,$protocol) = split(/:/,$line);
13553:             if ($protocol ne 'https') {
13554:                 $protocol = 'http';
13555:             }
13556: 	    $alldns{$host} = $protocol;
13557:         }
13558:         close($config);
13559:     }
13560:     while (%alldns) {
13561: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
13562: 	my $ua=new LWP::UserAgent;
13563:         $ua->timeout(30);
13564: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
13565: 	my $response=$ua->request($request);
13566:         delete($alldns{$dns});
13567: 	next if ($response->is_error());
13568: 	my @content = split("\n",$response->content);
13569:         unless ($nocache) {
13570: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
13571:         }
13572: 	&$func(\@content,$hashref);
13573: 	return;
13574:     }
13575:     my $which = (split('/',$url))[3];
13576:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
13577:     if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
13578:         my @content = <$config>;
13579:         &$func(\@content,$hashref);
13580:     }
13581:     return;
13582: }
13583: 
13584: # ------------------------------------------------------Get DNS checksums file
13585: sub parse_dns_checksums_tab {
13586:     my ($lines,$hashref) = @_;
13587:     my $lonhost = $perlvar{'lonHostID'};
13588:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
13589:     my $loncaparev = &get_server_loncaparev($machine_dom);
13590:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
13591:     my $webconfdir = '/etc/httpd/conf';
13592:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
13593:         $webconfdir = '/etc/apache2';
13594:     } elsif ($distro =~ /^sles(\d+)$/) {
13595:         if ($1 >= 10) {
13596:             $webconfdir = '/etc/apache2';
13597:         }
13598:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
13599:         if ($1 >= 10.0) {
13600:             $webconfdir = '/etc/apache2';
13601:         }
13602:     }
13603:     my ($release,$timestamp) = split(/\-/,$loncaparev);
13604:     my (%chksum,%revnum);
13605:     if (ref($lines) eq 'ARRAY') {
13606:         chomp(@{$lines});
13607:         my $version = shift(@{$lines});
13608:         if ($version eq $release) {
13609:             foreach my $line (@{$lines}) {
13610:                 my ($file,$version,$shasum) = split(/,/,$line);
13611:                 if ($file =~ m{^/etc/httpd/conf}) {
13612:                     if ($webconfdir eq '/etc/apache2') {
13613:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
13614:                     }
13615:                 }
13616:                 $chksum{$file} = $shasum;
13617:                 $revnum{$file} = $version;
13618:             }
13619:             if (ref($hashref) eq 'HASH') {
13620:                 %{$hashref} = (
13621:                                 sums     => \%chksum,
13622:                                 versions => \%revnum,
13623:                               );
13624:             }
13625:         }
13626:     }
13627:     return;
13628: }
13629: 
13630: sub fetch_dns_checksums {
13631:     my %checksums;
13632:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
13633:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
13634:     my ($release,$timestamp) = split(/\-/,$loncaparev);
13635:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
13636:              \%checksums);
13637:     return \%checksums;
13638: }
13639: 
13640: # ------------------------------------------------------------ Read domain file
13641: {
13642:     my $loaded;
13643:     my %domain;
13644: 
13645:     sub parse_domain_tab {
13646: 	my ($lines) = @_;
13647: 	foreach my $line (@$lines) {
13648: 	    next if ($line =~ /^(\#|\s*$ )/x);
13649: 
13650: 	    chomp($line);
13651: 	    my ($name,@elements) = split(/:/,$line,9);
13652: 	    my %this_domain;
13653: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
13654: 			       'lang_def', 'city', 'longi', 'lati',
13655: 			       'primary') {
13656: 		$this_domain{$field} = shift(@elements);
13657: 	    }
13658: 	    $domain{$name} = \%this_domain;
13659: 	}
13660:     }
13661: 
13662:     sub reset_domain_info {
13663: 	undef($loaded);
13664: 	undef(%domain);
13665:     }
13666: 
13667:     sub load_domain_tab {
13668: 	my ($ignore_cache,$nocache) = @_;
13669: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
13670: 	my $fh;
13671: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
13672: 	    my @lines = <$fh>;
13673: 	    &parse_domain_tab(\@lines);
13674: 	}
13675: 	close($fh);
13676: 	$loaded = 1;
13677:     }
13678: 
13679:     sub domain {
13680: 	&load_domain_tab() if (!$loaded);
13681: 
13682: 	my ($name,$what) = @_;
13683: 	return if ( !exists($domain{$name}) );
13684: 
13685: 	if (!$what) {
13686: 	    return $domain{$name}{'description'};
13687: 	}
13688: 	return $domain{$name}{$what};
13689:     }
13690: 
13691:     sub domain_info {
13692:         &load_domain_tab() if (!$loaded);
13693:         return %domain;
13694:     }
13695: 
13696: }
13697: 
13698: 
13699: # ------------------------------------------------------------- Read hosts file
13700: {
13701:     my %hostname;
13702:     my %hostdom;
13703:     my %libserv;
13704:     my $loaded;
13705:     my %name_to_host;
13706:     my %internetdom;
13707:     my %LC_dns_serv;
13708: 
13709:     sub parse_hosts_tab {
13710: 	my ($file) = @_;
13711: 	foreach my $configline (@$file) {
13712: 	    next if ($configline =~ /^(\#|\s*$ )/x);
13713:             chomp($configline);
13714: 	    if ($configline =~ /^\^/) {
13715:                 if ($configline =~ /^\^([\w.\-]+)/) {
13716:                     $LC_dns_serv{$1} = 1;
13717:                 }
13718:                 next;
13719:             }
13720: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
13721: 	    $name=~s/\s//g;
13722: 	    if ($id && $domain && $role && $name) {
13723:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
13724:                     my $curr = $hostname{$id};
13725:                     my $skip;
13726:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
13727:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
13728:                             $skip = 1;
13729:                         } else {
13730:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
13731:                         }
13732:                     }
13733:                     unless ($skip) {
13734:                         push(@{$name_to_host{$name}},$id);
13735:                     }
13736:                 } else {
13737:                     push(@{$name_to_host{$name}},$id);
13738:                 }
13739: 		$hostname{$id}=$name;
13740: 		$hostdom{$id}=$domain;
13741: 		if ($role eq 'library') { $libserv{$id}=$name; }
13742:                 if (defined($protocol)) {
13743:                     if ($protocol eq 'https') {
13744:                         $protocol{$id} = $protocol;
13745:                     } else {
13746:                         $protocol{$id} = 'http'; 
13747:                     }
13748:                 } else {
13749:                     $protocol{$id} = 'http';
13750:                 }
13751:                 if (defined($intdom)) {
13752:                     $internetdom{$id} = $intdom;
13753:                 }
13754: 	    }
13755: 	}
13756:     }
13757:     
13758:     sub reset_hosts_info {
13759: 	&purge_remembered();
13760: 	&reset_domain_info();
13761: 	&reset_hosts_ip_info();
13762: 	undef(%name_to_host);
13763: 	undef(%hostname);
13764: 	undef(%hostdom);
13765: 	undef(%libserv);
13766: 	undef($loaded);
13767:     }
13768: 
13769:     sub load_hosts_tab {
13770: 	my ($ignore_cache,$nocache) = @_;
13771: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
13772: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
13773: 	my @config = <$config>;
13774: 	&parse_hosts_tab(\@config);
13775: 	close($config);
13776: 	$loaded=1;
13777:     }
13778: 
13779:     sub hostname {
13780: 	&load_hosts_tab() if (!$loaded);
13781: 
13782: 	my ($lonid) = @_;
13783: 	return $hostname{$lonid};
13784:     }
13785: 
13786:     sub all_hostnames {
13787: 	&load_hosts_tab() if (!$loaded);
13788: 
13789: 	return %hostname;
13790:     }
13791: 
13792:     sub all_names {
13793:         my ($ignore_cache,$nocache) = @_;
13794: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
13795: 
13796: 	return %name_to_host;
13797:     }
13798: 
13799:     sub all_host_domain {
13800:         &load_hosts_tab() if (!$loaded);
13801:         return %hostdom;
13802:     }
13803: 
13804:     sub is_library {
13805: 	&load_hosts_tab() if (!$loaded);
13806: 
13807: 	return exists($libserv{$_[0]});
13808:     }
13809: 
13810:     sub all_library {
13811: 	&load_hosts_tab() if (!$loaded);
13812: 
13813: 	return %libserv;
13814:     }
13815: 
13816:     sub unique_library {
13817: 	#2x reverse removes all hostnames that appear more than once
13818:         my %unique = reverse &all_library();
13819:         return reverse %unique;
13820:     }
13821: 
13822:     sub get_servers {
13823: 	&load_hosts_tab() if (!$loaded);
13824: 
13825: 	my ($domain,$type) = @_;
13826: 	my %possible_hosts = ($type eq 'library') ? %libserv
13827: 	                                          : %hostname;
13828: 	my %result;
13829: 	if (ref($domain) eq 'ARRAY') {
13830: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
13831: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
13832: 		    $result{$host} = $hostname;
13833: 		}
13834: 	    }
13835: 	} else {
13836: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
13837: 		if ($hostdom{$host} eq $domain) {
13838: 		    $result{$host} = $hostname;
13839: 		}
13840: 	    }
13841: 	}
13842: 	return %result;
13843:     }
13844: 
13845:     sub get_unique_servers {
13846:         my %unique = reverse &get_servers(@_);
13847: 	return reverse %unique;
13848:     }
13849: 
13850:     sub host_domain {
13851: 	&load_hosts_tab() if (!$loaded);
13852: 
13853: 	my ($lonid) = @_;
13854: 	return $hostdom{$lonid};
13855:     }
13856: 
13857:     sub all_domains {
13858: 	&load_hosts_tab() if (!$loaded);
13859: 
13860: 	my %seen;
13861: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
13862: 	return @uniq;
13863:     }
13864: 
13865:     sub internet_dom {
13866:         &load_hosts_tab() if (!$loaded);
13867: 
13868:         my ($lonid) = @_;
13869:         return $internetdom{$lonid};
13870:     }
13871: 
13872:     sub is_LC_dns {
13873:         &load_hosts_tab() if (!$loaded);
13874: 
13875:         my ($hostname) = @_;
13876:         return exists($LC_dns_serv{$hostname});
13877:     }
13878: 
13879: }
13880: 
13881: { 
13882:     my %iphost;
13883:     my %name_to_ip;
13884:     my %lonid_to_ip;
13885: 
13886:     sub get_hosts_from_ip {
13887: 	my ($ip) = @_;
13888: 	my %iphosts = &get_iphost();
13889: 	if (ref($iphosts{$ip})) {
13890: 	    return @{$iphosts{$ip}};
13891: 	}
13892: 	return;
13893:     }
13894:     
13895:     sub reset_hosts_ip_info {
13896: 	undef(%iphost);
13897: 	undef(%name_to_ip);
13898: 	undef(%lonid_to_ip);
13899:     }
13900: 
13901:     sub get_host_ip {
13902: 	my ($lonid) = @_;
13903: 	if (exists($lonid_to_ip{$lonid})) {
13904: 	    return $lonid_to_ip{$lonid};
13905: 	}
13906: 	my $name=&hostname($lonid);
13907:    	my $ip = gethostbyname($name);
13908: 	return if (!$ip || length($ip) ne 4);
13909: 	$ip=inet_ntoa($ip);
13910: 	$name_to_ip{$name}   = $ip;
13911: 	$lonid_to_ip{$lonid} = $ip;
13912: 	return $ip;
13913:     }
13914:     
13915:     sub get_iphost {
13916: 	my ($ignore_cache,$nocache) = @_;
13917: 
13918: 	if (!$ignore_cache) {
13919: 	    if (%iphost) {
13920: 		return %iphost;
13921: 	    }
13922: 	    my ($ip_info,$cached)=
13923: 		&Apache::lonnet::is_cached_new('iphost','iphost');
13924: 	    if ($cached) {
13925: 		%iphost      = %{$ip_info->[0]};
13926: 		%name_to_ip  = %{$ip_info->[1]};
13927: 		%lonid_to_ip = %{$ip_info->[2]};
13928: 		return %iphost;
13929: 	    }
13930: 	}
13931: 
13932: 	# get yesterday's info for fallback
13933: 	my %old_name_to_ip;
13934: 	my ($ip_info,$cached)=
13935: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
13936: 	if ($cached) {
13937: 	    %old_name_to_ip = %{$ip_info->[1]};
13938: 	}
13939: 
13940: 	my %name_to_host = &all_names($ignore_cache,$nocache);
13941: 	foreach my $name (keys(%name_to_host)) {
13942: 	    my $ip;
13943: 	    if (!exists($name_to_ip{$name})) {
13944: 		$ip = gethostbyname($name);
13945: 		if (!$ip || length($ip) ne 4) {
13946: 		    if (defined($old_name_to_ip{$name})) {
13947: 			$ip = $old_name_to_ip{$name};
13948: 			&logthis("Can't find $name defaulting to old $ip");
13949: 		    } else {
13950: 			&logthis("Name $name no IP found");
13951: 			next;
13952: 		    }
13953: 		} else {
13954: 		    $ip=inet_ntoa($ip);
13955: 		}
13956: 		$name_to_ip{$name} = $ip;
13957: 	    } else {
13958: 		$ip = $name_to_ip{$name};
13959: 	    }
13960: 	    foreach my $id (@{ $name_to_host{$name} }) {
13961: 		$lonid_to_ip{$id} = $ip;
13962: 	    }
13963: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
13964: 	}
13965:         unless ($nocache) {
13966: 	    &do_cache_new('iphost','iphost',
13967: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
13968: 		          48*60*60);
13969:         }
13970: 
13971: 	return %iphost;
13972:     }
13973: 
13974:     #
13975:     #  Given a DNS returns the loncapa host name for that DNS 
13976:     # 
13977:     sub host_from_dns {
13978:         my ($dns) = @_;
13979:         my @hosts;
13980:         my $ip;
13981: 
13982:         if (exists($name_to_ip{$dns})) {
13983:             $ip = $name_to_ip{$dns};
13984:         }
13985:         if (!$ip) {
13986:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
13987:             if (length($ip) == 4) { 
13988: 	        $ip   = &IO::Socket::inet_ntoa($ip);
13989:             }
13990:         }
13991:         if ($ip) {
13992: 	    @hosts = get_hosts_from_ip($ip);
13993: 	    return $hosts[0];
13994:         }
13995:         return undef;
13996:     }
13997: 
13998:     sub get_internet_names {
13999:         my ($lonid) = @_;
14000:         return if ($lonid eq '');
14001:         my ($idnref,$cached)=
14002:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
14003:         if ($cached) {
14004:             return $idnref;
14005:         }
14006:         my $ip = &get_host_ip($lonid);
14007:         my @hosts = &get_hosts_from_ip($ip);
14008:         my %iphost = &get_iphost();
14009:         my (@idns,%seen);
14010:         foreach my $id (@hosts) {
14011:             my $dom = &host_domain($id);
14012:             my $prim_id = &domain($dom,'primary');
14013:             my $prim_ip = &get_host_ip($prim_id);
14014:             next if ($seen{$prim_ip});
14015:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
14016:                 foreach my $id (@{$iphost{$prim_ip}}) {
14017:                     my $intdom = &internet_dom($id);
14018:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
14019:                         push(@idns,$intdom);
14020:                     }
14021:                 }
14022:             }
14023:             $seen{$prim_ip} = 1;
14024:         }
14025:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
14026:     }
14027: 
14028: }
14029: 
14030: sub all_loncaparevs {
14031:     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);
14032: }
14033: 
14034: # ------------------------------------------------------- Read loncaparev table
14035: {
14036:     sub load_loncaparevs {
14037:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
14038:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
14039:                 while (my $configline=<$config>) {
14040:                     chomp($configline);
14041:                     my ($hostid,$loncaparev)=split(/:/,$configline);
14042:                     $loncaparevs{$hostid}=$loncaparev;
14043:                 }
14044:                 close($config);
14045:             }
14046:         }
14047:     }
14048: }
14049: 
14050: # ----------------------------------------------------- Read serverhostID table
14051: {
14052:     sub load_serverhomeIDs {
14053:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
14054:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
14055:                 while (my $configline=<$config>) {
14056:                     chomp($configline);
14057:                     my ($name,$id)=split(/:/,$configline);
14058:                     $serverhomeIDs{$name}=$id;
14059:                 }
14060:                 close($config);
14061:             }
14062:         }
14063:     }
14064: }
14065: 
14066: 
14067: BEGIN {
14068: 
14069: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
14070:     unless ($readit) {
14071: {
14072:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
14073:     %perlvar = (%perlvar,%{$configvars});
14074: }
14075: 
14076: 
14077: # ------------------------------------------------------ Read spare server file
14078: {
14079:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
14080: 
14081:     while (my $configline=<$config>) {
14082:        chomp($configline);
14083:        if ($configline) {
14084: 	   my ($host,$type) = split(':',$configline,2);
14085: 	   if (!defined($type) || $type eq '') { $type = 'default' };
14086: 	   push(@{ $spareid{$type} }, $host);
14087:        }
14088:     }
14089:     close($config);
14090: }
14091: # ------------------------------------------------------------ Read permissions
14092: {
14093:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
14094: 
14095:     while (my $configline=<$config>) {
14096: 	chomp($configline);
14097: 	if ($configline) {
14098: 	    my ($role,$perm)=split(/ /,$configline);
14099: 	    if ($perm ne '') { $pr{$role}=$perm; }
14100: 	}
14101:     }
14102:     close($config);
14103: }
14104: 
14105: # -------------------------------------------- Read plain texts for permissions
14106: {
14107:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
14108: 
14109:     while (my $configline=<$config>) {
14110: 	chomp($configline);
14111: 	if ($configline) {
14112: 	    my ($short,@plain)=split(/:/,$configline);
14113:             %{$prp{$short}} = ();
14114: 	    if (@plain > 0) {
14115:                 $prp{$short}{'std'} = $plain[0];
14116:                 for (my $i=1; $i<@plain; $i++) {
14117:                     $prp{$short}{'alt'.$i} = $plain[$i];  
14118:                 }
14119:             }
14120: 	}
14121:     }
14122:     close($config);
14123: }
14124: 
14125: # ---------------------------------------------------------- Read package table
14126: {
14127:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
14128: 
14129:     while (my $configline=<$config>) {
14130: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
14131: 	chomp($configline);
14132: 	my ($short,$plain)=split(/:/,$configline);
14133: 	my ($pack,$name)=split(/\&/,$short);
14134: 	if ($plain ne '') {
14135: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
14136: 	    $packagetab{$short}=$plain; 
14137: 	}
14138:     }
14139:     close($config);
14140: }
14141: 
14142: # --------------------------------------------------------- Read loncaparev table
14143: 
14144: &load_loncaparevs();
14145: 
14146: # ------------------------------------------------------- Read serverhostID table
14147: 
14148: &load_serverhomeIDs();
14149: 
14150: # ---------------------------------------------------------- Read releaseslist XML
14151: {
14152:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
14153:     if (-e $file) {
14154:         my $parser = HTML::LCParser->new($file);
14155:         while (my $token = $parser->get_token()) {
14156:             if ($token->[0] eq 'S') {
14157:                 my $item = $token->[1];
14158:                 my $name = $token->[2]{'name'};
14159:                 my $value = $token->[2]{'value'};
14160:                 if ($item ne '' && $name ne '' && $value ne '') {
14161:                     my $release = $parser->get_text();
14162:                     $release =~ s/(^\s*|\s*$ )//gx;
14163:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
14164:                 }
14165:             }
14166:         }
14167:     }
14168: }
14169: 
14170: # ---------------------------------------------------------- Read managers table
14171: {
14172:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
14173:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
14174:             while (my $configline=<$config>) {
14175:                 chomp($configline);
14176:                 next if ($configline =~ /^\#/);
14177:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
14178:                     $managerstab{$configline} = 1;
14179:                 }
14180:             }
14181:             close($config);
14182:         }
14183:     }
14184: }
14185: 
14186: # ------------- set up temporary directory
14187: {
14188:     $tmpdir = LONCAPA::tempdir();
14189: 
14190: }
14191: 
14192: # ------------- set default texengine (domain default overrides this)
14193: {
14194:     $deftex = LONCAPA::texengine();
14195: }
14196: 
14197: # ------------- set default minimum length for passwords for internal auth users
14198: {
14199:     $passwdmin = LONCAPA::passwd_min();
14200: }
14201: 
14202: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
14203: 				'compress_threshold'=> 20_000,
14204:  			        });
14205: 
14206: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
14207: $dumpcount=0;
14208: $locknum=0;
14209: 
14210: &logtouch();
14211: &logthis('<font color="yellow">INFO: Read configuration</font>');
14212: $readit=1;
14213:     {
14214: 	use integer;
14215: 	my $test=(2**32)+1;
14216: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
14217: 	&logthis(" Detected 64bit platform ($_64bit)");
14218:     }
14219: }
14220: }
14221: 
14222: 1;
14223: __END__
14224: 
14225: =pod
14226: 
14227: =head1 NAME
14228: 
14229: Apache::lonnet - Subroutines to ask questions about things in the network.
14230: 
14231: =head1 SYNOPSIS
14232: 
14233: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
14234: 
14235:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
14236: 
14237: Common parameters:
14238: 
14239: =over 4
14240: 
14241: =item *
14242: 
14243: $uname : an internal username (if $cname expecting a course Id specifically)
14244: 
14245: =item *
14246: 
14247: $udom : a domain (if $cdom expecting a course's domain specifically)
14248: 
14249: =item *
14250: 
14251: $symb : a resource instance identifier
14252: 
14253: =item *
14254: 
14255: $namespace : the name of a .db file that contains the data needed or
14256: being set.
14257: 
14258: =back
14259: 
14260: =head1 OVERVIEW
14261: 
14262: lonnet provides subroutines which interact with the
14263: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
14264: about classes, users, and resources.
14265: 
14266: For many of these objects you can also use this to store data about
14267: them or modify them in various ways.
14268: 
14269: =head2 Symbs
14270: 
14271: To identify a specific instance of a resource, LON-CAPA uses symbols
14272: or "symbs"X<symb>. These identifiers are built from the URL of the
14273: map, the resource number of the resource in the map, and the URL of
14274: the resource itself. The latter is somewhat redundant, but might help
14275: if maps change.
14276: 
14277: An example is
14278: 
14279:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
14280: 
14281: The respective map entry is
14282: 
14283:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
14284:   title="Problem 2">
14285:  </resource>
14286: 
14287: Symbs are used by the random number generator, as well as to store and
14288: restore data specific to a certain instance of for example a problem.
14289: 
14290: =head2 Storing And Retrieving Data
14291: 
14292: X<store()>X<cstore()>X<restore()>Three of the most important functions
14293: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
14294: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
14295: is is the non-critical message twin of cstore. These functions are for
14296: handlers to store a perl hash to a user's permanent data space in an
14297: easy manner, and to retrieve it again on another call. It is expected
14298: that a handler would use this once at the beginning to retrieve data,
14299: and then again once at the end to send only the new data back.
14300: 
14301: The data is stored in the user's data directory on the user's
14302: homeserver under the ID of the course.
14303: 
14304: The hash that is returned by restore will have all of the previous
14305: value for all of the elements of the hash.
14306: 
14307: Example:
14308: 
14309:  #creating a hash
14310:  my %hash;
14311:  $hash{'foo'}='bar';
14312: 
14313:  #storing it
14314:  &Apache::lonnet::cstore(\%hash);
14315: 
14316:  #changing a value
14317:  $hash{'foo'}='notbar';
14318: 
14319:  #adding a new value
14320:  $hash{'bar'}='foo';
14321:  &Apache::lonnet::cstore(\%hash);
14322: 
14323:  #retrieving the hash
14324:  my %history=&Apache::lonnet::restore();
14325: 
14326:  #print the hash
14327:  foreach my $key (sort(keys(%history))) {
14328:    print("\%history{$key} = $history{$key}");
14329:  }
14330: 
14331: Will print out:
14332: 
14333:  %history{1:foo} = bar
14334:  %history{1:keys} = foo:timestamp
14335:  %history{1:timestamp} = 990455579
14336:  %history{2:bar} = foo
14337:  %history{2:foo} = notbar
14338:  %history{2:keys} = foo:bar:timestamp
14339:  %history{2:timestamp} = 990455580
14340:  %history{bar} = foo
14341:  %history{foo} = notbar
14342:  %history{timestamp} = 990455580
14343:  %history{version} = 2
14344: 
14345: Note that the special hash entries C<keys>, C<version> and
14346: C<timestamp> were added to the hash. C<version> will be equal to the
14347: total number of versions of the data that have been stored. The
14348: C<timestamp> attribute will be the UNIX time the hash was
14349: stored. C<keys> is available in every historical section to list which
14350: keys were added or changed at a specific historical revision of a
14351: hash.
14352: 
14353: B<Warning>: do not store the hash that restore returns directly. This
14354: will cause a mess since it will restore the historical keys as if the
14355: were new keys. I.E. 1:foo will become 1:1:foo etc.
14356: 
14357: Calling convention:
14358: 
14359:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
14360:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
14361: 
14362: For more detailed information, see lonnet specific documentation.
14363: 
14364: =head1 RETURN MESSAGES
14365: 
14366: =over 4
14367: 
14368: =item * B<con_lost>: unable to contact remote host
14369: 
14370: =item * B<con_delayed>: unable to contact remote host, message will be delivered
14371: when the connection is brought back up
14372: 
14373: =item * B<con_failed>: unable to contact remote host and unable to save message
14374: for later delivery
14375: 
14376: =item * B<error:>: an error a occurred, a description of the error follows the :
14377: 
14378: =item * B<no_such_host>: unable to fund a host associated with the user/domain
14379: that was requested
14380: 
14381: =back
14382: 
14383: =head1 PUBLIC SUBROUTINES
14384: 
14385: =head2 Session Environment Functions
14386: 
14387: =over 4
14388: 
14389: =item * 
14390: X<appenv()>
14391: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
14392: the user envirnoment file, and will be restored for each access this
14393: user makes during this session, also modifies the %env for the current
14394: process. Optional rolesarrayref - if defined contains a reference to an array
14395: of roles which are exempt from the restriction on modifying user.role entries 
14396: in the user's environment.db and in %env.    
14397: 
14398: =item *
14399: X<delenv()>
14400: B<delenv($delthis,$regexp)>: removes all items from the session
14401: environment file that begin with $delthis. If the 
14402: optional second arg - $regexp - is true, $delthis is treated as a 
14403: regular expression, otherwise \Q$delthis\E is used. 
14404: The values are also deleted from the current processes %env.
14405: 
14406: =item * get_env_multiple($name) 
14407: 
14408: gets $name from the %env hash, it seemlessly handles the cases where multiple
14409: values may be defined and end up as an array ref.
14410: 
14411: returns an array of values
14412: 
14413: =back
14414: 
14415: =head2 User Information
14416: 
14417: =over 4
14418: 
14419: =item *
14420: X<queryauthenticate()>
14421: B<queryauthenticate($uname,$udom)>: try to determine user's current 
14422: authentication scheme
14423: 
14424: =item *
14425: X<authenticate()>
14426: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
14427: authenticate user from domain's lib servers (first use the current
14428: one). C<$upass> should be the users password.
14429: $checkdefauth is optional (value is 1 if a check should be made to
14430:    authenticate user using default authentication method, and allow
14431:    account creation if username does not have account in the domain).
14432: $clientcancheckhost is optional (value is 1 if checking whether the
14433:    server can host will occur on the client side in lonauth.pm).   
14434: 
14435: =item *
14436: X<homeserver()>
14437: B<homeserver($uname,$udom)>: find the server which has
14438: the user's directory and files (there must be only one), this caches
14439: the answer, and also caches if there is a borken connection.
14440: 
14441: =item *
14442: X<idget()>
14443: B<idget($udom,@ids)>: find the usernames behind a list of IDs
14444: (IDs are a unique resource in a domain, there must be only 1 ID per
14445: username, and only 1 username per ID in a specific domain) (returns
14446: hash: id=>name,id=>name)
14447: 
14448: =item *
14449: X<idrget()>
14450: B<idrget($udom,@unames)>: find the IDs behind a list of
14451: usernames (returns hash: name=>id,name=>id)
14452: 
14453: =item *
14454: X<idput()>
14455: B<idput($udom,%ids)>: store away a list of names and associated IDs
14456: 
14457: =item *
14458: X<rolesinit()>
14459: B<rolesinit($udom,$username)>: get user privileges.
14460: returns user role, first access and timer interval hashes
14461: 
14462: =item *
14463: X<privileged()>
14464: B<privileged($username,$domain)>: returns a true if user has a
14465: privileged and active role (i.e. su or dc), false otherwise.
14466: 
14467: =item *
14468: X<getsection()>
14469: B<getsection($udom,$uname,$cname)>: finds the section of student in the
14470: course $cname, return section name/number or '' for "not in course"
14471: and '-1' for "no section"
14472: 
14473: =item *
14474: X<userenvironment()>
14475: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
14476: passed in @what from the requested user's environment, returns a hash
14477: 
14478: =item * 
14479: X<userlog_query()>
14480: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
14481: activity.log file. %filters defines filters applied when parsing the
14482: log file. These can be start or end timestamps, or the type of action
14483: - log to look for Login or Logout events, check for Checkin or
14484: Checkout, role for role selection. The response is in the form
14485: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
14486: escaped strings of the action recorded in the activity.log file.
14487: 
14488: =back
14489: 
14490: =head2 User Roles
14491: 
14492: =over 4
14493: 
14494: =item *
14495: 
14496: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
14497: returns codes for allowed actions.
14498: 
14499: The first argument is required, all others are optional.
14500: 
14501: $priv is the privilege being checked.
14502: $uri contains additional information about what is being checked for access (e.g.,
14503: URL, course ID etc.).
14504: $symb is the unique resource instance identifier in a course; if needed,
14505: but not provided, it will be retrieved via a call to &symbread().
14506: $role is the role for which a priv is being checked (only used if priv is evb).
14507: $clientip is the user's IP address (only used when checking for access to portfolio
14508: files).
14509: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
14510: prevents recursive calls to &allowed.
14511: 
14512:  F: full access
14513:  U,I,K: authentication modes (cxx only)
14514:  '': forbidden
14515:  1: user needs to choose course
14516:  2: browse allowed
14517:  A: passphrase authentication needed
14518:  B: access temporarily blocked because of a blocking event in a course.
14519: 
14520: =item *
14521: 
14522: constructaccess($url,$setpriv) : check for access to construction space URL
14523: 
14524: See if the owner domain and name in the URL match those in the
14525: expected environment.  If so, return three element list
14526: ($ownername,$ownerdomain,$ownerhome).
14527: 
14528: Otherwise return the null string.
14529: 
14530: If second argument 'setpriv' is true, it assigns the privileges,
14531: and returns the same three element list, unless the owner has
14532: blocked "ad hoc" Domain Coordinator access to the Author Space,
14533: in which case the null string is returned.
14534: 
14535: =item *
14536: 
14537: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
14538: define a custom role rolename set privileges in format of lonTabs/roles.tab
14539: for system, domain, and course level. $uname and $udom are optional (current
14540: user's username and domain will be used when either of $uname or $udom are absent.
14541: 
14542: =item *
14543: 
14544: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
14545: (rolesplain.tab); plain text explanation of a user role term.
14546: $type is Course (default) or Community.
14547: If $forcedefault evaluates to true, text returned will be default 
14548: text for $type. Otherwise, if this is a course, the text returned 
14549: will be a custom name for the role (if defined in the course's 
14550: environment).  If no custom name is defined the default is returned.
14551:    
14552: =item *
14553: 
14554: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
14555: All arguments are optional. Returns a hash of a roles, either for
14556: co-author/assistant author roles for a user's Construction Space
14557: (default), or if $context is 'userroles', roles for the user himself,
14558: In the hash, keys are set to colon-separated $uname,$udom,$role, and
14559: (optionally) if $withsec is true, a fourth colon-separated item - $section.
14560: For each key, value is set to colon-separated start and end times for
14561: the role.  If no username and domain are specified, will default to
14562: current user/domain. Types, roles, and roledoms are references to arrays
14563: of role statuses (active, future or previous), roles 
14564: (e.g., cc,in, st etc.) and domains of the roles which can be used
14565: to restrict the list of roles reported. If no array ref is 
14566: provided for types, will default to return only active roles.
14567: 
14568: =item *
14569: 
14570: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
14571: user: $uname:$udom has a role in the course: $cdom_$cnum.
14572: 
14573: Additional optional arguments are: $type (if role checking is to be restricted
14574: to certain user status types -- previous (expired roles), active (currently
14575: available roles) or future (roles available in the future), and
14576: $hideprivileged -- if true will not report course roles for users who
14577: have active Domain Coordinator role in course's domain or in additional
14578: domains (specified in 'Domains to check for privileged users' in course
14579: environment -- set via:  Course Settings -> Classlists and staff listing).
14580: 
14581: =item *
14582: 
14583: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
14584: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
14585: $possdomains and $possroles are optional array refs -- to domains to check and
14586: roles to check.  If $possdomains is not specified, a dump will be done of the
14587: users' roles.db to check for a dc or su role in any domain. This can be
14588: time consuming if &privileged is called repeatedly (e.g., when displaying a
14589: classlist), so in such cases, supplying a $possdomains array is preferred, as
14590: this then allows &privileged_by_domain() to be used, which caches the identity
14591: of privileged users, eliminating the need for repeated calls to &dump().
14592: 
14593: =item *
14594: 
14595: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
14596: where the outer hash keys are domains specified in the $possdomains array ref,
14597: next inner hash keys are privileged roles specified in the $roles array ref,
14598: and the innermost hash contains key = value pairs for username:domain = end:start
14599: for active or future "privileged" users with that role in that domain. To avoid
14600: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
14601: innerhash are cached using priv_$role and $dom as the identifiers.
14602: 
14603: =back
14604: 
14605: =head2 User Modification
14606: 
14607: =over 4
14608: 
14609: =item *
14610: 
14611: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
14612: user for the level given by URL.  Optional start and end dates (leave empty
14613: string or zero for "no date")
14614: 
14615: =item *
14616: 
14617: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
14618: change a users, password, possible return values are: ok,
14619: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
14620: refused
14621: 
14622: =item *
14623: 
14624: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
14625: 
14626: =item *
14627: 
14628: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
14629:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
14630: 
14631: will update user information (firstname,middlename,lastname,generation,
14632: permanentemail), and if forceid is true, student/employee ID also.
14633: A user's institutional affiliation(s) can also be updated.
14634: User information fields will not be overwritten with empty entries 
14635: unless the field is included in the $candelete array reference.
14636: This array is included when a single user is modified via "Manage Users",
14637: or when Autoupdate.pl is run by cron in a domain.
14638: 
14639: =item *
14640: 
14641: modifystudent
14642: 
14643: modify a student's enrollment and identification information.
14644: The course id is resolved based on the current user's environment.  
14645: This means the invoking user must be a course coordinator or otherwise
14646: associated with a course.
14647: 
14648: This call is essentially a wrapper for lonnet::modifyuser and
14649: lonnet::modify_student_enrollment
14650: 
14651: Inputs: 
14652: 
14653: =over 4
14654: 
14655: =item B<$udom> Student's loncapa domain
14656: 
14657: =item B<$uname> Student's loncapa login name
14658: 
14659: =item B<$uid> Student/Employee ID
14660: 
14661: =item B<$umode> Student's authentication mode
14662: 
14663: =item B<$upass> Student's password
14664: 
14665: =item B<$first> Student's first name
14666: 
14667: =item B<$middle> Student's middle name
14668: 
14669: =item B<$last> Student's last name
14670: 
14671: =item B<$gene> Student's generation
14672: 
14673: =item B<$usec> Student's section in course
14674: 
14675: =item B<$end> Unix time of the roles expiration
14676: 
14677: =item B<$start> Unix time of the roles start date
14678: 
14679: =item B<$forceid> If defined, allow $uid to be changed
14680: 
14681: =item B<$desiredhome> server to use as home server for student
14682: 
14683: =item B<$email> Student's permanent e-mail address
14684: 
14685: =item B<$type> Type of enrollment (auto or manual)
14686: 
14687: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
14688: 
14689: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
14690: 
14691: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
14692: 
14693: =item B<$context> role change context (shown in User Management Logs display in a course)
14694: 
14695: =item B<$inststatus> institutional status of user - : separated string of escaped status types
14696: 
14697: =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.
14698: 
14699: =back
14700: 
14701: =item *
14702: 
14703: modify_student_enrollment
14704: 
14705: Change a student's enrollment status in a class.  The environment variable
14706: 'role.request.course' must be defined for this function to proceed.
14707: 
14708: Inputs:
14709: 
14710: =over 4
14711: 
14712: =item $udom, student's domain
14713: 
14714: =item $uname, student's name
14715: 
14716: =item $uid, student's user id
14717: 
14718: =item $first, student's first name
14719: 
14720: =item $middle
14721: 
14722: =item $last
14723: 
14724: =item $gene
14725: 
14726: =item $usec
14727: 
14728: =item $end
14729: 
14730: =item $start
14731: 
14732: =item $type
14733: 
14734: =item $locktype
14735: 
14736: =item $cid
14737: 
14738: =item $selfenroll
14739: 
14740: =item $context
14741: 
14742: =item $credits, number of credits student will earn from this class
14743: 
14744: =item $instsec, institutional course section code for student
14745: 
14746: =back
14747: 
14748: 
14749: =item *
14750: 
14751: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
14752: custom role; give a custom role to a user for the level given by URL.  Specify
14753: name and domain of role author, and role name
14754: 
14755: =item *
14756: 
14757: revokerole($udom,$uname,$url,$role) : revoke a role for url
14758: 
14759: =item *
14760: 
14761: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
14762: 
14763: =back
14764: 
14765: =head2 Course Infomation
14766: 
14767: =over 4
14768: 
14769: =item *
14770: 
14771: coursedescription($courseid,$options) : returns a hash of information about the
14772: specified course id, including all environment settings for the
14773: course, the description of the course will be in the hash under the
14774: key 'description'
14775: 
14776: $options is an optional parameter that if supplied is a hash reference that controls
14777: what how this function works.  It has the following key/values:
14778: 
14779: =over 4
14780: 
14781: =item freshen_cache
14782: 
14783: If defined, and the environment cache for the course is valid, it is 
14784: returned in the returned hash.
14785: 
14786: =item one_time
14787: 
14788: If defined, the last cache time is set to _now_
14789: 
14790: =item user
14791: 
14792: If defined, the supplied username is used instead of the current user.
14793: 
14794: 
14795: =back
14796: 
14797: =item *
14798: 
14799: resdata($name,$domain,$type,@which) : request for current parameter
14800: setting for a specific $type, where $type is either 'course' or 'user',
14801: @what should be a list of parameters to ask about. This routine caches
14802: answers for 10 minutes.
14803: 
14804: =item *
14805: 
14806: get_courseresdata($courseid, $domain) : dump the entire course resource
14807: data base, returning a hash that is keyed by the resource name and has
14808: values that are the resource value.  I believe that the timestamps and
14809: versions are also returned.
14810: 
14811: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
14812: supplemental content area. This routine caches the number of files for
14813: 10 minutes.
14814: 
14815: =back
14816: 
14817: =head2 Course Modification
14818: 
14819: =over 4
14820: 
14821: =item *
14822: 
14823: writecoursepref($courseid,%prefs) : write preferences (environment
14824: database) for a course
14825: 
14826: =item *
14827: 
14828: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
14829: 
14830: =item *
14831: 
14832: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
14833: 
14834: =item *
14835: 
14836: is_course($courseid), is_course($cdom, $cnum)
14837: 
14838: Accepts either a combined $courseid (in the form of domain_courseid) or the
14839: two component version $cdom, $cnum. It checks if the specified course exists.
14840: 
14841: Returns:
14842:     undef if the course doesn't exist, otherwise
14843:     in scalar context the combined courseid.
14844:     in list context the two components of the course identifier, domain and 
14845:     courseid.    
14846: 
14847: =back
14848: 
14849: =head2 Bubblesheet Configuration
14850: 
14851: =over 4
14852: 
14853: =item *
14854: 
14855: get_scantron_config($which)
14856: 
14857: $which - the name of the configuration to parse from the file.
14858: 
14859: Parses and returns the bubblesheet configuration line selected as a
14860: hash of configuration file fields.
14861: 
14862: 
14863: Returns:
14864:     If the named configuration is not in the file, an empty
14865:     hash is returned.
14866: 
14867:     a hash with the fields
14868:       name         - internal name for the this configuration setup
14869:       description  - text to display to operator that describes this config
14870:       CODElocation - if 0 or the string 'none'
14871:                           - no CODE exists for this config
14872:                      if -1 || the string 'letter'
14873:                           - a CODE exists for this config and is
14874:                             a string of letters
14875:                      Unsupported value (but planned for future support)
14876:                           if a positive integer
14877:                                - The CODE exists as the first n items from
14878:                                  the question section of the form
14879:                           if the string 'number'
14880:                                - The CODE exists for this config and is
14881:                                  a string of numbers
14882:       CODEstart   - (only matter if a CODE exists) column in the line where
14883:                      the CODE starts
14884:       CODElength  - length of the CODE
14885:       IDstart     - column where the student/employee ID starts
14886:       IDlength    - length of the student/employee ID info
14887:       Qstart      - column where the information from the bubbled
14888:                     'questions' start
14889:       Qlength     - number of columns comprising a single bubble line from
14890:                     the sheet. (usually either 1 or 10)
14891:       Qon         - either a single character representing the character used
14892:                     to signal a bubble was chosen in the positional setup, or
14893:                     the string 'letter' if the letter of the chosen bubble is
14894:                     in the final, or 'number' if a number representing the
14895:                     chosen bubble is in the file (1->A 0->J)
14896:       Qoff        - the character used to represent that a bubble was
14897:                     left blank
14898:       PaperID     - if the scanning process generates a unique number for each
14899:                     sheet scanned the column that this ID number starts in
14900:       PaperIDlength - number of columns that comprise the unique ID number
14901:                       for the sheet of paper
14902:       FirstName   - column that the first name starts in
14903:       FirstNameLength - number of columns that the first name spans
14904:       LastName    - column that the last name starts in
14905:       LastNameLength - number of columns that the last name spans
14906:       BubblesPerRow - number of bubbles available in each row used to
14907:                       bubble an answer. (If not specified, 10 assumed).
14908: 
14909: 
14910: =item *
14911: 
14912: get_scantronformat_file($cdom)
14913: 
14914: $cdom - the course's domain (optional); if not supplied, uses
14915: domain for current $env{'request.course.id'}.
14916: 
14917: Returns an array containing lines from the scantron format file for
14918: the domain of the course.
14919: 
14920: If a url for a custom.tab file is listed in domain's configuration.db,
14921: lines are from this file.
14922: 
14923: Otherwise, if a default.tab has been published in RES space by the
14924: domainconfig user, lines are from this file.
14925: 
14926: Otherwise, fall back to getting lines from the legacy file on the
14927: local server:  /home/httpd/lonTabs/default_scantronformat.tab
14928: 
14929: =back
14930: 
14931: =head2 Resource Subroutines
14932: 
14933: =over 4
14934: 
14935: =item *
14936: 
14937: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
14938: 
14939: =item *
14940: 
14941: repcopy($filename) : subscribes to the requested file, and attempts to
14942: replicate from the owning library server, Might return
14943: 'unavailable', 'not_found', 'forbidden', 'ok', or
14944: 'bad_request', also attempts to grab the metadata for the
14945: resource. Expects the local filesystem pathname
14946: (/home/httpd/html/res/....)
14947: 
14948: =back
14949: 
14950: =head2 Resource Information
14951: 
14952: =over 4
14953: 
14954: =item *
14955: 
14956: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
14957: and returns the value of a variety of different possible values,
14958: $varname should be a request string, and the other parameters can be
14959: used to specify who and what one is asking about. Ordinarily, $cid 
14960: does not need to be specified, as it is retrived from 
14961: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
14962: within lonuserstate::loadmap() when initializing a course, before
14963: $env{'request.course.id'} has been set, so it needs to be provided
14964: in that one case.
14965: 
14966: Possible values for $varname are environment.lastname (or other item
14967: from the envirnment hash), user.name (or someother aspect about the
14968: user), resource.0.maxtries (or some other part and parameter of a
14969: resource)
14970: 
14971: =item *
14972: 
14973: directcondval($number) : get current value of a condition; reads from a state
14974: string
14975: 
14976: =item *
14977: 
14978: condval($condidx) : value of condition index based on state
14979: 
14980: =item *
14981: 
14982: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
14983: resource's metadata, $what should be either a specific key, or either
14984: 'keys' (to get a list of possible keys) or 'packages' to get a list of
14985: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
14986: 
14987: this function automatically caches all requests
14988: 
14989: =item *
14990: 
14991: metadata_query($query,$custom,$customshow) : make a metadata query against the
14992: network of library servers; returns file handle of where SQL and regex results
14993: will be stored for query
14994: 
14995: =item *
14996: 
14997: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
14998: return symbolic list entry (all arguments optional).
14999: 
15000: Args: filename is the filename (including path) for the file for which a symb
15001: is required; donotrecurse, if true will prevent calls to allowed() being made
15002: to check access status if more than one resource was found in the bighash
15003: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
15004: a randompick); ignorecachednull, if true will prevent a symb of '' being
15005: returned if $env{$cache_str} is defined as ''; checkforblock if true will
15006: cause possible symbs to be checked to determine if they are subject to content
15007: blocking, if so they will not be included as possible symbs; possibles is a
15008: ref to a hash, which, as a side effect, will be populated with all possible
15009: symbs (content blocking not tested).
15010: 
15011: returns the data handle
15012: 
15013: =item *
15014: 
15015: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
15016: and is a possible symb for the URL in $thisfn, and if is an encrypted
15017: resource that the user accessed using /enc/ returns a 1 on success, 0
15018: on failure, user must be in a course, as it assumes the existence of
15019: the course initial hash, and uses $env('request.course.id'}.  The third
15020: arg is an optional reference to a scalar.  If this arg is passed in the
15021: call to symbverify, it will be set to 1 if the symb has been set to be 
15022: encrypted; otherwise it will be null.
15023: 
15024: =item *
15025: 
15026: symbclean($symb) : removes versions numbers from a symb, returns the
15027: cleaned symb
15028: 
15029: =item *
15030: 
15031: is_on_map($uri) : checks if the $uri is somewhere on the current
15032: course map, user must be in a course for it to work.
15033: 
15034: =item *
15035: 
15036: numval($salt) : return random seed value (addend for rndseed)
15037: 
15038: =item *
15039: 
15040: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
15041: a random seed, all arguments are optional, if they aren't sent it uses the
15042: environment to derive them. Note: if symb isn't sent and it can't get one
15043: from &symbread it will use the current time as its return value
15044: 
15045: =item *
15046: 
15047: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
15048: unfakeable, receipt
15049: 
15050: =item *
15051: 
15052: receipt() : API to ireceipt working off of env values; given out to users
15053: 
15054: =item *
15055: 
15056: countacc($url) : count the number of accesses to a given URL
15057: 
15058: =item *
15059: 
15060: 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
15061: 
15062: =item *
15063: 
15064: 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)
15065: 
15066: =item *
15067: 
15068: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
15069: 
15070: =item *
15071: 
15072: devalidate($symb) : devalidate temporary spreadsheet calculations,
15073: forcing spreadsheet to reevaluate the resource scores next time.
15074: 
15075: =item *
15076: 
15077: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
15078: when viewing in course context.
15079: 
15080:  input: six args -- filename (decluttered), course number, course domain,
15081:                     url, symb (if registered) and group (if this is a
15082:                     group item -- e.g., bulletin board, group page etc.).
15083: 
15084:  output: array of five scalars --
15085:          $cfile -- url for file editing if editable on current server
15086:          $home -- homeserver of resource (i.e., for author if published,
15087:                                           or course if uploaded.).
15088:          $switchserver --  1 if server switch will be needed.
15089:          $forceedit -- 1 if icon/link should be to go to edit mode
15090:          $forceview -- 1 if icon/link should be to go to view mode
15091: 
15092: =item *
15093: 
15094: is_course_upload($file,$cnum,$cdom)
15095: 
15096: Used in course context to determine if current file was uploaded to
15097: the course (i.e., would be found in /userfiles/docs on the course's
15098: homeserver.
15099: 
15100:   input: 3 args -- filename (decluttered), course number and course domain.
15101:   output: boolean -- 1 if file was uploaded.
15102: 
15103: =back
15104: 
15105: =head2 Storing/Retreiving Data
15106: 
15107: =over 4
15108: 
15109: =item *
15110: 
15111: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash 
15112: permanently for this url; hashref needs to be given and should be a \%hashname;
15113: the remaining args aren't required and if they aren't passed or are '' they will
15114: be derived from the env (with the exception of $laststore, which is an
15115: optional arg used when a user's submission is stored in grading).
15116: $laststore is $version=$timestamp, where $version is the most recent version
15117: number retrieved for the corresponding $symb in the $namespace db file, and
15118: $timestamp is the timestamp for that transaction (UNIX time).
15119: $laststore is currently only passed when cstore() is called by
15120: structuretags::finalize_storage().
15121: 
15122: =item *
15123: 
15124: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store 
15125: but uses critical subroutine
15126: 
15127: =item *
15128: 
15129: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
15130: all args are optional
15131: 
15132: =item *
15133: 
15134: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
15135: dumps the complete (or key matching regexp) namespace into a hash
15136: ($udom, $uname, $regexp, $range are optional) for a namespace that is
15137: normally &store()ed into
15138: 
15139: $range should be either an integer '100' (give me the first 100
15140:                                            matching records)
15141:               or be  two integers sperated by a - with no spaces
15142:                  '30-50' (give me the 30th through the 50th matching
15143:                           records)
15144: 
15145: 
15146: =item *
15147: 
15148: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
15149: replaces a &store() version of data with a replacement set of data
15150: for a particular resource in a namespace passed in the $storehash hash 
15151: reference. If $tolog is true, the transaction is logged in the courselog
15152: with an action=PUTSTORE.
15153: 
15154: =item *
15155: 
15156: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
15157: works very similar to store/cstore, but all data is stored in a
15158: temporary location and can be reset using tmpreset, $storehash should
15159: be a hash reference, returns nothing on success
15160: 
15161: =item *
15162: 
15163: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
15164: similar to restore, but all data is stored in a temporary location and
15165: can be reset using tmpreset. Returns a hash of values on success,
15166: error string otherwise.
15167: 
15168: =item *
15169: 
15170: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
15171: deltes all keys for $symb form the temporary storage hash.
15172: 
15173: =item *
15174: 
15175: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
15176: reference filled in from namesp ($udom and $uname are optional)
15177: 
15178: =item *
15179: 
15180: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
15181: namesp ($udom and $uname are optional)
15182: 
15183: =item *
15184: 
15185: dump($namespace,$udom,$uname,$regexp,$range) : 
15186: dumps the complete (or key matching regexp) namespace into a hash
15187: ($udom, $uname, $regexp, $range are optional)
15188: 
15189: $range should be either an integer '100' (give me the first 100
15190:                                            matching records)
15191:               or be  two integers sperated by a - with no spaces
15192:                  '30-50' (give me the 30th through the 50th matching
15193:                           records)
15194: =item *
15195: 
15196: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
15197: $store can be a scalar, an array reference, or if the amount to be 
15198: incremented is > 1, a hash reference.
15199: 
15200: ($udom and $uname are optional)
15201: 
15202: =item *
15203: 
15204: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
15205: ($udom and $uname are optional)
15206: 
15207: =item *
15208: 
15209: cput($namespace,$storehash,$udom,$uname) : critical put
15210: ($udom and $uname are optional)
15211: 
15212: =item *
15213: 
15214: newput($namespace,$storehash,$udom,$uname) :
15215: 
15216: Attempts to store the items in the $storehash, but only if they don't
15217: currently exist, if this succeeds you can be certain that you have 
15218: successfully created a new key value pair in the $namespace db.
15219: 
15220: 
15221: Args:
15222:  $namespace: name of database to store values to
15223:  $storehash: hashref to store to the db
15224:  $udom: (optional) domain of user containing the db
15225:  $uname: (optional) name of user caontaining the db
15226: 
15227: Returns:
15228:  'ok' -> succeeded in storing all keys of $storehash
15229:  'key_exists: <key>' -> failed to anything out of $storehash, as at
15230:                         least <key> already existed in the db (other
15231:                         requested keys may also already exist)
15232:  'error: <msg>' -> unable to tie the DB or other error occurred
15233:  'con_lost' -> unable to contact request server
15234:  'refused' -> action was not allowed by remote machine
15235: 
15236: 
15237: =item *
15238: 
15239: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
15240: reference filled in from namesp (encrypts the return communication)
15241: ($udom and $uname are optional)
15242: 
15243: =item *
15244: 
15245: log($udom,$name,$home,$message) : write to permanent log for user; use
15246: critical subroutine
15247: 
15248: =item *
15249: 
15250: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
15251: array reference filled in from namespace found in domain level on either
15252: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
15253: 
15254: =item *
15255: 
15256: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
15257: domain level either on specified domain server ($uhome) or primary domain 
15258: server ($udom and $uhome are optional)
15259: 
15260: =item * 
15261: 
15262: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
15263: for: authentication, language, quotas, timezone, date locale, and portal URL in
15264: the target domain.
15265: 
15266: May also include additional key => value pairs for the following groups:
15267: 
15268: =over
15269: 
15270: =item
15271: disk quotas (MB allocated by default to portfolios and authoring spaces).
15272: 
15273: =over
15274: 
15275: =item defaultquota, authorquota
15276: 
15277: =back
15278: 
15279: =item
15280: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
15281: portfolio for users).
15282: 
15283: =over
15284: 
15285: =item
15286: aboutme, blog, webdav, portfolio
15287: 
15288: =back
15289: 
15290: =item
15291: requestcourses: ability to request courses, and how requests are processed.
15292: 
15293: =over
15294: 
15295: =item
15296: official, unofficial, community, textbook
15297: 
15298: =back
15299: 
15300: =item
15301: inststatus: types of institutional affiliation, and order in which they are displayed.
15302: 
15303: =over
15304: 
15305: =item
15306: inststatustypes, inststatusorder, inststatusguest
15307: 
15308: =back
15309: 
15310: =item
15311: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
15312: for course's uploaded content.
15313: 
15314: =over
15315: 
15316: =item
15317: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
15318: communityquota, textbookquota
15319: 
15320: =back
15321: 
15322: =item
15323: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
15324: on your servers.
15325: 
15326: =over
15327: 
15328: =item
15329: remotesessions, hostedsessions
15330: 
15331: =back
15332: 
15333: =back
15334: 
15335: In cases where a domain coordinator has never used the "Set Domain Configuration"
15336: utility to create a configuration.db file on a domain's primary library server
15337: only the following domain defaults: auth_def, auth_arg_def, lang_def
15338: -- corresponding values are authentication type (internal, krb4, krb5,
15339: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
15340: will be available. Values are retrieved from cache (if current), unless the
15341: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
15342: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
15343: 
15344: Typical usage:
15345: 
15346: %domdefaults = &get_domain_defaults($target_domain);
15347: 
15348: =back
15349: 
15350: =head2 Network Status Functions
15351: 
15352: =over 4
15353: 
15354: =item *
15355: 
15356: dirlist() : return directory list based on URI (first arg).
15357: 
15358: Inputs: 1 required, 5 optional.
15359: 
15360: =over
15361: 
15362: =item 
15363: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
15364: 
15365: =item
15366: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
15367: 
15368: =item
15369: $username -  username of user/course to be listed. Extracted from $uri if absent. 
15370: 
15371: =item
15372: $getpropath - boolean: 1 if prepend path using &propath(). 
15373: 
15374: =item
15375: $getuserdir - boolean: 1 if prepend path for "userfiles".
15376: 
15377: =item 
15378: $alternateRoot - path to prepend in place of path from $uri.
15379: 
15380: =back
15381: 
15382: Returns: Array of up to two items.
15383: 
15384: =over
15385: 
15386: a reference to an array of files/subdirectories
15387: 
15388: =over
15389: 
15390: Each element in the array of files/subdirectories is a & separated list of
15391: item name and the result of running stat on the item.  If dirlist was requested
15392: for a file instead of a directory, the item name will be ''. For a directory 
15393: listing, if the item is a metadata file, the element will end &N&M 
15394: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
15395: default copyright set (1).  
15396: 
15397: =back
15398: 
15399: a scalar containing error condition (if encountered).
15400: 
15401: =over
15402: 
15403: =item 
15404: no_host (no homeserver identified for $username:$domain).
15405: 
15406: =item 
15407: no_such_host (server contacted for listing not identified as valid host).
15408: 
15409: =item 
15410: con_lost (connection to remote server failed).
15411: 
15412: =item 
15413: refused (invalid $username:$domain received on lond side).
15414: 
15415: =item 
15416: no_such_dir (directory at specified path on lond side does not exist). 
15417: 
15418: =item 
15419: empty (directory at specified path on lond side is empty).
15420: 
15421: =over
15422: 
15423: This is currently not encountered because the &ls3, &ls2, 
15424: &ls (_handler) routines on the lond side do not filter out
15425: . and .. from a directory listing. 
15426: 
15427: =back
15428: 
15429: =back
15430: 
15431: =back
15432: 
15433: =item *
15434: 
15435: spareserver() : find server with least workload from spare.tab
15436: 
15437: 
15438: =item *
15439: 
15440: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
15441: if there is no corresponding loncapa host.
15442: 
15443: =back
15444: 
15445: 
15446: =head2 Apache Request
15447: 
15448: =over 4
15449: 
15450: =item *
15451: 
15452: ssi($url,%hash) : server side include, does a complete request cycle on url to
15453: localhost, posts hash
15454: 
15455: =back
15456: 
15457: =head2 Data to String to Data
15458: 
15459: =over 4
15460: 
15461: =item *
15462: 
15463: hash2str(%hash) : convert a hash into a string complete with escaping and '='
15464: and '&' separators, supports elements that are arrayrefs and hashrefs
15465: 
15466: =item *
15467: 
15468: hashref2str($hashref) : convert a hashref into a string complete with
15469: escaping and '=' and '&' separators, supports elements that are
15470: arrayrefs and hashrefs
15471: 
15472: =item *
15473: 
15474: arrayref2str($arrayref) : convert an arrayref into a string complete
15475: with escaping and '&' separators, supports elements that are arrayrefs
15476: and hashrefs
15477: 
15478: =item *
15479: 
15480: str2hash($string) : convert string to hash using unescaping and
15481: splitting on '=' and '&', supports elements that are arrayrefs and
15482: hashrefs
15483: 
15484: =item *
15485: 
15486: str2array($string) : convert string to hash using unescaping and
15487: splitting on '&', supports elements that are arrayrefs and hashrefs
15488: 
15489: =back
15490: 
15491: =head2 Logging Routines
15492: 
15493: 
15494: These routines allow one to make log messages in the lonnet.log and
15495: lonnet.perm logfiles.
15496: 
15497: =over 4
15498: 
15499: =item *
15500: 
15501: logtouch() : make sure the logfile, lonnet.log, exists
15502: 
15503: =item *
15504: 
15505: logthis() : append message to the normal lonnet.log file, it gets
15506: preiodically rolled over and deleted.
15507: 
15508: =item *
15509: 
15510: logperm() : append a permanent message to lonnet.perm.log, this log
15511: file never gets deleted by any automated portion of the system, only
15512: messages of critical importance should go in here.
15513: 
15514: 
15515: =back
15516: 
15517: =head2 General File Helper Routines
15518: 
15519: =over 4
15520: 
15521: =item *
15522: 
15523: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
15524: (a) files in /uploaded
15525:   (i) If a local copy of the file exists - 
15526:       compares modification date of local copy with last-modified date for 
15527:       definitive version stored on home server for course. If local copy is 
15528:       stale, requests a new version from the home server and stores it. 
15529:       If the original has been removed from the home server, then local copy 
15530:       is unlinked.
15531:   (ii) If local copy does not exist -
15532:       requests the file from the home server and stores it. 
15533:   
15534:   If $caller is 'uploadrep':  
15535:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
15536:     for request for files originally uploaded via DOCS. 
15537:      - returns 'ok' if fresh local copy now available, -1 otherwise.
15538:   
15539:   Otherwise:
15540:      This indicates a call from the content generation phase of the request.
15541:      -  returns the entire contents of the file or -1.
15542:      
15543: (b) files in /res
15544:    - returns the entire contents of a file or -1; 
15545:    it properly subscribes to and replicates the file if neccessary.
15546: 
15547: 
15548: =item *
15549: 
15550: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
15551:                   reference
15552: 
15553: returns either a stat() list of data about the file or an empty list
15554: if the file doesn't exist or couldn't find out about it (connection
15555: problems or user unknown)
15556: 
15557: =item *
15558: 
15559: filelocation($dir,$file) : returns file system location of a file
15560: based on URI; meant to be "fairly clean" absolute reference, $dir is a
15561: directory that relative $file lookups are to looked in ($dir of /a/dir
15562: and a file of ../bob will become /a/bob)
15563: 
15564: =item *
15565: 
15566: hreflocation($dir,$file) : returns file system location or a URL; same as
15567: filelocation except for hrefs
15568: 
15569: =item *
15570: 
15571: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
15572: also removes beginning /home/httpd/html unless /priv/ follows it.
15573: 
15574: =back
15575: 
15576: =head2 Usererfile file routines (/uploaded*)
15577: 
15578: =over 4
15579: 
15580: =item *
15581: 
15582: userfileupload(): main rotine for putting a file in a user or course's
15583:                   filespace, arguments are,
15584: 
15585:  formname - required - this is the name of the element in $env where the
15586:            filename, and the contents of the file to create/modifed exist
15587:            the filename is in $env{'form.'.$formname.'.filename'} and the
15588:            contents of the file is located in $env{'form.'.$formname}
15589:  context - if coursedoc, store the file in the course of the active role
15590:              of the current user; 
15591:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
15592:            if 'canceloverwrite': delete file in tmp/overwrites directory
15593:  subdir - required - subdirectory to put the file in under ../userfiles/
15594:          if undefined, it will be placed in "unknown"
15595: 
15596:  (This routine calls clean_filename() to remove any dangerous
15597:  characters from the filename, and then calls finuserfileupload() to
15598:  complete the transaction)
15599: 
15600:  returns either the url of the uploaded file (/uploaded/....) if successful
15601:  and /adm/notfound.html if unsuccessful
15602: 
15603: =item *
15604: 
15605: clean_filename(): routine for cleaing a filename up for storage in
15606:                  userfile space, argument is:
15607: 
15608:  filename - proposed filename
15609: 
15610: returns: the new clean filename
15611: 
15612: =item *
15613: 
15614: finishuserfileupload(): routine that creates and sends the file to
15615: userspace, probably shouldn't be called directly
15616: 
15617:   docuname: username or courseid of destination for the file
15618:   docudom: domain of user/course of destination for the file
15619:   formname: same as for userfileupload()
15620:   fname: filename (including subdirectories) for the file
15621:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
15622:           if hashref, and context is scantron, will convert csv format to standard format
15623:   allfiles: reference to hash used to store objects found by parser
15624:   codebase: reference to hash used for codebases of java objects found by parser
15625:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
15626:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
15627:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
15628:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
15629:   context: if 'overwrite', will move the uploaded file from its temporary location to
15630:             userfiles to facilitate overwriting a previously uploaded file with same name.
15631:   mimetype: reference to scalar to accommodate mime type determined
15632:             from File::MMagic if $parser = parse.
15633: 
15634:  returns either the url of the uploaded file (/uploaded/....) if successful
15635:  and /adm/notfound.html if unsuccessful (or an error message if context 
15636:  was 'overwrite').
15637:  
15638: 
15639: =item *
15640: 
15641: renameuserfile(): renames an existing userfile to a new name
15642: 
15643:   Args:
15644:    docuname: username or courseid of destination for the file
15645:    docudom: domain of user/course of destination for the file
15646:    old: current file name (including any subdirs under userfiles)
15647:    new: desired file name (including any subdirs under userfiles)
15648: 
15649: =item *
15650: 
15651: mkdiruserfile(): creates a directory is a userfiles dir
15652: 
15653:   Args:
15654:    docuname: username or courseid of destination for the file
15655:    docudom: domain of user/course of destination for the file
15656:    dir: dir to create (including any subdirs under userfiles)
15657: 
15658: =item *
15659: 
15660: removeuserfile(): removes a file that exists in userfiles
15661: 
15662:   Args:
15663:    docuname: username or courseid of destination for the file
15664:    docudom: domain of user/course of destination for the file
15665:    fname: filname to delete (including any subdirs under userfiles)
15666: 
15667: =item *
15668: 
15669: removeuploadedurl(): convience function for removeuserfile()
15670: 
15671:   Args:
15672:    url:  a full /uploaded/... url to delete
15673: 
15674: =item * 
15675: 
15676: get_portfile_permissions():
15677:   Args:
15678:     domain: domain of user or course contain the portfolio files
15679:     user: name of user or num of course contain the portfolio files
15680:   Returns:
15681:     hashref of a dump of the proper file_permissions.db
15682:    
15683: 
15684: =item * 
15685: 
15686: get_access_controls():
15687: 
15688: Args:
15689:   current_permissions: the hash ref returned from get_portfile_permissions()
15690:   group: (optional) the group you want the files associated with
15691:   file: (optional) the file you want access info on
15692: 
15693: Returns:
15694:     a hash (keys are file names) of hashes containing
15695:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
15696:         values are XML containing access control settings (see below) 
15697: 
15698: Internal notes:
15699: 
15700:  access controls are stored in file_permissions.db as key=value pairs.
15701:     key -> path to file/file_name\0uniqueID:scope_end_start
15702:         where scope -> public,guest,course,group,domains or users.
15703:               end -> UNIX time for end of access (0 -> no end date)
15704:               start -> UNIX time for start of access
15705: 
15706:     value -> XML description of access control
15707:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
15708:             <start></start>
15709:             <end></end>
15710: 
15711:             <password></password>  for scope type = guest
15712: 
15713:             <domain></domain>     for scope type = course or group
15714:             <number></number>
15715:             <roles id="">
15716:              <role></role>
15717:              <access></access>
15718:              <section></section>
15719:              <group></group>
15720:             </roles>
15721: 
15722:             <dom></dom>         for scope type = domains
15723: 
15724:             <users>             for scope type = users
15725:              <user>
15726:               <uname></uname>
15727:               <udom></udom>
15728:              </user>
15729:             </users>
15730:            </scope> 
15731:               
15732:  Access data is also aggregated for each file in an additional key=value pair:
15733:  key -> path to file/file_name\0accesscontrol 
15734:  value -> reference to hash
15735:           hash contains key = value pairs
15736:           where key = uniqueID:scope_end_start
15737:                 value = UNIX time record was last updated
15738: 
15739:           Used to improve speed of look-ups of access controls for each file.  
15740:  
15741:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
15742: 
15743: =item *
15744: 
15745: modify_access_controls():
15746: 
15747: Modifies access controls for a portfolio file
15748: Args
15749: 1. file name
15750: 2. reference to hash of required changes,
15751: 3. domain
15752: 4. username
15753:   where domain,username are the domain of the portfolio owner 
15754:   (either a user or a course) 
15755: 
15756: Returns:
15757: 1. result of additions or updates ('ok' or 'error', with error message). 
15758: 2. result of deletions ('ok' or 'error', with error message).
15759: 3. reference to hash of any new or updated access controls.
15760: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
15761:    key = integer (inbound ID)
15762:    value = uniqueID
15763: 
15764: =item *
15765: 
15766: get_timebased_id():
15767: 
15768: Attempts to get a unique timestamp-based suffix for use with items added to a
15769: course via the Course Editor (e.g., folders, composite pages,
15770: group bulletin boards).
15771: 
15772: Args: (first three required; six others optional)
15773: 
15774: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
15775:    docssequence, or name of group
15776: 
15777: 2. keyid (alphanumeric): name of temporary locking key in hash,
15778:    e.g., num, boardids
15779: 
15780: 3. namespace: name of gdbm file used to store suffixes already assigned;
15781:    file will be named nohist_namespace.db
15782: 
15783: 4. cdom: domain of course; default is current course domain from %env
15784: 
15785: 5. cnum: course number; default is current course number from %env
15786: 
15787: 6. idtype: set to concat if an additional digit is to be appended to the
15788:    unix timestamp to form the suffix, if the plain timestamp is already
15789:    in use.  Default is to not do this, but simply increment the unix
15790:    timestamp by 1 until a unique key is obtained.
15791: 
15792: 7. who: holder of locking key; defaults to user:domain for user.
15793: 
15794: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
15795:    retrying); default is 3.
15796: 
15797: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
15798: 
15799: Returns:
15800: 
15801: 1. suffix obtained (numeric)
15802: 
15803: 2. result of deleting locking key (ok if deleted, or lock never obtained)
15804: 
15805: 3. error: contains (localized) error message if an error occurred.
15806: 
15807: 
15808: =back
15809: 
15810: =head2 HTTP Helper Routines
15811: 
15812: =over 4
15813: 
15814: =item *
15815: 
15816: escape() : unpack non-word characters into CGI-compatible hex codes
15817: 
15818: =item *
15819: 
15820: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
15821: 
15822: =back
15823: 
15824: =head1 PRIVATE SUBROUTINES
15825: 
15826: =head2 Underlying communication routines (Shouldn't call)
15827: 
15828: =over 4
15829: 
15830: =item *
15831: 
15832: subreply() : tries to pass a message to lonc, returns con_lost if incapable
15833: 
15834: =item *
15835: 
15836: reply() : uses subreply to send a message to remote machine, logs all failures
15837: 
15838: =item *
15839: 
15840: critical() : passes a critical message to another server; if cannot
15841: get through then place message in connection buffer directory and
15842: returns con_delayed, if incapable of saving message, returns
15843: con_failed
15844: 
15845: =item *
15846: 
15847: reconlonc() : tries to reconnect lonc client processes.
15848: 
15849: =back
15850: 
15851: =head2 Resource Access Logging
15852: 
15853: =over 4
15854: 
15855: =item *
15856: 
15857: flushcourselogs() : flush (save) buffer logs and access logs
15858: 
15859: =item *
15860: 
15861: courselog($what) : save message for course in hash
15862: 
15863: =item *
15864: 
15865: courseacclog($what) : save message for course using &courselog().  Perform
15866: special processing for specific resource types (problems, exams, quizzes, etc).
15867: 
15868: =item *
15869: 
15870: goodbye() : flush course logs and log shutting down; it is called in srm.conf
15871: as a PerlChildExitHandler
15872: 
15873: =back
15874: 
15875: =head2 Other
15876: 
15877: =over 4
15878: 
15879: =item *
15880: 
15881: symblist($mapname,%newhash) : update symbolic storage links
15882: 
15883: =back
15884: 
15885: =cut
15886: 

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