File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1165: download - view: text, annotated - select for diffs
Tue Apr 24 20:31:59 2012 UTC (12 years, 2 months ago) by droeschl
Branches: MAIN
CVS tags: HEAD
Removed unused $range parameter from dump_dom because it's going to be
eliminated in dump and lond's dump_with_regexp shortly.
Also, refactoring of dump_dom to avoid unnecessary copy of hash.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1165 2012/04/24 20:31:59 droeschl 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: 
   78: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
   79:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
   80:             %managerstab);
   81: 
   82: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
   83:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
   84:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
   85:     %courseownerbuf, %coursetypebuf,$locknum);
   86: 
   87: use IO::Socket;
   88: use GDBM_File;
   89: use HTML::LCParser;
   90: use Fcntl qw(:flock);
   91: use Storable qw(thaw nfreeze);
   92: use Time::HiRes qw( gettimeofday tv_interval );
   93: use Cache::Memcached;
   94: use Digest::MD5;
   95: use Math::Random;
   96: use File::MMagic;
   97: use LONCAPA qw(:DEFAULT :match);
   98: use LONCAPA::Configuration;
   99: use LONCAPA::lonmetadata;
  100: 
  101: use File::Copy;
  102: 
  103: my $readit;
  104: my $max_connection_retries = 10;     # Or some such value.
  105: 
  106: require Exporter;
  107: 
  108: our @ISA = qw (Exporter);
  109: our @EXPORT = qw(%env);
  110: 
  111: 
  112: # --------------------------------------------------------------------- Logging
  113: {
  114:     my $logid;
  115:     sub instructor_log {
  116: 	my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
  117:         if (($cnum eq '') || ($cdom eq '')) {
  118:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  119:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  120:         }
  121: 	$logid++;
  122:         my $now = time();
  123: 	my $id=$now.'00000'.$$.'00000'.$logid;
  124: 	return &Apache::lonnet::put('nohist_'.$hash_name,
  125: 				    { $id => {
  126: 					'exe_uname' => $env{'user.name'},
  127: 					'exe_udom'  => $env{'user.domain'},
  128: 					'exe_time'  => $now,
  129: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
  130: 					'delflag'   => $delflag,
  131: 					'logentry'  => $storehash,
  132: 					'uname'     => $uname,
  133: 					'udom'      => $udom,
  134: 				    }
  135: 				  },$cdom,$cnum);
  136:     }
  137: }
  138: 
  139: sub logtouch {
  140:     my $execdir=$perlvar{'lonDaemons'};
  141:     unless (-e "$execdir/logs/lonnet.log") {	
  142: 	open(my $fh,">>$execdir/logs/lonnet.log");
  143: 	close $fh;
  144:     }
  145:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  146:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  147: }
  148: 
  149: sub logthis {
  150:     my $message=shift;
  151:     my $execdir=$perlvar{'lonDaemons'};
  152:     my $now=time;
  153:     my $local=localtime($now);
  154:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
  155: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
  156: 	print $fh $logstring;
  157: 	close($fh);
  158:     }
  159:     return 1;
  160: }
  161: 
  162: sub logperm {
  163:     my $message=shift;
  164:     my $execdir=$perlvar{'lonDaemons'};
  165:     my $now=time;
  166:     my $local=localtime($now);
  167:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
  168: 	print $fh "$now:$message:$local\n";
  169: 	close($fh);
  170:     }
  171:     return 1;
  172: }
  173: 
  174: sub create_connection {
  175:     my ($hostname,$lonid) = @_;
  176:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  177: 				     Type    => SOCK_STREAM,
  178: 				     Timeout => 10);
  179:     return 0 if (!$client);
  180:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
  181:     my $result = <$client>;
  182:     chomp($result);
  183:     return 1 if ($result eq 'done');
  184:     return 0;
  185: }
  186: 
  187: sub get_server_timezone {
  188:     my ($cnum,$cdom) = @_;
  189:     my $home=&homeserver($cnum,$cdom);
  190:     if ($home ne 'no_host') {
  191:         my $cachetime = 24*3600;
  192:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
  193:         if (defined($cached)) {
  194:             return $timezone;
  195:         } else {
  196:             my $timezone = &reply('servertimezone',$home);
  197:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
  198:         }
  199:     }
  200: }
  201: 
  202: sub get_server_distarch {
  203:     my ($lonhost,$ignore_cache) = @_;
  204:     if (defined($lonhost)) {
  205:         if (!defined(&hostname($lonhost))) {
  206:             return;
  207:         }
  208:         my $cachetime = 12*3600;
  209:         if (!$ignore_cache) {
  210:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
  211:             if (defined($cached)) {
  212:                 return $distarch;
  213:             }
  214:         }
  215:         my $rep = &reply('serverdistarch',$lonhost);
  216:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
  217:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
  218:                 $rep eq '') {
  219:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
  220:         }
  221:     }
  222:     return;
  223: }
  224: 
  225: sub get_server_loncaparev {
  226:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
  227:     if (defined($lonhost)) {
  228:         if (!defined(&hostname($lonhost))) {
  229:             undef($lonhost);
  230:         }
  231:     }
  232:     if (!defined($lonhost)) {
  233:         if (defined(&domain($dom,'primary'))) {
  234:             $lonhost=&domain($dom,'primary');
  235:             if ($lonhost eq 'no_host') {
  236:                 undef($lonhost);
  237:             }
  238:         }
  239:     }
  240:     if (defined($lonhost)) {
  241:         my $cachetime = 12*3600;
  242:         if (!$ignore_cache) {
  243:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
  244:             if (defined($cached)) {
  245:                 return $loncaparev;
  246:             }
  247:         }
  248:         my ($answer,$loncaparev);
  249:         my @ids=&current_machine_ids();
  250:         if (grep(/^\Q$lonhost\E$/,@ids)) {
  251:             $answer = $perlvar{'lonVersion'};
  252:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  253:                 $loncaparev = $1;
  254:             }
  255:         } else {
  256:             $answer = &reply('serverloncaparev',$lonhost);
  257:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
  258:                 if ($caller eq 'loncron') {
  259:                     my $ua=new LWP::UserAgent;
  260:                     $ua->timeout(4);
  261:                     my $protocol = $protocol{$lonhost};
  262:                     $protocol = 'http' if ($protocol ne 'https');
  263:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
  264:                     my $request=new HTTP::Request('GET',$url);
  265:                     my $response=$ua->request($request);
  266:                     unless ($response->is_error()) {
  267:                         my $content = $response->content;
  268:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
  269:                             $loncaparev = $1;
  270:                         }
  271:                     }
  272:                 } else {
  273:                     $loncaparev = $loncaparevs{$lonhost};
  274:                 }
  275:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  276:                 $loncaparev = $1;
  277:             }
  278:         }
  279:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
  280:     }
  281: }
  282: 
  283: sub get_server_homeID {
  284:     my ($hostname,$ignore_cache,$caller) = @_;
  285:     unless ($ignore_cache) {
  286:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
  287:         if (defined($cached)) {
  288:             return $serverhomeID;
  289:         }
  290:     }
  291:     my $cachetime = 12*3600;
  292:     my $serverhomeID;
  293:     if ($caller eq 'loncron') { 
  294:         my @machine_ids = &machine_ids($hostname);
  295:         foreach my $id (@machine_ids) {
  296:             my $response = &reply('serverhomeID',$id);
  297:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
  298:                 $serverhomeID = $response;
  299:                 last;
  300:             }
  301:         }
  302:         if ($serverhomeID eq '') {
  303:             $serverhomeID = $machine_ids[-1];
  304:         }
  305:     } else {
  306:         $serverhomeID = $serverhomeIDs{$hostname};
  307:     }
  308:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
  309: }
  310: 
  311: sub get_remote_globals {
  312:     my ($lonhost,$whathash,$ignore_cache) = @_;
  313:     my ($result,%returnhash,%whatneeded);
  314:     if (ref($whathash) eq 'HASH') {
  315:         foreach my $what (sort(keys(%{$whathash}))) {
  316:             my $hashid = $lonhost.'-'.$what;
  317:             my ($response,$cached);
  318:             unless ($ignore_cache) {
  319:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
  320:             }
  321:             if (defined($cached)) {
  322:                 $returnhash{$what} = $response;
  323:             } else {
  324:                 $whatneeded{$what} = 1;
  325:             }
  326:         }
  327:         if (keys(%whatneeded) == 0) {
  328:             $result = 'ok';
  329:         } else {
  330:             my $requested = &freeze_escape(\%whatneeded);
  331:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
  332:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  333:                 ($rep eq 'unknown_cmd')) {
  334:                 $result = $rep;
  335:             } else {
  336:                 $result = 'ok';
  337:                 my @pairs=split(/\&/,$rep);
  338:                 foreach my $item (@pairs) {
  339:                     my ($key,$value)=split(/=/,$item,2);
  340:                     my $what = &unescape($key);
  341:                     my $hashid = $lonhost.'-'.$what;
  342:                     $returnhash{$what}=&thaw_unescape($value);
  343:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
  344:                 }
  345:             }
  346:         }
  347:     }
  348:     return ($result,\%returnhash);
  349: }
  350: 
  351: sub remote_devalidate_cache {
  352:     my ($lonhost,$name,$id) = @_;
  353:     my $response = &reply('devalidatecache:'.&escape($name).':'.&escape($id),$lonhost);
  354:     return $response;
  355: }
  356: 
  357: # -------------------------------------------------- Non-critical communication
  358: sub subreply {
  359:     my ($cmd,$server)=@_;
  360:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  361:     #
  362:     #  With loncnew process trimming, there's a timing hole between lonc server
  363:     #  process exit and the master server picking up the listen on the AF_UNIX
  364:     #  socket.  In that time interval, a lock file will exist:
  365: 
  366:     my $lockfile=$peerfile.".lock";
  367:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  368: 	sleep(1);
  369:     }
  370:     # At this point, either a loncnew parent is listening or an old lonc
  371:     # or loncnew child is listening so we can connect or everything's dead.
  372:     #
  373:     #   We'll give the connection a few tries before abandoning it.  If
  374:     #   connection is not possible, we'll con_lost back to the client.
  375:     #   
  376:     my $client;
  377:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  378: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  379: 				      Type    => SOCK_STREAM,
  380: 				      Timeout => 10);
  381: 	if ($client) {
  382: 	    last;		# Connected!
  383: 	} else {
  384: 	    &create_connection(&hostname($server),$server);
  385: 	}
  386:         sleep(1);		# Try again later if failed connection.
  387:     }
  388:     my $answer;
  389:     if ($client) {
  390: 	print $client "sethost:$server:$cmd\n";
  391: 	$answer=<$client>;
  392: 	if (!$answer) { $answer="con_lost"; }
  393: 	chomp($answer);
  394:     } else {
  395: 	$answer = 'con_lost';	# Failed connection.
  396:     }
  397:     return $answer;
  398: }
  399: 
  400: sub reply {
  401:     my ($cmd,$server)=@_;
  402:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  403:     my $answer=subreply($cmd,$server);
  404:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  405:        &logthis("<font color=\"blue\">WARNING:".
  406:                 " $cmd to $server returned $answer</font>");
  407:     }
  408:     return $answer;
  409: }
  410: 
  411: # ----------------------------------------------------------- Send USR1 to lonc
  412: 
  413: sub reconlonc {
  414:     my ($lonid) = @_;
  415:     my $hostname = &hostname($lonid);
  416:     if ($lonid) {
  417: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  418: 	if ($hostname && -e $peerfile) {
  419: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  420: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  421: 					     Type    => SOCK_STREAM,
  422: 					     Timeout => 10);
  423: 	    if ($client) {
  424: 		print $client ("reset_retries\n");
  425: 		my $answer=<$client>;
  426: 		#reset just this one.
  427: 	    }
  428: 	}
  429: 	return;
  430:     }
  431: 
  432:     &logthis("Trying to reconnect lonc");
  433:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  434:     if (open(my $fh,"<$loncfile")) {
  435: 	my $loncpid=<$fh>;
  436:         chomp($loncpid);
  437:         if (kill 0 => $loncpid) {
  438: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  439:             kill USR1 => $loncpid;
  440:             sleep 1;
  441:          } else {
  442: 	    &logthis(
  443:                "<font color=\"blue\">WARNING:".
  444:                " lonc at pid $loncpid not responding, giving up</font>");
  445:         }
  446:     } else {
  447: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  448:     }
  449: }
  450: 
  451: # ------------------------------------------------------ Critical communication
  452: 
  453: sub critical {
  454:     my ($cmd,$server)=@_;
  455:     unless (&hostname($server)) {
  456:         &logthis("<font color=\"blue\">WARNING:".
  457:                " Critical message to unknown server ($server)</font>");
  458:         return 'no_such_host';
  459:     }
  460:     my $answer=reply($cmd,$server);
  461:     if ($answer eq 'con_lost') {
  462: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
  463: 	my $answer=reply($cmd,$server);
  464:         if ($answer eq 'con_lost') {
  465:             my $now=time;
  466:             my $middlename=$cmd;
  467:             $middlename=substr($middlename,0,16);
  468:             $middlename=~s/\W//g;
  469:             my $dfilename=
  470:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  471:             $dumpcount++;
  472:             {
  473: 		my $dfh;
  474: 		if (open($dfh,">$dfilename")) {
  475: 		    print $dfh "$cmd\n"; 
  476: 		    close($dfh);
  477: 		}
  478:             }
  479:             sleep 2;
  480:             my $wcmd='';
  481:             {
  482: 		my $dfh;
  483: 		if (open($dfh,"<$dfilename")) {
  484: 		    $wcmd=<$dfh>; 
  485: 		    close($dfh);
  486: 		}
  487:             }
  488:             chomp($wcmd);
  489:             if ($wcmd eq $cmd) {
  490: 		&logthis("<font color=\"blue\">WARNING: ".
  491:                          "Connection buffer $dfilename: $cmd</font>");
  492:                 &logperm("D:$server:$cmd");
  493: 	        return 'con_delayed';
  494:             } else {
  495:                 &logthis("<font color=\"red\">CRITICAL:"
  496:                         ." Critical connection failed: $server $cmd</font>");
  497:                 &logperm("F:$server:$cmd");
  498:                 return 'con_failed';
  499:             }
  500:         }
  501:     }
  502:     return $answer;
  503: }
  504: 
  505: # ------------------------------------------- check if return value is an error
  506: 
  507: sub error {
  508:     my ($result) = @_;
  509:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  510: 	if ($2 == 2) { return undef; }
  511: 	return $1;
  512:     }
  513:     return undef;
  514: }
  515: 
  516: sub convert_and_load_session_env {
  517:     my ($lonidsdir,$handle)=@_;
  518:     my @profile;
  519:     {
  520: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  521: 	if (!$opened) {
  522: 	    return 0;
  523: 	}
  524: 	flock($idf,LOCK_SH);
  525: 	@profile=<$idf>;
  526: 	close($idf);
  527:     }
  528:     my %temp_env;
  529:     foreach my $line (@profile) {
  530: 	if ($line !~ m/=/) {
  531: 	    return 0;
  532: 	}
  533: 	chomp($line);
  534: 	my ($envname,$envvalue)=split(/=/,$line,2);
  535: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  536:     }
  537:     unlink("$lonidsdir/$handle.id");
  538:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  539: 	    0640)) {
  540: 	%disk_env = %temp_env;
  541: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  542: 	untie(%disk_env);
  543:     }
  544:     return 1;
  545: }
  546: 
  547: # ------------------------------------------- Transfer profile into environment
  548: my $env_loaded;
  549: sub transfer_profile_to_env {
  550:     my ($lonidsdir,$handle,$force_transfer) = @_;
  551:     if (!$force_transfer && $env_loaded) { return; } 
  552: 
  553:     if (!defined($lonidsdir)) {
  554: 	$lonidsdir = $perlvar{'lonIDsDir'};
  555:     }
  556:     if (!defined($handle)) {
  557:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  558:     }
  559: 
  560:     my $convert;
  561:     {
  562:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  563: 	if (!$opened) {
  564: 	    return;
  565: 	}
  566: 	flock($idf,LOCK_SH);
  567: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  568: 		&GDBM_READER(),0640)) {
  569: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  570: 	    untie(%disk_env);
  571: 	} else {
  572: 	    $convert = 1;
  573: 	}
  574:     }
  575:     if ($convert) {
  576: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  577: 	    &logthis("Failed to load session, or convert session.");
  578: 	}
  579:     }
  580: 
  581:     my %remove;
  582:     while ( my $envname = each(%env) ) {
  583:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  584:             if ($time < time-300) {
  585:                 $remove{$key}++;
  586:             }
  587:         }
  588:     }
  589: 
  590:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  591:     $env_loaded=1;
  592:     foreach my $expired_key (keys(%remove)) {
  593:         &delenv($expired_key);
  594:     }
  595: }
  596: 
  597: # ---------------------------------------------------- Check for valid session 
  598: sub check_for_valid_session {
  599:     my ($r,$name) = @_;
  600:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  601:     if ($name eq '') {
  602:         $name = 'lonID';
  603:     }
  604:     my $lonid=$cookies{$name};
  605:     return undef if (!$lonid);
  606: 
  607:     my $handle=&LONCAPA::clean_handle($lonid->value);
  608:     my $lonidsdir;
  609:     if ($name eq 'lonDAV') {
  610:         $lonidsdir=$r->dir_config('lonDAVsessDir');
  611:     } else {
  612:         $lonidsdir=$r->dir_config('lonIDsDir');
  613:     }
  614:     return undef if (!-e "$lonidsdir/$handle.id");
  615: 
  616:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  617:     return undef if (!$opened);
  618: 
  619:     flock($idf,LOCK_SH);
  620:     my %disk_env;
  621:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  622: 	    &GDBM_READER(),0640)) {
  623: 	return undef;	
  624:     }
  625: 
  626:     if (!defined($disk_env{'user.name'})
  627: 	|| !defined($disk_env{'user.domain'})) {
  628: 	return undef;
  629:     }
  630:     return $handle;
  631: }
  632: 
  633: sub timed_flock {
  634:     my ($file,$lock_type) = @_;
  635:     my $failed=0;
  636:     eval {
  637: 	local $SIG{__DIE__}='DEFAULT';
  638: 	local $SIG{ALRM}=sub {
  639: 	    $failed=1;
  640: 	    die("failed lock");
  641: 	};
  642: 	alarm(13);
  643: 	flock($file,$lock_type);
  644: 	alarm(0);
  645:     };
  646:     if ($failed) {
  647: 	return undef;
  648:     } else {
  649: 	return 1;
  650:     }
  651: }
  652: 
  653: # ---------------------------------------------------------- Append Environment
  654: 
  655: sub appenv {
  656:     my ($newenv,$roles) = @_;
  657:     if (ref($newenv) eq 'HASH') {
  658:         foreach my $key (keys(%{$newenv})) {
  659:             my $refused = 0;
  660: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  661:                 $refused = 1;
  662:                 if (ref($roles) eq 'ARRAY') {
  663:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
  664:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  665:                         $refused = 0;
  666:                     }
  667:                 }
  668:             }
  669:             if ($refused) {
  670:                 &logthis("<font color=\"blue\">WARNING: ".
  671:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  672:                          .'</font>');
  673: 	        delete($newenv->{$key});
  674:             } else {
  675:                 $env{$key}=$newenv->{$key};
  676:             }
  677:         }
  678:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
  679:         if ($opened
  680: 	    && &timed_flock($env_file,LOCK_EX)
  681: 	    &&
  682: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  683: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  684: 	    while (my ($key,$value) = each(%{$newenv})) {
  685: 	        $disk_env{$key} = $value;
  686: 	    }
  687: 	    untie(%disk_env);
  688:         }
  689:     }
  690:     return 'ok';
  691: }
  692: # ----------------------------------------------------- Delete from Environment
  693: 
  694: sub delenv {
  695:     my ($delthis,$regexp,$roles) = @_;
  696:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
  697:         my $refused = 1;
  698:         if (ref($roles) eq 'ARRAY') {
  699:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
  700:             if (grep(/^\Q$role\E$/,@{$roles})) {
  701:                 $refused = 0;
  702:             }
  703:         }
  704:         if ($refused) {
  705:             &logthis("<font color=\"blue\">WARNING: ".
  706:                      "Attempt to delete from environment ".$delthis);
  707:             return 'error';
  708:         }
  709:     }
  710:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  711:     if ($opened
  712: 	&& &timed_flock($env_file,LOCK_EX)
  713: 	&&
  714: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  715: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  716: 	foreach my $key (keys(%disk_env)) {
  717: 	    if ($regexp) {
  718:                 if ($key=~/^$delthis/) {
  719:                     delete($env{$key});
  720:                     delete($disk_env{$key});
  721:                 } 
  722:             } else {
  723:                 if ($key=~/^\Q$delthis\E/) {
  724: 		    delete($env{$key});
  725: 		    delete($disk_env{$key});
  726: 	        }
  727:             }
  728: 	}
  729: 	untie(%disk_env);
  730:     }
  731:     return 'ok';
  732: }
  733: 
  734: sub get_env_multiple {
  735:     my ($name) = @_;
  736:     my @values;
  737:     if (defined($env{$name})) {
  738:         # exists is it an array
  739:         if (ref($env{$name})) {
  740:             @values=@{ $env{$name} };
  741:         } else {
  742:             $values[0]=$env{$name};
  743:         }
  744:     }
  745:     return(@values);
  746: }
  747: 
  748: # ------------------------------------------------------------------- Locking
  749: 
  750: sub set_lock {
  751:     my ($text)=@_;
  752:     $locknum++;
  753:     my $id=$$.'-'.$locknum;
  754:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  755:              'session.lock.'.$id => $text});
  756:     return $id;
  757: }
  758: 
  759: sub get_locks {
  760:     my $num=0;
  761:     my %texts=();
  762:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  763:        if ($lock=~/\w/) {
  764:           $num++;
  765:           $texts{$lock}=$env{'session.lock.'.$lock};
  766:        }
  767:    }
  768:    return ($num,%texts);
  769: }
  770: 
  771: sub remove_lock {
  772:     my ($id)=@_;
  773:     my $newlocks='';
  774:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  775:        if (($lock=~/\w/) && ($lock ne $id)) {
  776:           $newlocks.=','.$lock;
  777:        }
  778:     }
  779:     &appenv({'session.locks' => $newlocks});
  780:     &delenv('session.lock.'.$id);
  781: }
  782: 
  783: sub remove_all_locks {
  784:     my $activelocks=$env{'session.locks'};
  785:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  786:        if ($lock=~/\w/) {
  787:           &remove_lock($lock);
  788:        }
  789:     }
  790: }
  791: 
  792: 
  793: # ------------------------------------------ Find out current server userload
  794: sub userload {
  795:     my $numusers=0;
  796:     {
  797: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  798: 	my $filename;
  799: 	my $curtime=time;
  800: 	while ($filename=readdir(LONIDS)) {
  801: 	    next if ($filename eq '.' || $filename eq '..');
  802: 	    next if ($filename =~ /publicuser_\d+\.id/);
  803: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  804: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  805: 	}
  806: 	closedir(LONIDS);
  807:     }
  808:     my $userloadpercent=0;
  809:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  810:     if ($maxuserload) {
  811: 	$userloadpercent=100*$numusers/$maxuserload;
  812:     }
  813:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  814:     return $userloadpercent;
  815: }
  816: 
  817: # ------------------------------ Find server with least workload from spare.tab
  818: 
  819: sub spareserver {
  820:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
  821:     my $spare_server;
  822:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  823:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  824:                                                      :  $userloadpercent;
  825:     my ($uint_dom,$remotesessions);
  826:     if (($udom ne '') && (&domain($udom) ne '')) {
  827:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
  828:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
  829:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
  830:         $remotesessions = $udomdefaults{'remotesessions'};
  831:     }
  832:     my $spareshash = &this_host_spares($udom);
  833:     if (ref($spareshash) eq 'HASH') {
  834:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  835:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  836:                 if ($uint_dom) {
  837:                     next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
  838:                                                  $try_server));
  839:                 }
  840: 	        ($spare_server, $lowest_load) =
  841: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
  842:             }
  843:         }
  844: 
  845:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
  846: 
  847:         if (!$found_server) {
  848:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
  849: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
  850:                     if ($uint_dom) {
  851:                         next unless (&spare_can_host($udom,$uint_dom,
  852:                                                      $remotesessions,$try_server));
  853:                     }
  854: 	            ($spare_server, $lowest_load) =
  855: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
  856:                 }
  857: 	    }
  858:         }
  859:     }
  860: 
  861:     if (!$want_server_name) {
  862:         my $protocol = 'http';
  863:         if ($protocol{$spare_server} eq 'https') {
  864:             $protocol = $protocol{$spare_server};
  865:         }
  866:         if (defined($spare_server)) {
  867:             my $hostname = &hostname($spare_server);
  868:             if (defined($hostname)) {
  869: 	        $spare_server = $protocol.'://'.$hostname;
  870:             }
  871:         }
  872:     }
  873:     return $spare_server;
  874: }
  875: 
  876: sub compare_server_load {
  877:     my ($try_server, $spare_server, $lowest_load) = @_;
  878: 
  879:     my $loadans     = &reply('load',    $try_server);
  880:     my $userloadans = &reply('userload',$try_server);
  881: 
  882:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  883: 	return ($spare_server, $lowest_load); #didn't get a number from the server
  884:     }
  885: 
  886:     my $load;
  887:     if ($loadans =~ /\d/) {
  888: 	if ($userloadans =~ /\d/) {
  889: 	    #both are numbers, pick the bigger one
  890: 	    $load = ($loadans > $userloadans) ? $loadans 
  891: 		                              : $userloadans;
  892: 	} else {
  893: 	    $load = $loadans;
  894: 	}
  895:     } else {
  896: 	$load = $userloadans;
  897:     }
  898: 
  899:     if (($load =~ /\d/) && ($load < $lowest_load)) {
  900: 	$spare_server = $try_server;
  901: 	$lowest_load  = $load;
  902:     }
  903:     return ($spare_server,$lowest_load);
  904: }
  905: 
  906: # --------------------------- ask offload servers if user already has a session
  907: sub find_existing_session {
  908:     my ($udom,$uname) = @_;
  909:     my $spareshash = &this_host_spares($udom);
  910:     if (ref($spareshash) eq 'HASH') {
  911:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  912:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  913:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
  914:             }
  915:         }
  916:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
  917:             foreach my $try_server (@{ $spareshash->{'default'} }) {
  918:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
  919:             }
  920:         }
  921:     }
  922:     return;
  923: }
  924: 
  925: # -------------------------------- ask if server already has a session for user
  926: sub has_user_session {
  927:     my ($lonid,$udom,$uname) = @_;
  928:     my $result = &reply(join(':','userhassession',
  929: 			     map {&escape($_)} ($udom,$uname)),$lonid);
  930:     return 1 if ($result eq 'ok');
  931: 
  932:     return 0;
  933: }
  934: 
  935: # --------- determine least loaded server in a user's domain which allows login
  936: 
  937: sub choose_server {
  938:     my ($udom,$checkloginvia) = @_;
  939:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
  940:     my %servers = &get_servers($udom);
  941:     my $lowest_load = 30000;
  942:     my ($login_host,$hostname,$portal_path,$isredirect);
  943:     foreach my $lonhost (keys(%servers)) {
  944:         my $loginvia;
  945:         if ($checkloginvia) {
  946:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
  947:             if ($loginvia) {
  948:                 my ($server,$path) = split(/:/,$loginvia);
  949:                 ($login_host, $lowest_load) =
  950:                     &compare_server_load($server, $login_host, $lowest_load);
  951:                 if ($login_host eq $server) {
  952:                     $portal_path = $path;
  953:                     $isredirect = 1;
  954:                 }
  955:             } else {
  956:                 ($login_host, $lowest_load) =
  957:                     &compare_server_load($lonhost, $login_host, $lowest_load);
  958:                 if ($login_host eq $lonhost) {
  959:                     $portal_path = '';
  960:                     $isredirect = ''; 
  961:                 }
  962:             }
  963:         } else {
  964:             ($login_host, $lowest_load) =
  965:                 &compare_server_load($lonhost, $login_host, $lowest_load);
  966:         }
  967:     }
  968:     if ($login_host ne '') {
  969:         $hostname = &hostname($login_host);
  970:     }
  971:     return ($login_host,$hostname,$portal_path,$isredirect);
  972: }
  973: 
  974: # --------------------------------------------- Try to change a user's password
  975: 
  976: sub changepass {
  977:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
  978:     $currentpass = &escape($currentpass);
  979:     $newpass     = &escape($newpass);
  980:     my $lonhost = $perlvar{'lonHostID'};
  981:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
  982: 		       $server);
  983:     if (! $answer) {
  984: 	&logthis("No reply on password change request to $server ".
  985: 		 "by $uname in domain $udom.");
  986:     } elsif ($answer =~ "^ok") {
  987:         &logthis("$uname in $udom successfully changed their password ".
  988: 		 "on $server.");
  989:     } elsif ($answer =~ "^pwchange_failure") {
  990: 	&logthis("$uname in $udom was unable to change their password ".
  991: 		 "on $server.  The action was blocked by either lcpasswd ".
  992: 		 "or pwchange");
  993:     } elsif ($answer =~ "^non_authorized") {
  994:         &logthis("$uname in $udom did not get their password correct when ".
  995: 		 "attempting to change it on $server.");
  996:     } elsif ($answer =~ "^auth_mode_error") {
  997:         &logthis("$uname in $udom attempted to change their password despite ".
  998: 		 "not being locally or internally authenticated on $server.");
  999:     } elsif ($answer =~ "^unknown_user") {
 1000:         &logthis("$uname in $udom attempted to change their password ".
 1001: 		 "on $server but were unable to because $server is not ".
 1002: 		 "their home server.");
 1003:     } elsif ($answer =~ "^refused") {
 1004: 	&logthis("$server refused to change $uname in $udom password because ".
 1005: 		 "it was sent an unencrypted request to change the password.");
 1006:     } elsif ($answer =~ "invalid_client") {
 1007:         &logthis("$server refused to change $uname in $udom password because ".
 1008:                  "it was a reset by e-mail originating from an invalid server.");
 1009:     }
 1010:     return $answer;
 1011: }
 1012: 
 1013: # ----------------------- Try to determine user's current authentication scheme
 1014: 
 1015: sub queryauthenticate {
 1016:     my ($uname,$udom)=@_;
 1017:     my $uhome=&homeserver($uname,$udom);
 1018:     if (!$uhome) {
 1019: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
 1020: 	return 'no_host';
 1021:     }
 1022:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
 1023:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
 1024: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1025:     }
 1026:     return $answer;
 1027: }
 1028: 
 1029: # --------- Try to authenticate user from domain's lib servers (first this one)
 1030: 
 1031: sub authenticate {
 1032:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
 1033:     $upass=&escape($upass);
 1034:     $uname= &LONCAPA::clean_username($uname);
 1035:     my $uhome=&homeserver($uname,$udom,1);
 1036:     my $newhome;
 1037:     if ((!$uhome) || ($uhome eq 'no_host')) {
 1038: # Maybe the machine was offline and only re-appeared again recently?
 1039:         &reconlonc();
 1040: # One more
 1041: 	$uhome=&homeserver($uname,$udom,1);
 1042:         if (($uhome eq 'no_host') && $checkdefauth) {
 1043:             if (defined(&domain($udom,'primary'))) {
 1044:                 $newhome=&domain($udom,'primary');
 1045:             }
 1046:             if ($newhome ne '') {
 1047:                 $uhome = $newhome;
 1048:             }
 1049:         }
 1050: 	if ((!$uhome) || ($uhome eq 'no_host')) {
 1051: 	    &logthis("User $uname at $udom is unknown in authenticate");
 1052: 	    return 'no_host';
 1053:         }
 1054:     }
 1055:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
 1056:     if ($answer eq 'authorized') {
 1057:         if ($newhome) {
 1058:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
 1059:             return 'no_account_on_host'; 
 1060:         } else {
 1061:             &logthis("User $uname at $udom authorized by $uhome");
 1062:             return $uhome;
 1063:         }
 1064:     }
 1065:     if ($answer eq 'non_authorized') {
 1066: 	&logthis("User $uname at $udom rejected by $uhome");
 1067: 	return 'no_host'; 
 1068:     }
 1069:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1070:     return 'no_host';
 1071: }
 1072: 
 1073: sub can_host_session {
 1074:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
 1075:     my $canhost = 1;
 1076:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
 1077:     if (ref($remotesessions) eq 'HASH') {
 1078:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
 1079:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
 1080:                 $canhost = 0;
 1081:             } else {
 1082:                 $canhost = 1;
 1083:             }
 1084:         }
 1085:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
 1086:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
 1087:                 $canhost = 1;
 1088:             } else {
 1089:                 $canhost = 0;
 1090:             }
 1091:         }
 1092:         if ($canhost) {
 1093:             if ($remotesessions->{'version'} ne '') {
 1094:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
 1095:                 if ($reqmajor ne '' && $reqminor ne '') {
 1096:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
 1097:                         my $major = $1;
 1098:                         my $minor = $2;
 1099:                         if (($major < $reqmajor ) ||
 1100:                             (($major == $reqmajor) && ($minor < $reqminor))) {
 1101:                             $canhost = 0;
 1102:                         }
 1103:                     } else {
 1104:                         $canhost = 0;
 1105:                     }
 1106:                 }
 1107:             }
 1108:         }
 1109:     }
 1110:     if ($canhost) {
 1111:         if (ref($hostedsessions) eq 'HASH') {
 1112:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1113:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 1114:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
 1115:                 if (($uint_dom ne '') && 
 1116:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
 1117:                     $canhost = 0;
 1118:                 } else {
 1119:                     $canhost = 1;
 1120:                 }
 1121:             }
 1122:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
 1123:                 if (($uint_dom ne '') && 
 1124:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
 1125:                     $canhost = 1;
 1126:                 } else {
 1127:                     $canhost = 0;
 1128:                 }
 1129:             }
 1130:         }
 1131:     }
 1132:     return $canhost;
 1133: }
 1134: 
 1135: sub spare_can_host {
 1136:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
 1137:     my $canhost=1;
 1138:     my @intdoms;
 1139:     my $internet_names = &Apache::lonnet::get_internet_names($try_server);
 1140:     if (ref($internet_names) eq 'ARRAY') {
 1141:         @intdoms = @{$internet_names};
 1142:     }
 1143:     unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1144:         my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
 1145:         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
 1146:         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
 1147:         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
 1148:         $canhost = &can_host_session($udom,$try_server,$remoterev,
 1149:                                      $remotesessions,
 1150:                                      $defdomdefaults{'hostedsessions'});
 1151:     }
 1152:     return $canhost;
 1153: }
 1154: 
 1155: sub this_host_spares {
 1156:     my ($dom) = @_;
 1157:     my ($dom_in_use,$lonhost_in_use,$result);
 1158:     my @hosts = &current_machine_ids();
 1159:     foreach my $lonhost (@hosts) {
 1160:         if (&host_domain($lonhost) eq $dom) {
 1161:             $dom_in_use = $dom;
 1162:             $lonhost_in_use = $lonhost;
 1163:             last;
 1164:         }
 1165:     }
 1166:     if ($dom_in_use ne '') {
 1167:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1168:     }
 1169:     if (ref($result) ne 'HASH') {
 1170:         $lonhost_in_use = $perlvar{'lonHostID'};
 1171:         $dom_in_use = &host_domain($lonhost_in_use);
 1172:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1173:         if (ref($result) ne 'HASH') {
 1174:             $result = \%spareid;
 1175:         }
 1176:     }
 1177:     return $result;
 1178: }
 1179: 
 1180: sub spares_for_offload  {
 1181:     my ($dom_in_use,$lonhost_in_use) = @_;
 1182:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
 1183:     if (defined($cached)) {
 1184:         return $result;
 1185:     } else {
 1186:         my $cachetime = 60*60*24;
 1187:         my %domconfig =
 1188:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
 1189:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1190:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
 1191:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
 1192:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
 1193:                 }
 1194:             }
 1195:         }
 1196:     }
 1197:     return;
 1198: }
 1199: 
 1200: sub get_lonbalancer_config {
 1201:     my ($servers) = @_;
 1202:     my ($currbalancer,$currtargets);
 1203:     if (ref($servers) eq 'HASH') {
 1204:         foreach my $server (keys(%{$servers})) {
 1205:             my %what = (
 1206:                          spareid => 1,
 1207:                          perlvar => 1,
 1208:                        );
 1209:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
 1210:             if ($result eq 'ok') {
 1211:                 if (ref($returnhash) eq 'HASH') {
 1212:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
 1213:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
 1214:                             $currbalancer = $server;
 1215:                             $currtargets = {};
 1216:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
 1217:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
 1218:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
 1219:                                 }
 1220:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
 1221:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
 1222:                                 }
 1223:                             }
 1224:                             last;
 1225:                         }
 1226:                     }
 1227:                 }
 1228:             }
 1229:         }
 1230:     }
 1231:     return ($currbalancer,$currtargets);
 1232: }
 1233: 
 1234: sub check_loadbalancing {
 1235:     my ($uname,$udom) = @_;
 1236:     my ($is_balancer,$dom_in_use,$homeintdom,$rule_in_effect,
 1237:         $offloadto,$otherserver);
 1238:     my $lonhost = $perlvar{'lonHostID'};
 1239:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1240:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
 1241:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
 1242:     my $serverhomedom = &host_domain($lonhost);
 1243: 
 1244:     my $cachetime = 60*60*24;
 1245: 
 1246:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1247:         $dom_in_use = $udom;
 1248:         $homeintdom = 1;
 1249:     } else {
 1250:         $dom_in_use = $serverhomedom;
 1251:     }
 1252:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
 1253:     unless (defined($cached)) {
 1254:         my %domconfig =
 1255:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
 1256:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1257:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1258:         }
 1259:     }
 1260:     if (ref($result) eq 'HASH') {
 1261:         my $currbalancer = $result->{'lonhost'};
 1262:         my $currtargets = $result->{'targets'};
 1263:         my $currrules = $result->{'rules'};
 1264:         if ($currbalancer ne '') {
 1265:             my @hosts = &current_machine_ids();
 1266:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
 1267:                 $is_balancer = 1;
 1268:             }
 1269:         }
 1270:         if ($is_balancer) {
 1271:             if (ref($currrules) eq 'HASH') {
 1272:                 if ($homeintdom) {
 1273:                     if ($uname ne '') {
 1274:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
 1275:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
 1276:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
 1277:                                 $rule_in_effect = $currrules->{'_LC_author'};
 1278:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
 1279:                                 $rule_in_effect = $currrules->{'_LC_adv'}
 1280:                             }
 1281:                         }
 1282:                         if ($rule_in_effect eq '') {
 1283:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
 1284:                             if ($userenv{'inststatus'} ne '') {
 1285:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
 1286:                                 my ($othertitle,$usertypes,$types) =
 1287:                                     &Apache::loncommon::sorted_inst_types($udom);
 1288:                                 if (ref($types) eq 'ARRAY') {
 1289:                                     foreach my $type (@{$types}) {
 1290:                                         if (grep(/^\Q$type\E$/,@statuses)) {
 1291:                                             if (exists($currrules->{$type})) {
 1292:                                                 $rule_in_effect = $currrules->{$type};
 1293:                                             }
 1294:                                         }
 1295:                                     }
 1296:                                 }
 1297:                             } else {
 1298:                                 if (exists($currrules->{'default'})) {
 1299:                                     $rule_in_effect = $currrules->{'default'};
 1300:                                 }
 1301:                             }
 1302:                         }
 1303:                     } else {
 1304:                         if (exists($currrules->{'default'})) {
 1305:                             $rule_in_effect = $currrules->{'default'};
 1306:                         }
 1307:                     }
 1308:                 } else {
 1309:                     if ($currrules->{'_LC_external'} ne '') {
 1310:                         $rule_in_effect = $currrules->{'_LC_external'};
 1311:                     }
 1312:                 }
 1313:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1314:                                                        $uname,$udom);
 1315:             }
 1316:         }
 1317:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
 1318:         my ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
 1319:         unless (defined($cached)) {
 1320:             my %domconfig =
 1321:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
 1322:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1323:                 $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1324:             }
 1325:         }
 1326:         if (ref($result) eq 'HASH') {
 1327:             my $currbalancer = $result->{'lonhost'};
 1328:             my $currtargets = $result->{'targets'};
 1329:             my $currrules = $result->{'rules'};
 1330: 
 1331:             if ($currbalancer eq $lonhost) {
 1332:                 $is_balancer = 1;
 1333:                 if (ref($currrules) eq 'HASH') {
 1334:                     if ($currrules->{'_LC_internetdom'} ne '') {
 1335:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
 1336:                     }
 1337:                 }
 1338:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1339:                                                        $uname,$udom);
 1340:             }
 1341:         } else {
 1342:             if ($perlvar{'lonBalancer'} eq 'yes') {
 1343:                 $is_balancer = 1;
 1344:                 $offloadto = &this_host_spares($dom_in_use);
 1345:             }
 1346:         }
 1347:     } else {
 1348:         if ($perlvar{'lonBalancer'} eq 'yes') {
 1349:             $is_balancer = 1;
 1350:             $offloadto = &this_host_spares($dom_in_use);
 1351:         }
 1352:     }
 1353:     my $lowest_load = 30000;
 1354:     if (ref($offloadto) eq 'HASH') {
 1355:         if (ref($offloadto->{'primary'}) eq 'ARRAY') {
 1356:             foreach my $try_server (@{$offloadto->{'primary'}}) {
 1357:                 ($otherserver,$lowest_load) =
 1358:                     &compare_server_load($try_server,$otherserver,$lowest_load);
 1359:             }
 1360:         }
 1361:         my $found_server = ($otherserver ne '' && $lowest_load < 100);
 1362: 
 1363:         if (!$found_server) {
 1364:             if (ref($offloadto->{'default'}) eq 'ARRAY') {
 1365:                 foreach my $try_server (@{$offloadto->{'default'}}) {
 1366:                     ($otherserver,$lowest_load) =
 1367:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1368:                 }
 1369:             }
 1370:         }
 1371:     } elsif (ref($offloadto) eq 'ARRAY') {
 1372:         if (@{$offloadto} == 1) {
 1373:             $otherserver = $offloadto->[0];
 1374:         } elsif (@{$offloadto} > 1) {
 1375:             foreach my $try_server (@{$offloadto}) {
 1376:                 ($otherserver,$lowest_load) =
 1377:                     &compare_server_load($try_server,$otherserver,$lowest_load);
 1378:             }
 1379:         }
 1380:     }
 1381:     return ($is_balancer,$otherserver);
 1382: }
 1383: 
 1384: sub get_loadbalancer_targets {
 1385:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
 1386:     my $offloadto;
 1387:     if ($rule_in_effect eq '') {
 1388:         $offloadto = $currtargets;
 1389:     } else {
 1390:         if ($rule_in_effect eq 'homeserver') {
 1391:             my $homeserver = &homeserver($uname,$udom);
 1392:             if ($homeserver ne 'no_host') {
 1393:                 $offloadto = [$homeserver];
 1394:             }
 1395:         } elsif ($rule_in_effect eq 'externalbalancer') {
 1396:             my %domconfig =
 1397:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1398:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1399:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
 1400:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
 1401:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
 1402:                     }
 1403:                 }
 1404:             } else {
 1405:                 my %servers = &dom_servers($udom);
 1406:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
 1407:                 if (&hostname($remotebalancer) ne '') {
 1408:                     $offloadto = [$remotebalancer];
 1409:                 }
 1410:             }
 1411:         } elsif (&hostname($rule_in_effect) ne '') {
 1412:             $offloadto = [$rule_in_effect];
 1413:         }
 1414:     }
 1415:     return $offloadto;
 1416: }
 1417: 
 1418: sub internet_dom_servers {
 1419:     my ($dom) = @_;
 1420:     my (%uniqservers,%servers);
 1421:     my $primaryserver = &hostname(&domain($dom,'primary'));
 1422:     my @machinedoms = &machine_domains($primaryserver);
 1423:     foreach my $mdom (@machinedoms) {
 1424:         my %currservers = %servers;
 1425:         my %server = &get_servers($mdom);
 1426:         %servers = (%currservers,%server);
 1427:     }
 1428:     my %by_hostname;
 1429:     foreach my $id (keys(%servers)) {
 1430:         push(@{$by_hostname{$servers{$id}}},$id);
 1431:     }
 1432:     foreach my $hostname (sort(keys(%by_hostname))) {
 1433:         if (@{$by_hostname{$hostname}} > 1) {
 1434:             my $match = 0;
 1435:             foreach my $id (@{$by_hostname{$hostname}}) {
 1436:                 if (&host_domain($id) eq $dom) {
 1437:                     $uniqservers{$id} = $hostname;
 1438:                     $match = 1;
 1439:                 }
 1440:             }
 1441:             unless ($match) {
 1442:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1443:             }
 1444:         } else {
 1445:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1446:         }
 1447:     }
 1448:     return %uniqservers;
 1449: }
 1450: 
 1451: # ---------------------- Find the homebase for a user from domain's lib servers
 1452: 
 1453: my %homecache;
 1454: sub homeserver {
 1455:     my ($uname,$udom,$ignoreBadCache)=@_;
 1456:     my $index="$uname:$udom";
 1457: 
 1458:     if (exists($homecache{$index})) { return $homecache{$index}; }
 1459: 
 1460:     my %servers = &get_servers($udom,'library');
 1461:     foreach my $tryserver (keys(%servers)) {
 1462:         next if ($ignoreBadCache ne 'true' && 
 1463: 		 exists($badServerCache{$tryserver}));
 1464: 
 1465: 	my $answer=reply("home:$udom:$uname",$tryserver);
 1466: 	if ($answer eq 'found') {
 1467: 	    delete($badServerCache{$tryserver}); 
 1468: 	    return $homecache{$index}=$tryserver;
 1469: 	} elsif ($answer eq 'no_host') {
 1470: 	    $badServerCache{$tryserver}=1;
 1471: 	}
 1472:     }    
 1473:     return 'no_host';
 1474: }
 1475: 
 1476: # ------------------------------------- Find the usernames behind a list of IDs
 1477: 
 1478: sub idget {
 1479:     my ($udom,@ids)=@_;
 1480:     my %returnhash=();
 1481:     
 1482:     my %servers = &get_servers($udom,'library');
 1483:     foreach my $tryserver (keys(%servers)) {
 1484: 	my $idlist=join('&',@ids);
 1485: 	$idlist=~tr/A-Z/a-z/; 
 1486: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
 1487: 	my @answer=();
 1488: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
 1489: 	    @answer=split(/\&/,$reply);
 1490: 	}                    ;
 1491: 	my $i;
 1492: 	for ($i=0;$i<=$#ids;$i++) {
 1493: 	    if ($answer[$i]) {
 1494: 		$returnhash{$ids[$i]}=$answer[$i];
 1495: 	    } 
 1496: 	}
 1497:     } 
 1498:     return %returnhash;
 1499: }
 1500: 
 1501: # ------------------------------------- Find the IDs behind a list of usernames
 1502: 
 1503: sub idrget {
 1504:     my ($udom,@unames)=@_;
 1505:     my %returnhash=();
 1506:     foreach my $uname (@unames) {
 1507:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
 1508:     }
 1509:     return %returnhash;
 1510: }
 1511: 
 1512: # ------------------------------- Store away a list of names and associated IDs
 1513: 
 1514: sub idput {
 1515:     my ($udom,%ids)=@_;
 1516:     my %servers=();
 1517:     foreach my $uname (keys(%ids)) {
 1518: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
 1519:         my $uhom=&homeserver($uname,$udom);
 1520:         if ($uhom ne 'no_host') {
 1521:             my $id=&escape($ids{$uname});
 1522:             $id=~tr/A-Z/a-z/;
 1523:             my $esc_unam=&escape($uname);
 1524: 	    if ($servers{$uhom}) {
 1525: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
 1526:             } else {
 1527:                 $servers{$uhom}=$id.'='.$esc_unam;
 1528:             }
 1529:         }
 1530:     }
 1531:     foreach my $server (keys(%servers)) {
 1532:         &critical('idput:'.$udom.':'.$servers{$server},$server);
 1533:     }
 1534: }
 1535: 
 1536: # ------------------------------dump from db file owned by domainconfig user
 1537: sub dump_dom {
 1538:     my ($namespace, $udom, $regexp) = @_;
 1539: 
 1540:     $udom ||= $env{'user.domain'};
 1541: 
 1542:     return () unless $udom;
 1543: 
 1544:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
 1545: }
 1546: 
 1547: # ------------------------------------------ get items from domain db files   
 1548: 
 1549: sub get_dom {
 1550:     my ($namespace,$storearr,$udom,$uhome)=@_;
 1551:     my $items='';
 1552:     foreach my $item (@$storearr) {
 1553:         $items.=&escape($item).'&';
 1554:     }
 1555:     $items=~s/\&$//;
 1556:     if (!$udom) {
 1557:         $udom=$env{'user.domain'};
 1558:         if (defined(&domain($udom,'primary'))) {
 1559:             $uhome=&domain($udom,'primary');
 1560:         } else {
 1561:             undef($uhome);
 1562:         }
 1563:     } else {
 1564:         if (!$uhome) {
 1565:             if (defined(&domain($udom,'primary'))) {
 1566:                 $uhome=&domain($udom,'primary');
 1567:             }
 1568:         }
 1569:     }
 1570:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1571:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 1572:         my %returnhash;
 1573:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 1574:             return %returnhash;
 1575:         }
 1576:         my @pairs=split(/\&/,$rep);
 1577:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 1578:             return @pairs;
 1579:         }
 1580:         my $i=0;
 1581:         foreach my $item (@$storearr) {
 1582:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 1583:             $i++;
 1584:         }
 1585:         return %returnhash;
 1586:     } else {
 1587:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 1588:     }
 1589: }
 1590: 
 1591: # -------------------------------------------- put items in domain db files 
 1592: 
 1593: sub put_dom {
 1594:     my ($namespace,$storehash,$udom,$uhome)=@_;
 1595:     if (!$udom) {
 1596:         $udom=$env{'user.domain'};
 1597:         if (defined(&domain($udom,'primary'))) {
 1598:             $uhome=&domain($udom,'primary');
 1599:         } else {
 1600:             undef($uhome);
 1601:         }
 1602:     } else {
 1603:         if (!$uhome) {
 1604:             if (defined(&domain($udom,'primary'))) {
 1605:                 $uhome=&domain($udom,'primary');
 1606:             }
 1607:         }
 1608:     } 
 1609:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1610:         my $items='';
 1611:         foreach my $item (keys(%$storehash)) {
 1612:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 1613:         }
 1614:         $items=~s/\&$//;
 1615:         return &reply("putdom:$udom:$namespace:$items",$uhome);
 1616:     } else {
 1617:         &logthis("put_dom failed - no homeserver and/or domain");
 1618:     }
 1619: }
 1620: 
 1621: # --------------------- newput for items in db file owned by domainconfig user
 1622: sub newput_dom {
 1623:     my ($namespace,$storehash,$udom) = @_;
 1624:     my $result;
 1625:     if (!$udom) {
 1626:         $udom=$env{'user.domain'};
 1627:     }
 1628:     if ($udom) {
 1629:         my $uname = &get_domainconfiguser($udom);
 1630:         $result = &newput($namespace,$storehash,$udom,$uname);
 1631:     }
 1632:     return $result;
 1633: }
 1634: 
 1635: # --------------------- delete for items in db file owned by domainconfig user
 1636: sub del_dom {
 1637:     my ($namespace,$storearr,$udom)=@_;
 1638:     if (ref($storearr) eq 'ARRAY') {
 1639:         if (!$udom) {
 1640:             $udom=$env{'user.domain'};
 1641:         }
 1642:         if ($udom) {
 1643:             my $uname = &get_domainconfiguser($udom); 
 1644:             return &del($namespace,$storearr,$udom,$uname);
 1645:         }
 1646:     }
 1647: }
 1648: 
 1649: # ----------------------------------construct domainconfig user for a domain 
 1650: sub get_domainconfiguser {
 1651:     my ($udom) = @_;
 1652:     return $udom.'-domainconfig';
 1653: }
 1654: 
 1655: sub retrieve_inst_usertypes {
 1656:     my ($udom) = @_;
 1657:     my (%returnhash,@order);
 1658:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 1659:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 1660:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 1661:         %returnhash = %{$domdefs{'inststatustypes'}};
 1662:         @order = @{$domdefs{'inststatusorder'}};
 1663:     } else {
 1664:         if (defined(&domain($udom,'primary'))) {
 1665:             my $uhome=&domain($udom,'primary');
 1666:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 1667:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 1668:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
 1669:                 return (\%returnhash,\@order);
 1670:             }
 1671:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 1672:             my @pairs=split(/\&/,$hashitems);
 1673:             foreach my $item (@pairs) {
 1674:                 my ($key,$value)=split(/=/,$item,2);
 1675:                 $key = &unescape($key);
 1676:                 next if ($key =~ /^error: 2 /);
 1677:                 $returnhash{$key}=&thaw_unescape($value);
 1678:             }
 1679:             my @esc_order = split(/\&/,$orderitems);
 1680:             foreach my $item (@esc_order) {
 1681:                 push(@order,&unescape($item));
 1682:             }
 1683:         } else {
 1684:             &logthis("get_dom failed - no primary domain server for $udom");
 1685:         }
 1686:     }
 1687:     return (\%returnhash,\@order);
 1688: }
 1689: 
 1690: sub is_domainimage {
 1691:     my ($url) = @_;
 1692:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
 1693:         if (&domain($1) ne '') {
 1694:             return '1';
 1695:         }
 1696:     }
 1697:     return;
 1698: }
 1699: 
 1700: sub inst_directory_query {
 1701:     my ($srch) = @_;
 1702:     my $udom = $srch->{'srchdomain'};
 1703:     my %results;
 1704:     my $homeserver = &domain($udom,'primary');
 1705:     my $outcome;
 1706:     if ($homeserver ne '') {
 1707: 	my $queryid=&reply("querysend:instdirsearch:".
 1708: 			   &escape($srch->{'srchby'}).':'.
 1709: 			   &escape($srch->{'srchterm'}).':'.
 1710: 			   &escape($srch->{'srchtype'}),$homeserver);
 1711: 	my $host=&hostname($homeserver);
 1712: 	if ($queryid !~/^\Q$host\E\_/) {
 1713: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1714: 	    return;
 1715: 	}
 1716: 	my $response = &get_query_reply($queryid);
 1717: 	my $maxtries = 5;
 1718: 	my $tries = 1;
 1719: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1720: 	    $response = &get_query_reply($queryid);
 1721: 	    $tries ++;
 1722: 	}
 1723: 
 1724:         if (!&error($response) && $response ne 'refused') {
 1725:             if ($response eq 'unavailable') {
 1726:                 $outcome = $response;
 1727:             } else {
 1728:                 $outcome = 'ok';
 1729:                 my @matches = split(/\n/,$response);
 1730:                 foreach my $match (@matches) {
 1731:                     my ($key,$value) = split(/=/,$match);
 1732:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 1733:                 }
 1734:             }
 1735:         }
 1736:     }
 1737:     return ($outcome,%results);
 1738: }
 1739: 
 1740: sub usersearch {
 1741:     my ($srch) = @_;
 1742:     my $dom = $srch->{'srchdomain'};
 1743:     my %results;
 1744:     my %libserv = &all_library();
 1745:     my $query = 'usersearch';
 1746:     foreach my $tryserver (keys(%libserv)) {
 1747:         if (&host_domain($tryserver) eq $dom) {
 1748:             my $host=&hostname($tryserver);
 1749:             my $queryid=
 1750:                 &reply("querysend:".&escape($query).':'.
 1751:                        &escape($srch->{'srchby'}).':'.
 1752:                        &escape($srch->{'srchtype'}).':'.
 1753:                        &escape($srch->{'srchterm'}),$tryserver);
 1754:             if ($queryid !~/^\Q$host\E\_/) {
 1755:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 1756:                 next;
 1757:             }
 1758:             my $reply = &get_query_reply($queryid);
 1759:             my $maxtries = 1;
 1760:             my $tries = 1;
 1761:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 1762:                 $reply = &get_query_reply($queryid);
 1763:                 $tries ++;
 1764:             }
 1765:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 1766:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 1767:             } else {
 1768:                 my @matches;
 1769:                 if ($reply =~ /\n/) {
 1770:                     @matches = split(/\n/,$reply);
 1771:                 } else {
 1772:                     @matches = split(/\&/,$reply);
 1773:                 }
 1774:                 foreach my $match (@matches) {
 1775:                     my ($uname,$udom,%userhash);
 1776:                     foreach my $entry (split(/:/,$match)) {
 1777:                         my ($key,$value) =
 1778:                             map {&unescape($_);} split(/=/,$entry);
 1779:                         $userhash{$key} = $value;
 1780:                         if ($key eq 'username') {
 1781:                             $uname = $value;
 1782:                         } elsif ($key eq 'domain') {
 1783:                             $udom = $value;
 1784:                         }
 1785:                     }
 1786:                     $results{$uname.':'.$udom} = \%userhash;
 1787:                 }
 1788:             }
 1789:         }
 1790:     }
 1791:     return %results;
 1792: }
 1793: 
 1794: sub get_instuser {
 1795:     my ($udom,$uname,$id) = @_;
 1796:     my $homeserver = &domain($udom,'primary');
 1797:     my ($outcome,%results);
 1798:     if ($homeserver ne '') {
 1799:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 1800:                            &escape($id).':'.&escape($udom),$homeserver);
 1801:         my $host=&hostname($homeserver);
 1802:         if ($queryid !~/^\Q$host\E\_/) {
 1803:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1804:             return;
 1805:         }
 1806:         my $response = &get_query_reply($queryid);
 1807:         my $maxtries = 5;
 1808:         my $tries = 1;
 1809:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1810:             $response = &get_query_reply($queryid);
 1811:             $tries ++;
 1812:         }
 1813:         if (!&error($response) && $response ne 'refused') {
 1814:             if ($response eq 'unavailable') {
 1815:                 $outcome = $response;
 1816:             } else {
 1817:                 $outcome = 'ok';
 1818:                 my @matches = split(/\n/,$response);
 1819:                 foreach my $match (@matches) {
 1820:                     my ($key,$value) = split(/=/,$match);
 1821:                     $results{&unescape($key)} = &thaw_unescape($value);
 1822:                 }
 1823:             }
 1824:         }
 1825:     }
 1826:     my %userinfo;
 1827:     if (ref($results{$uname}) eq 'HASH') {
 1828:         %userinfo = %{$results{$uname}};
 1829:     } 
 1830:     return ($outcome,%userinfo);
 1831: }
 1832: 
 1833: sub inst_rulecheck {
 1834:     my ($udom,$uname,$id,$item,$rules) = @_;
 1835:     my %returnhash;
 1836:     if ($udom ne '') {
 1837:         if (ref($rules) eq 'ARRAY') {
 1838:             @{$rules} = map {&escape($_);} (@{$rules});
 1839:             my $rulestr = join(':',@{$rules});
 1840:             my $homeserver=&domain($udom,'primary');
 1841:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1842:                 my $response;
 1843:                 if ($item eq 'username') {                
 1844:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 1845:                                               ':'.&escape($uname).':'.$rulestr,
 1846:                                               $homeserver));
 1847:                 } elsif ($item eq 'id') {
 1848:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 1849:                                               ':'.&escape($id).':'.$rulestr,
 1850:                                               $homeserver));
 1851:                 } elsif ($item eq 'selfcreate') {
 1852:                     $response=&unescape(&reply('instselfcreatecheck:'.
 1853:                                                &escape($udom).':'.&escape($uname).
 1854:                                               ':'.$rulestr,$homeserver));
 1855:                 }
 1856:                 if ($response ne 'refused') {
 1857:                     my @pairs=split(/\&/,$response);
 1858:                     foreach my $item (@pairs) {
 1859:                         my ($key,$value)=split(/=/,$item,2);
 1860:                         $key = &unescape($key);
 1861:                         next if ($key =~ /^error: 2 /);
 1862:                         $returnhash{$key}=&thaw_unescape($value);
 1863:                     }
 1864:                 }
 1865:             }
 1866:         }
 1867:     }
 1868:     return %returnhash;
 1869: }
 1870: 
 1871: sub inst_userrules {
 1872:     my ($udom,$check) = @_;
 1873:     my (%ruleshash,@ruleorder);
 1874:     if ($udom ne '') {
 1875:         my $homeserver=&domain($udom,'primary');
 1876:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1877:             my $response;
 1878:             if ($check eq 'id') {
 1879:                 $response=&reply('instidrules:'.&escape($udom),
 1880:                                  $homeserver);
 1881:             } elsif ($check eq 'email') {
 1882:                 $response=&reply('instemailrules:'.&escape($udom),
 1883:                                  $homeserver);
 1884:             } else {
 1885:                 $response=&reply('instuserrules:'.&escape($udom),
 1886:                                  $homeserver);
 1887:             }
 1888:             if (($response ne 'refused') && ($response ne 'error') && 
 1889:                 ($response ne 'unknown_cmd') && 
 1890:                 ($response ne 'no_such_host')) {
 1891:                 my ($hashitems,$orderitems) = split(/:/,$response);
 1892:                 my @pairs=split(/\&/,$hashitems);
 1893:                 foreach my $item (@pairs) {
 1894:                     my ($key,$value)=split(/=/,$item,2);
 1895:                     $key = &unescape($key);
 1896:                     next if ($key =~ /^error: 2 /);
 1897:                     $ruleshash{$key}=&thaw_unescape($value);
 1898:                 }
 1899:                 my @esc_order = split(/\&/,$orderitems);
 1900:                 foreach my $item (@esc_order) {
 1901:                     push(@ruleorder,&unescape($item));
 1902:                 }
 1903:             }
 1904:         }
 1905:     }
 1906:     return (\%ruleshash,\@ruleorder);
 1907: }
 1908: 
 1909: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 1910: 
 1911: sub get_domain_defaults {
 1912:     my ($domain) = @_;
 1913:     my $cachetime = 60*60*24;
 1914:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 1915:     if (defined($cached)) {
 1916:         if (ref($result) eq 'HASH') {
 1917:             return %{$result};
 1918:         }
 1919:     }
 1920:     my %domdefaults;
 1921:     my %domconfig =
 1922:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 1923:                                   'requestcourses','inststatus',
 1924:                                   'coursedefaults','usersessions'],$domain);
 1925:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 1926:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 1927:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 1928:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 1929:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 1930:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 1931:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
 1932:     } else {
 1933:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 1934:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 1935:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 1936:     }
 1937:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 1938:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 1939:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 1940:         } else {
 1941:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 1942:         } 
 1943:         my @usertools = ('aboutme','blog','portfolio');
 1944:         foreach my $item (@usertools) {
 1945:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 1946:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 1947:             }
 1948:         }
 1949:     }
 1950:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 1951:         foreach my $item ('official','unofficial','community') {
 1952:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 1953:         }
 1954:     }
 1955:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 1956:         foreach my $item ('inststatustypes','inststatusorder') {
 1957:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 1958:         }
 1959:     }
 1960:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 1961:         foreach my $item ('canuse_pdfforms') {
 1962:             $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
 1963:         }
 1964:     }
 1965:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1966:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 1967:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 1968:         }
 1969:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 1970:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 1971:         }
 1972:     }
 1973:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
 1974:                                   $cachetime);
 1975:     return %domdefaults;
 1976: }
 1977: 
 1978: # --------------------------------------------------- Assign a key to a student
 1979: 
 1980: sub assign_access_key {
 1981: #
 1982: # a valid key looks like uname:udom#comments
 1983: # comments are being appended
 1984: #
 1985:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 1986:     $kdom=
 1987:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 1988:     $knum=
 1989:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 1990:     $cdom=
 1991:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1992:     $cnum=
 1993:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1994:     $udom=$env{'user.name'} unless (defined($udom));
 1995:     $uname=$env{'user.domain'} unless (defined($uname));
 1996:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 1997:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 1998:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 1999:                                                   # assigned to this person
 2000:                                                   # - this should not happen,
 2001:                                                   # unless something went wrong
 2002:                                                   # the first time around
 2003: # ready to assign
 2004:         $logentry=$1.'; '.$logentry;
 2005:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 2006:                                                  $kdom,$knum) eq 'ok') {
 2007: # key now belongs to user
 2008: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 2009:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 2010:                 &appenv({'environment.'.$envkey => $ckey});
 2011:                 return 'ok';
 2012:             } else {
 2013:                 return 
 2014:   'error: Count not permanently assign key, will need to be re-entered later.';
 2015: 	    }
 2016:         } else {
 2017:             return 'error: Could not assign key, try again later.';
 2018:         }
 2019:     } elsif (!$existing{$ckey}) {
 2020: # the key does not exist
 2021: 	return 'error: The key does not exist';
 2022:     } else {
 2023: # the key is somebody else's
 2024: 	return 'error: The key is already in use';
 2025:     }
 2026: }
 2027: 
 2028: # ------------------------------------------ put an additional comment on a key
 2029: 
 2030: sub comment_access_key {
 2031: #
 2032: # a valid key looks like uname:udom#comments
 2033: # comments are being appended
 2034: #
 2035:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 2036:     $cdom=
 2037:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2038:     $cnum=
 2039:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2040:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2041:     if ($existing{$ckey}) {
 2042:         $existing{$ckey}.='; '.$logentry;
 2043: # ready to assign
 2044:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 2045:                                                  $cdom,$cnum) eq 'ok') {
 2046: 	    return 'ok';
 2047:         } else {
 2048: 	    return 'error: Count not store comment.';
 2049:         }
 2050:     } else {
 2051: # the key does not exist
 2052: 	return 'error: The key does not exist';
 2053:     }
 2054: }
 2055: 
 2056: # ------------------------------------------------------ Generate a set of keys
 2057: 
 2058: sub generate_access_keys {
 2059:     my ($number,$cdom,$cnum,$logentry)=@_;
 2060:     $cdom=
 2061:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2062:     $cnum=
 2063:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2064:     unless (&allowed('mky',$cdom)) { return 0; }
 2065:     unless (($cdom) && ($cnum)) { return 0; }
 2066:     if ($number>10000) { return 0; }
 2067:     sleep(2); # make sure don't get same seed twice
 2068:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 2069:     my $total=0;
 2070:     for (my $i=1;$i<=$number;$i++) {
 2071:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 2072:                   sprintf("%lx",int(100000*rand)).'-'.
 2073:                   sprintf("%lx",int(100000*rand));
 2074:        $newkey=~s/1/g/g; # folks mix up 1 and l
 2075:        $newkey=~s/0/h/g; # and also 0 and O
 2076:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 2077:        if ($existing{$newkey}) {
 2078:            $i--;
 2079:        } else {
 2080: 	  if (&put('accesskeys',
 2081:               { $newkey => '# generated '.localtime().
 2082:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 2083:                            '; '.$logentry },
 2084: 		   $cdom,$cnum) eq 'ok') {
 2085:               $total++;
 2086: 	  }
 2087:        }
 2088:     }
 2089:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 2090:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 2091:     return $total;
 2092: }
 2093: 
 2094: # ------------------------------------------------------- Validate an accesskey
 2095: 
 2096: sub validate_access_key {
 2097:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 2098:     $cdom=
 2099:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2100:     $cnum=
 2101:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2102:     $udom=$env{'user.domain'} unless (defined($udom));
 2103:     $uname=$env{'user.name'} unless (defined($uname));
 2104:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2105:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 2106: }
 2107: 
 2108: # ------------------------------------- Find the section of student in a course
 2109: sub devalidate_getsection_cache {
 2110:     my ($udom,$unam,$courseid)=@_;
 2111:     my $hashid="$udom:$unam:$courseid";
 2112:     &devalidate_cache_new('getsection',$hashid);
 2113: }
 2114: 
 2115: sub courseid_to_courseurl {
 2116:     my ($courseid) = @_;
 2117:     #already url style courseid
 2118:     return $courseid if ($courseid =~ m{^/});
 2119: 
 2120:     if (exists($env{'course.'.$courseid.'.num'})) {
 2121: 	my $cnum = $env{'course.'.$courseid.'.num'};
 2122: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 2123: 	return "/$cdom/$cnum";
 2124:     }
 2125: 
 2126:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 2127:     if (exists($courseinfo{'num'})) {
 2128: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 2129:     }
 2130: 
 2131:     return undef;
 2132: }
 2133: 
 2134: sub getsection {
 2135:     my ($udom,$unam,$courseid)=@_;
 2136:     my $cachetime=1800;
 2137: 
 2138:     my $hashid="$udom:$unam:$courseid";
 2139:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 2140:     if (defined($cached)) { return $result; }
 2141: 
 2142:     my %Pending; 
 2143:     my %Expired;
 2144:     #
 2145:     # Each role can either have not started yet (pending), be active, 
 2146:     #    or have expired.
 2147:     #
 2148:     # If there is an active role, we are done.
 2149:     #
 2150:     # If there is more than one role which has not started yet, 
 2151:     #     choose the one which will start sooner
 2152:     # If there is one role which has not started yet, return it.
 2153:     #
 2154:     # If there is more than one expired role, choose the one which ended last.
 2155:     # If there is a role which has expired, return it.
 2156:     #
 2157:     $courseid = &courseid_to_courseurl($courseid);
 2158:     my $extra = &freeze_escape({'skipcheck' => 1});
 2159:     my %roleshash = &dump('roles',$udom,$unam,$courseid,undef,$extra);
 2160:     foreach my $key (keys(%roleshash)) {
 2161:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 2162:         my $section=$1;
 2163:         if ($key eq $courseid.'_st') { $section=''; }
 2164:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 2165:         my $now=time;
 2166:         if (defined($end) && $end && ($now > $end)) {
 2167:             $Expired{$end}=$section;
 2168:             next;
 2169:         }
 2170:         if (defined($start) && $start && ($now < $start)) {
 2171:             $Pending{$start}=$section;
 2172:             next;
 2173:         }
 2174:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 2175:     }
 2176:     #
 2177:     # Presumedly there will be few matching roles from the above
 2178:     # loop and the sorting time will be negligible.
 2179:     if (scalar(keys(%Pending))) {
 2180:         my ($time) = sort {$a <=> $b} keys(%Pending);
 2181:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 2182:     } 
 2183:     if (scalar(keys(%Expired))) {
 2184:         my @sorted = sort {$a <=> $b} keys(%Expired);
 2185:         my $time = pop(@sorted);
 2186:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 2187:     }
 2188:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 2189: }
 2190: 
 2191: sub save_cache {
 2192:     &purge_remembered();
 2193:     #&Apache::loncommon::validate_page();
 2194:     undef(%env);
 2195:     undef($env_loaded);
 2196: }
 2197: 
 2198: my $to_remember=-1;
 2199: my %remembered;
 2200: my %accessed;
 2201: my $kicks=0;
 2202: my $hits=0;
 2203: sub make_key {
 2204:     my ($name,$id) = @_;
 2205:     if (length($id) > 65 
 2206: 	&& length(&escape($id)) > 200) {
 2207: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 2208:     }
 2209:     return &escape($name.':'.$id);
 2210: }
 2211: 
 2212: sub devalidate_cache_new {
 2213:     my ($name,$id,$debug) = @_;
 2214:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 2215:     $id=&make_key($name,$id);
 2216:     $memcache->delete($id);
 2217:     delete($remembered{$id});
 2218:     delete($accessed{$id});
 2219: }
 2220: 
 2221: sub is_cached_new {
 2222:     my ($name,$id,$debug) = @_;
 2223:     $id=&make_key($name,$id);
 2224:     if (exists($remembered{$id})) {
 2225: 	if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
 2226: 	$accessed{$id}=[&gettimeofday()];
 2227: 	$hits++;
 2228: 	return ($remembered{$id},1);
 2229:     }
 2230:     my $value = $memcache->get($id);
 2231:     if (!(defined($value))) {
 2232: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 2233: 	return (undef,undef);
 2234:     }
 2235:     if ($value eq '__undef__') {
 2236: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 2237: 	$value=undef;
 2238:     }
 2239:     &make_room($id,$value,$debug);
 2240:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 2241:     return ($value,1);
 2242: }
 2243: 
 2244: sub do_cache_new {
 2245:     my ($name,$id,$value,$time,$debug) = @_;
 2246:     $id=&make_key($name,$id);
 2247:     my $setvalue=$value;
 2248:     if (!defined($setvalue)) {
 2249: 	$setvalue='__undef__';
 2250:     }
 2251:     if (!defined($time) ) {
 2252: 	$time=600;
 2253:     }
 2254:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 2255:     my $result = $memcache->set($id,$setvalue,$time);
 2256:     if (! $result) {
 2257: 	&logthis("caching of id -> $id  failed");
 2258: 	$memcache->disconnect_all();
 2259:     }
 2260:     # need to make a copy of $value
 2261:     &make_room($id,$value,$debug);
 2262:     return $value;
 2263: }
 2264: 
 2265: sub make_room {
 2266:     my ($id,$value,$debug)=@_;
 2267: 
 2268:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
 2269:                                     : $value;
 2270:     if ($to_remember<0) { return; }
 2271:     $accessed{$id}=[&gettimeofday()];
 2272:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 2273:     my $to_kick;
 2274:     my $max_time=0;
 2275:     foreach my $other (keys(%accessed)) {
 2276: 	if (&tv_interval($accessed{$other}) > $max_time) {
 2277: 	    $to_kick=$other;
 2278: 	    $max_time=&tv_interval($accessed{$other});
 2279: 	}
 2280:     }
 2281:     delete($remembered{$to_kick});
 2282:     delete($accessed{$to_kick});
 2283:     $kicks++;
 2284:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 2285:     return;
 2286: }
 2287: 
 2288: sub purge_remembered {
 2289:     #&logthis("Tossing ".scalar(keys(%remembered)));
 2290:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 2291:     undef(%remembered);
 2292:     undef(%accessed);
 2293: }
 2294: # ------------------------------------- Read an entry from a user's environment
 2295: 
 2296: sub userenvironment {
 2297:     my ($udom,$unam,@what)=@_;
 2298:     my $items;
 2299:     foreach my $item (@what) {
 2300:         $items.=&escape($item).'&';
 2301:     }
 2302:     $items=~s/\&$//;
 2303:     my %returnhash=();
 2304:     my $uhome = &homeserver($unam,$udom);
 2305:     unless ($uhome eq 'no_host') {
 2306:         my @answer=split(/\&/, 
 2307:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 2308:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 2309:             return %returnhash;
 2310:         }
 2311:         my $i;
 2312:         for ($i=0;$i<=$#what;$i++) {
 2313: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 2314:         }
 2315:     }
 2316:     return %returnhash;
 2317: }
 2318: 
 2319: # ---------------------------------------------------------- Get a studentphoto
 2320: sub studentphoto {
 2321:     my ($udom,$unam,$ext) = @_;
 2322:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2323:     if (defined($env{'request.course.id'})) {
 2324:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 2325:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 2326:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 2327:             } else {
 2328:                 my ($result,$perm_reqd)=
 2329: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2330:                 if ($result eq 'ok') {
 2331:                     if (!($perm_reqd eq 'yes')) {
 2332:                         return(&retrievestudentphoto($udom,$unam,$ext));
 2333:                     }
 2334:                 }
 2335:             }
 2336:         }
 2337:     } else {
 2338:         my ($result,$perm_reqd) = 
 2339: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2340:         if ($result eq 'ok') {
 2341:             if (!($perm_reqd eq 'yes')) {
 2342:                 return(&retrievestudentphoto($udom,$unam,$ext));
 2343:             }
 2344:         }
 2345:     }
 2346:     return '/adm/lonKaputt/lonlogo_broken.gif';
 2347: }
 2348: 
 2349: sub retrievestudentphoto {
 2350:     my ($udom,$unam,$ext,$type) = @_;
 2351:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2352:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 2353:     if ($ret eq 'ok') {
 2354:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 2355:         if ($type eq 'thumbnail') {
 2356:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 2357:         }
 2358:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 2359:         return $tokenurl;
 2360:     } else {
 2361:         if ($type eq 'thumbnail') {
 2362:             return '/adm/lonKaputt/genericstudent_tn.gif';
 2363:         } else { 
 2364:             return '/adm/lonKaputt/lonlogo_broken.gif';
 2365:         }
 2366:     }
 2367: }
 2368: 
 2369: # -------------------------------------------------------------------- New chat
 2370: 
 2371: sub chatsend {
 2372:     my ($newentry,$anon,$group)=@_;
 2373:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 2374:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2375:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 2376:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 2377: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 2378: 		   &escape($newentry)).':'.$group,$chome);
 2379: }
 2380: 
 2381: # ------------------------------------------ Find current version of a resource
 2382: 
 2383: sub getversion {
 2384:     my $fname=&clutter(shift);
 2385:     unless ($fname=~/^\/res\//) { return -1; }
 2386:     return &currentversion(&filelocation('',$fname));
 2387: }
 2388: 
 2389: sub currentversion {
 2390:     my $fname=shift;
 2391:     my $author=$fname;
 2392:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2393:     my ($udom,$uname)=split(/\//,$author);
 2394:     my $home=&homeserver($uname,$udom);
 2395:     if ($home eq 'no_host') { 
 2396:         return -1; 
 2397:     }
 2398:     my $answer=&reply("currentversion:$fname",$home);
 2399:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 2400: 	return -1;
 2401:     }
 2402:     return $answer;
 2403: }
 2404: 
 2405: #
 2406: # Return special version number of resource if set by override, empty otherwise
 2407: #
 2408: sub usedversion {
 2409:     my $fname=shift;
 2410:     unless ($fname) { $fname=$env{'request.uri'}; }
 2411:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 2412:     if ($urlversion) { return $urlversion; }
 2413:     return '';
 2414: }
 2415: 
 2416: # ----------------------------- Subscribe to a resource, return URL if possible
 2417: 
 2418: sub subscribe {
 2419:     my $fname=shift;
 2420:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 2421:     $fname=~s/[\n\r]//g;
 2422:     my $author=$fname;
 2423:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2424:     my ($udom,$uname)=split(/\//,$author);
 2425:     my $home=homeserver($uname,$udom);
 2426:     if ($home eq 'no_host') {
 2427:         return 'not_found';
 2428:     }
 2429:     my $answer=reply("sub:$fname",$home);
 2430:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 2431: 	$answer.=' by '.$home;
 2432:     }
 2433:     return $answer;
 2434: }
 2435:     
 2436: # -------------------------------------------------------------- Replicate file
 2437: 
 2438: sub repcopy {
 2439:     my $filename=shift;
 2440:     $filename=~s/\/+/\//g;
 2441:     my $londocroot = $perlvar{'lonDocRoot'};
 2442:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 2443:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
 2444:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 2445: 	$filename=~m{^/*(uploaded|editupload)/}) {
 2446: 	return &repcopy_userfile($filename);
 2447:     }
 2448:     $filename=~s/[\n\r]//g;
 2449:     my $transname="$filename.in.transfer";
 2450: # FIXME: this should flock
 2451:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 2452:     my $remoteurl=subscribe($filename);
 2453:     if ($remoteurl =~ /^con_lost by/) {
 2454: 	   &logthis("Subscribe returned $remoteurl: $filename");
 2455:            return 'unavailable';
 2456:     } elsif ($remoteurl eq 'not_found') {
 2457: 	   #&logthis("Subscribe returned not_found: $filename");
 2458: 	   return 'not_found';
 2459:     } elsif ($remoteurl =~ /^rejected by/) {
 2460: 	   &logthis("Subscribe returned $remoteurl: $filename");
 2461:            return 'forbidden';
 2462:     } elsif ($remoteurl eq 'directory') {
 2463:            return 'ok';
 2464:     } else {
 2465:         my $author=$filename;
 2466:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2467:         my ($udom,$uname)=split(/\//,$author);
 2468:         my $home=homeserver($uname,$udom);
 2469:         unless ($home eq $perlvar{'lonHostID'}) {
 2470:            my @parts=split(/\//,$filename);
 2471:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 2472:            if ($path ne "$londocroot/res") {
 2473:                &logthis("Malconfiguration for replication: $filename");
 2474: 	       return 'bad_request';
 2475:            }
 2476:            my $count;
 2477:            for ($count=5;$count<$#parts;$count++) {
 2478:                $path.="/$parts[$count]";
 2479:                if ((-e $path)!=1) {
 2480: 		   mkdir($path,0777);
 2481:                }
 2482:            }
 2483:            my $ua=new LWP::UserAgent;
 2484:            my $request=new HTTP::Request('GET',"$remoteurl");
 2485:            my $response=$ua->request($request,$transname);
 2486:            if ($response->is_error()) {
 2487: 	       unlink($transname);
 2488:                my $message=$response->status_line;
 2489:                &logthis("<font color=\"blue\">WARNING:"
 2490:                        ." LWP get: $message: $filename</font>");
 2491:                return 'unavailable';
 2492:            } else {
 2493: 	       if ($remoteurl!~/\.meta$/) {
 2494:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 2495:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 2496:                   if ($mresponse->is_error()) {
 2497: 		      unlink($filename.'.meta');
 2498:                       &logthis(
 2499:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 2500:                   }
 2501: 	       }
 2502:                rename($transname,$filename);
 2503:                return 'ok';
 2504:            }
 2505:        }
 2506:     }
 2507: }
 2508: 
 2509: # ------------------------------------------------ Get server side include body
 2510: sub ssi_body {
 2511:     my ($filelink,%form)=@_;
 2512:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 2513:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 2514:     }
 2515:     my $output='';
 2516:     my $response;
 2517:     if ($filelink=~/^https?\:/) {
 2518:        ($output,$response)=&externalssi($filelink);
 2519:     } else {
 2520:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 2521:        $filelink .= 'inhibitmenu=yes';
 2522:        ($output,$response)=&ssi($filelink,%form);
 2523:     }
 2524:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 2525:     $output=~s/^.*?\<body[^\>]*\>//si;
 2526:     $output=~s/\<\/body\s*\>.*?$//si;
 2527:     if (wantarray) {
 2528:         return ($output, $response);
 2529:     } else {
 2530:         return $output;
 2531:     }
 2532: }
 2533: 
 2534: # --------------------------------------------------------- Server Side Include
 2535: 
 2536: sub absolute_url {
 2537:     my ($host_name) = @_;
 2538:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 2539:     if ($host_name eq '') {
 2540: 	$host_name = $ENV{'SERVER_NAME'};
 2541:     }
 2542:     return $protocol.$host_name;
 2543: }
 2544: 
 2545: #
 2546: #   Server side include.
 2547: # Parameters:
 2548: #  fn     Possibly encrypted resource name/id.
 2549: #  form   Hash that describes how the rendering should be done
 2550: #         and other things.
 2551: # Returns:
 2552: #   Scalar context: The content of the response.
 2553: #   Array context:  2 element list of the content and the full response object.
 2554: #     
 2555: sub ssi {
 2556: 
 2557:     my ($fn,%form)=@_;
 2558:     my $ua=new LWP::UserAgent;
 2559:     my $request;
 2560: 
 2561:     $form{'no_update_last_known'}=1;
 2562:     &Apache::lonenc::check_encrypt(\$fn);
 2563:     if (%form) {
 2564:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 2565:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
 2566:     } else {
 2567:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 2568:     }
 2569: 
 2570:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 2571:     my $response=$ua->request($request);
 2572: 
 2573:     if (wantarray) {
 2574: 	return ($response->content, $response);
 2575:     } else {
 2576: 	return $response->content;
 2577:     }
 2578: }
 2579: 
 2580: sub externalssi {
 2581:     my ($url)=@_;
 2582:     my $ua=new LWP::UserAgent;
 2583:     my $request=new HTTP::Request('GET',$url);
 2584:     my $response=$ua->request($request);
 2585:     if (wantarray) {
 2586:         return ($response->content, $response);
 2587:     } else {
 2588:         return $response->content;
 2589:     }
 2590: }
 2591: 
 2592: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 2593: 
 2594: sub allowuploaded {
 2595:     my ($srcurl,$url)=@_;
 2596:     $url=&clutter(&declutter($url));
 2597:     my $dir=$url;
 2598:     $dir=~s/\/[^\/]+$//;
 2599:     my %httpref=();
 2600:     my $httpurl=&hreflocation('',$url);
 2601:     $httpref{'httpref.'.$httpurl}=$srcurl;
 2602:     &Apache::lonnet::appenv(\%httpref);
 2603: }
 2604: 
 2605: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 2606: # input: action, courseID, current domain, intended
 2607: #        path to file, source of file, instruction to parse file for objects,
 2608: #        ref to hash for embedded objects,
 2609: #        ref to hash for codebase of java objects.
 2610: #        reference to scalar to accommodate mime type determined
 2611: #          from File::MMagic if $parser = parse.
 2612: #
 2613: # output: url to file (if action was uploaddoc), 
 2614: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 2615: #
 2616: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 2617: # course.
 2618: #
 2619: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2620: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 2621: #          course's home server.
 2622: #
 2623: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 2624: #          be copied from $source (current location) to 
 2625: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2626: #         and will then be copied to
 2627: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 2628: #         course's home server.
 2629: #
 2630: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2631: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 2632: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2633: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 2634: #         in course's home server.
 2635: #
 2636: 
 2637: sub process_coursefile {
 2638:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 2639:         $mimetype)=@_;
 2640:     my $fetchresult;
 2641:     my $home=&homeserver($docuname,$docudom);
 2642:     if ($action eq 'propagate') {
 2643:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2644: 			     $home);
 2645:     } else {
 2646:         my $fpath = '';
 2647:         my $fname = $file;
 2648:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 2649:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 2650:         my $filepath = &build_filepath($fpath);
 2651:         if ($action eq 'copy') {
 2652:             if ($source eq '') {
 2653:                 $fetchresult = 'no source file';
 2654:                 return $fetchresult;
 2655:             } else {
 2656:                 my $destination = $filepath.'/'.$fname;
 2657:                 rename($source,$destination);
 2658:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2659:                                  $home);
 2660:             }
 2661:         } elsif ($action eq 'uploaddoc') {
 2662:             open(my $fh,'>'.$filepath.'/'.$fname);
 2663:             print $fh $env{'form.'.$source};
 2664:             close($fh);
 2665:             if ($parser eq 'parse') {
 2666:                 my $mm = new File::MMagic;
 2667:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 2668:                 if ($type eq 'text/html') {
 2669:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 2670:                     unless ($parse_result eq 'ok') {
 2671:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 2672:                     }
 2673:                 }
 2674:                 if (ref($mimetype)) {
 2675:                     $$mimetype = $type;
 2676:                 } 
 2677:             }
 2678:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2679:                                  $home);
 2680:             if ($fetchresult eq 'ok') {
 2681:                 return '/uploaded/'.$fpath.'/'.$fname;
 2682:             } else {
 2683:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2684:                         ' to host '.$home.': '.$fetchresult);
 2685:                 return '/adm/notfound.html';
 2686:             }
 2687:         }
 2688:     }
 2689:     unless ( $fetchresult eq 'ok') {
 2690:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2691:              ' to host '.$home.': '.$fetchresult);
 2692:     }
 2693:     return $fetchresult;
 2694: }
 2695: 
 2696: sub build_filepath {
 2697:     my ($fpath) = @_;
 2698:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 2699:     unless ($fpath eq '') {
 2700:         my @parts=split('/',$fpath);
 2701:         foreach my $part (@parts) {
 2702:             $filepath.= '/'.$part;
 2703:             if ((-e $filepath)!=1) {
 2704:                 mkdir($filepath,0777);
 2705:             }
 2706:         }
 2707:     }
 2708:     return $filepath;
 2709: }
 2710: 
 2711: sub store_edited_file {
 2712:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 2713:     my $file = $primary_url;
 2714:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 2715:     my $fpath = '';
 2716:     my $fname = $file;
 2717:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 2718:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 2719:     my $filepath = &build_filepath($fpath);
 2720:     open(my $fh,'>'.$filepath.'/'.$fname);
 2721:     print $fh $content;
 2722:     close($fh);
 2723:     my $home=&homeserver($docuname,$docudom);
 2724:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2725: 			  $home);
 2726:     if ($$fetchresult eq 'ok') {
 2727:         return '/uploaded/'.$fpath.'/'.$fname;
 2728:     } else {
 2729:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2730: 		 ' to host '.$home.': '.$$fetchresult);
 2731:         return '/adm/notfound.html';
 2732:     }
 2733: }
 2734: 
 2735: sub clean_filename {
 2736:     my ($fname,$args)=@_;
 2737: # Replace Windows backslashes by forward slashes
 2738:     $fname=~s/\\/\//g;
 2739:     if (!$args->{'keep_path'}) {
 2740:         # Get rid of everything but the actual filename
 2741: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 2742:     }
 2743: # Replace spaces by underscores
 2744:     $fname=~s/\s+/\_/g;
 2745: # Replace all other weird characters by nothing
 2746:     $fname=~s{[^/\w\.\-]}{}g;
 2747: # Replace all .\d. sequences with _\d. so they no longer look like version
 2748: # numbers
 2749:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 2750:     return $fname;
 2751: }
 2752: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 2753: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 2754: # image with the same aspect ratio as the original, but with dimensions which do 
 2755: # not exceed $resizewidth and $resizeheight.
 2756:  
 2757: sub resizeImage {
 2758:     my ($img_path,$resizewidth,$resizeheight) = @_;
 2759:     my $ima = Image::Magick->new;
 2760:     my $resized;
 2761:     if (-e $img_path) {
 2762:         $ima->Read($img_path);
 2763:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 2764:             my $width = $ima->Get('width');
 2765:             my $height = $ima->Get('height');
 2766:             if ($width > $resizewidth) {
 2767: 	        my $factor = $width/$resizewidth;
 2768:                 my $newheight = $height/$factor;
 2769:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 2770:                 $resized = 1;
 2771:             }
 2772:         }
 2773:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 2774:             my $width = $ima->Get('width');
 2775:             my $height = $ima->Get('height');
 2776:             if ($height > $resizeheight) {
 2777:                 my $factor = $height/$resizeheight;
 2778:                 my $newwidth = $width/$factor;
 2779:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 2780:                 $resized = 1;
 2781:             }
 2782:         }
 2783:         if ($resized) {
 2784:             $ima->Write($img_path);
 2785:         }
 2786:     }
 2787:     return;
 2788: }
 2789: 
 2790: # --------------- Take an uploaded file and put it into the userfiles directory
 2791: # input: $formname - the contents of the file are in $env{"form.$formname"}
 2792: #                    the desired filename is in $env{"form.$formname.filename"}
 2793: #        $context - possible values: coursedoc, existingfile, overwrite, 
 2794: #                                    canceloverwrite, or ''. 
 2795: #                   if 'coursedoc': upload to the current course
 2796: #                   if 'existingfile': write file to tmp/overwrites directory 
 2797: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 2798: #                   $context is passed as argument to &finishuserfileupload
 2799: #        $subdir - directory in userfile to store the file into
 2800: #        $parser - instruction to parse file for objects ($parser = parse)    
 2801: #        $allfiles - reference to hash for embedded objects
 2802: #        $codebase - reference to hash for codebase of java objects
 2803: #        $desuname - username for permanent storage of uploaded file
 2804: #        $dsetudom - domain for permanaent storage of uploaded file
 2805: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 2806: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 2807: #        $resizewidth - width (pixels) to which to resize uploaded image
 2808: #        $resizeheight - height (pixels) to which to resize uploaded image
 2809: #        $mimetype - reference to scalar to accommodate mime type determined
 2810: #                    from File::MMagic.
 2811: # 
 2812: # output: url of file in userspace, or error: <message> 
 2813: #             or /adm/notfound.html if failure to upload occurse
 2814: 
 2815: sub userfileupload {
 2816:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 2817:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 2818:     if (!defined($subdir)) { $subdir='unknown'; }
 2819:     my $fname=$env{'form.'.$formname.'.filename'};
 2820:     $fname=&clean_filename($fname);
 2821:     # See if there is anything left
 2822:     unless ($fname) { return 'error: no uploaded file'; }
 2823:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 2824:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 2825:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 2826:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 2827:         my $now = time;
 2828:         my $filepath;
 2829:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 2830:              $filepath = 'tmp/helprequests/'.$now;
 2831:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 2832:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 2833:                          '_'.$env{'user.domain'}.'/pending';
 2834:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 2835:             my ($docuname,$docudom);
 2836:             if ($destudom) {
 2837:                 $docudom = $destudom;
 2838:             } else {
 2839:                 $docudom = $env{'user.domain'};
 2840:             }
 2841:             if ($destuname) {
 2842:                 $docuname = $destuname;
 2843:             } else {
 2844:                 $docuname = $env{'user.name'};
 2845:             }
 2846:             if (exists($env{'form.group'})) {
 2847:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2848:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2849:             }
 2850:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 2851:             if ($context eq 'canceloverwrite') {
 2852:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 2853:                 if (-e  $tempfile) {
 2854:                     my @info = stat($tempfile);
 2855:                     if ($info[9] eq $env{'form.timestamp'}) {
 2856:                         unlink($tempfile);
 2857:                     }
 2858:                 }
 2859:                 return;
 2860:             }
 2861:         }
 2862:         # Create the directory if not present
 2863:         my @parts=split(/\//,$filepath);
 2864:         my $fullpath = $perlvar{'lonDaemons'};
 2865:         for (my $i=0;$i<@parts;$i++) {
 2866:             $fullpath .= '/'.$parts[$i];
 2867:             if ((-e $fullpath)!=1) {
 2868:                 mkdir($fullpath,0777);
 2869:             }
 2870:         }
 2871:         open(my $fh,'>'.$fullpath.'/'.$fname);
 2872:         print $fh $env{'form.'.$formname};
 2873:         close($fh);
 2874:         if ($context eq 'existingfile') {
 2875:             my @info = stat($fullpath.'/'.$fname);
 2876:             return ($fullpath.'/'.$fname,$info[9]);
 2877:         } else {
 2878:             return $fullpath.'/'.$fname;
 2879:         }
 2880:     }
 2881:     if ($subdir eq 'scantron') {
 2882:         $fname = 'scantron_orig_'.$fname;
 2883:     } else {
 2884:         $fname="$subdir/$fname";
 2885:     }
 2886:     if ($context eq 'coursedoc') {
 2887: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2888: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2889:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 2890:             return &finishuserfileupload($docuname,$docudom,
 2891: 					 $formname,$fname,$parser,$allfiles,
 2892: 					 $codebase,$thumbwidth,$thumbheight,
 2893:                                          $resizewidth,$resizeheight,$context,$mimetype);
 2894:         } else {
 2895:             $fname=$env{'form.folder'}.'/'.$fname;
 2896:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 2897: 				       $fname,$formname,$parser,
 2898: 				       $allfiles,$codebase,$mimetype);
 2899:         }
 2900:     } elsif (defined($destuname)) {
 2901:         my $docuname=$destuname;
 2902:         my $docudom=$destudom;
 2903: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 2904: 				     $parser,$allfiles,$codebase,
 2905:                                      $thumbwidth,$thumbheight,
 2906:                                      $resizewidth,$resizeheight,$context,$mimetype);
 2907:     } else {
 2908:         my $docuname=$env{'user.name'};
 2909:         my $docudom=$env{'user.domain'};
 2910:         if (exists($env{'form.group'})) {
 2911:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2912:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2913:         }
 2914: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 2915: 				     $parser,$allfiles,$codebase,
 2916:                                      $thumbwidth,$thumbheight,
 2917:                                      $resizewidth,$resizeheight,$context,$mimetype);
 2918:     }
 2919: }
 2920: 
 2921: sub finishuserfileupload {
 2922:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 2923:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 2924:     my $path=$docudom.'/'.$docuname.'/';
 2925:     my $filepath=$perlvar{'lonDocRoot'};
 2926:   
 2927:     my ($fnamepath,$file,$fetchthumb);
 2928:     $file=$fname;
 2929:     if ($fname=~m|/|) {
 2930:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 2931: 	$path.=$fnamepath.'/';
 2932:     }
 2933:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 2934:     my $count;
 2935:     for ($count=4;$count<=$#parts;$count++) {
 2936:         $filepath.="/$parts[$count]";
 2937:         if ((-e $filepath)!=1) {
 2938: 	    mkdir($filepath,0777);
 2939:         }
 2940:     }
 2941: 
 2942: # Save the file
 2943:     {
 2944: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 2945: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 2946: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 2947: 	    return '/adm/notfound.html';
 2948: 	}
 2949:         if ($context eq 'overwrite') {
 2950:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 2951:             my $target = $filepath.'/'.$file;
 2952:             if (-e $source) {
 2953:                 my @info = stat($source);
 2954:                 if ($info[9] eq $env{'form.timestamp'}) {   
 2955:                     unless (&File::Copy::move($source,$target)) {
 2956:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 2957:                         return "Moving from $source failed";
 2958:                     }
 2959:                 } else {
 2960:                     return "Temporary file: $source had unexpected date/time for last modification";
 2961:                 }
 2962:             } else {
 2963:                 return "Temporary file: $source missing";
 2964:             }
 2965:         } elsif (!print FH ($env{'form.'.$formname})) {
 2966: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 2967: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 2968: 	    return '/adm/notfound.html';
 2969: 	}
 2970: 	close(FH);
 2971:         if ($resizewidth && $resizeheight) {
 2972:             my $mm = new File::MMagic;
 2973:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 2974:             if ($mime_type =~ m{^image/}) {
 2975: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 2976:             }  
 2977: 	}
 2978:     }
 2979:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 2980:         if (ref($mimetype)) {
 2981:             if ($$mimetype eq '') {
 2982:                 my $mm = new File::MMagic;
 2983:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 2984:                 $$mimetype = $type;
 2985:             }
 2986:         }
 2987:     }
 2988:     if ($parser eq 'parse') {
 2989:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 2990:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 2991:                                                        $allfiles,$codebase);
 2992:             unless ($parse_result eq 'ok') {
 2993:                 &logthis('Failed to parse '.$filepath.$file.
 2994: 	   	         ' for embedded media: '.$parse_result); 
 2995:             }
 2996:         }
 2997:     }
 2998:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 2999:         my $input = $filepath.'/'.$file;
 3000:         my $output = $filepath.'/'.'tn-'.$file;
 3001:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 3002:         system("convert -sample $thumbsize $input $output");
 3003:         if (-e $filepath.'/'.'tn-'.$file) {
 3004:             $fetchthumb  = 1; 
 3005:         }
 3006:     }
 3007:  
 3008: # Notify homeserver to grep it
 3009: #
 3010:     my $docuhome=&homeserver($docuname,$docudom);	
 3011:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 3012:     if ($fetchresult eq 'ok') {
 3013:         if ($fetchthumb) {
 3014:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 3015:             if ($thumbresult ne 'ok') {
 3016:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 3017:                          $docuhome.': '.$thumbresult);
 3018:             }
 3019:         }
 3020: #
 3021: # Return the URL to it
 3022:         return '/uploaded/'.$path.$file;
 3023:     } else {
 3024:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 3025: 		 ': '.$fetchresult);
 3026:         return '/adm/notfound.html';
 3027:     }
 3028: }
 3029: 
 3030: sub extract_embedded_items {
 3031:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 3032:     my @state = ();
 3033:     my (%lastids,%related,%shockwave,%flashvars);
 3034:     my %javafiles = (
 3035:                       codebase => '',
 3036:                       code => '',
 3037:                       archive => ''
 3038:                     );
 3039:     my %mediafiles = (
 3040:                       src => '',
 3041:                       movie => '',
 3042:                      );
 3043:     my $p;
 3044:     if ($content) {
 3045:         $p = HTML::LCParser->new($content);
 3046:     } else {
 3047:         $p = HTML::LCParser->new($fullpath);
 3048:     }
 3049:     while (my $t=$p->get_token()) {
 3050: 	if ($t->[0] eq 'S') {
 3051: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 3052: 	    push(@state, $tagname);
 3053:             if (lc($tagname) eq 'allow') {
 3054:                 &add_filetype($allfiles,$attr->{'src'},'src');
 3055:             }
 3056: 	    if (lc($tagname) eq 'img') {
 3057: 		&add_filetype($allfiles,$attr->{'src'},'src');
 3058: 	    }
 3059: 	    if (lc($tagname) eq 'a') {
 3060: 		&add_filetype($allfiles,$attr->{'href'},'href');
 3061: 	    }
 3062:             if (lc($tagname) eq 'script') {
 3063:                 my $src;
 3064:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 3065:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 3066:                 } else {
 3067:                     if ($attr->{'src'} ne '') {
 3068:                         $src = $attr->{'src'};
 3069:                         &add_filetype($allfiles,$src,'src');
 3070:                     }
 3071:                 }
 3072:                 my $text = $p->get_trimmed_text();
 3073:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 3074:                     my @swfargs = split(/,/,$1);
 3075:                     foreach my $item (@swfargs) {
 3076:                         $item =~ s/["']//g;
 3077:                         $item =~ s/^\s+//;
 3078:                         $item =~ s/\s+$//;
 3079:                     }
 3080:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 3081:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 3082:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 3083:                         } else {
 3084:                             $related{$swfargs[0]} = [$swfargs[2]];
 3085:                         }
 3086:                     }
 3087:                 }
 3088:             }
 3089:             if (lc($tagname) eq 'link') {
 3090:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 3091:                     &add_filetype($allfiles,$attr->{'href'},'href');
 3092:                 }
 3093:             }
 3094: 	    if (lc($tagname) eq 'object' ||
 3095: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 3096: 		foreach my $item (keys(%javafiles)) {
 3097: 		    $javafiles{$item} = '';
 3098: 		}
 3099:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 3100:                     $lastids{lc($tagname)} = $attr->{'id'};
 3101:                 }
 3102: 	    }
 3103: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 3104: 		my $name = lc($attr->{'name'});
 3105: 		foreach my $item (keys(%javafiles)) {
 3106: 		    if ($name eq $item) {
 3107: 			$javafiles{$item} = $attr->{'value'};
 3108: 			last;
 3109: 		    }
 3110: 		}
 3111:                 my $pathfrom;
 3112: 		foreach my $item (keys(%mediafiles)) {
 3113: 		    if ($name eq $item) {
 3114:                         $pathfrom = $attr->{'value'};
 3115:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 3116: 			&add_filetype($allfiles,$pathfrom,$name);
 3117: 			last;
 3118: 		    }
 3119: 		}
 3120:                 if ($name eq 'flashvars') {
 3121:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 3122:                 }
 3123:                 if ($pathfrom ne '') {
 3124:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 3125:                                          $pathfrom);
 3126:                 }
 3127: 	    }
 3128: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 3129: 		foreach my $item (keys(%javafiles)) {
 3130: 		    if ($attr->{$item}) {
 3131: 			$javafiles{$item} = $attr->{$item};
 3132: 			last;
 3133: 		    }
 3134: 		}
 3135: 		foreach my $item (keys(%mediafiles)) {
 3136: 		    if ($attr->{$item}) {
 3137: 			&add_filetype($allfiles,$attr->{$item},$item);
 3138: 			last;
 3139: 		    }
 3140: 		}
 3141:                 if (lc($tagname) eq 'embed') {
 3142:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 3143:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 3144:                                              $attr->{'src'});
 3145:                     }
 3146:                 }
 3147: 	    }
 3148:             if ($t->[4] =~ m{/>$}) {
 3149:                 pop(@state);  
 3150:             }
 3151: 	} elsif ($t->[0] eq 'E') {
 3152: 	    my ($tagname) = ($t->[1]);
 3153: 	    if ($javafiles{'codebase'} ne '') {
 3154: 		$javafiles{'codebase'} .= '/';
 3155: 	    }  
 3156: 	    if (lc($tagname) eq 'applet' ||
 3157: 		lc($tagname) eq 'object' ||
 3158: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 3159: 		) {
 3160: 		foreach my $item (keys(%javafiles)) {
 3161: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 3162: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 3163: 			&add_filetype($allfiles,$file,$item);
 3164: 		    }
 3165: 		}
 3166: 	    } 
 3167: 	    pop @state;
 3168: 	}
 3169:     }
 3170:     foreach my $id (sort(keys(%flashvars))) {
 3171:         if ($shockwave{$id} ne '') {
 3172:             my @pairs = split(/\&/,$flashvars{$id});
 3173:             foreach my $pair (@pairs) {
 3174:                 my ($key,$value) = split(/\=/,$pair);
 3175:                 if ($key eq 'thumb') {
 3176:                     &add_filetype($allfiles,$value,$key);
 3177:                 } elsif ($key eq 'content') {
 3178:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 3179:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 3180:                     if ($ext ne '') {
 3181:                         &add_filetype($allfiles,$path.$value,$ext);
 3182:                     }
 3183:                 }
 3184:             }
 3185:         }
 3186:     }
 3187:     return 'ok';
 3188: }
 3189: 
 3190: sub add_filetype {
 3191:     my ($allfiles,$file,$type)=@_;
 3192:     if (exists($allfiles->{$file})) {
 3193: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 3194: 	    push(@{$allfiles->{$file}}, &escape($type));
 3195: 	}
 3196:     } else {
 3197: 	@{$allfiles->{$file}} = (&escape($type));
 3198:     }
 3199: }
 3200: 
 3201: sub embedded_dependency {
 3202:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 3203:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 3204:         if (($identifier ne '') &&
 3205:             (ref($related->{$identifier}) eq 'ARRAY') &&
 3206:             ($pathfrom ne '')) {
 3207:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 3208:             foreach my $dep (@{$related->{$identifier}}) {
 3209:                 &add_filetype($allfiles,$path.$dep,'object');
 3210:             }
 3211:         }
 3212:     }
 3213:     return;
 3214: }
 3215: 
 3216: sub removeuploadedurl {
 3217:     my ($url)=@_;	
 3218:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 3219:     return &removeuserfile($uname,$udom,$fname);
 3220: }
 3221: 
 3222: sub removeuserfile {
 3223:     my ($docuname,$docudom,$fname)=@_;
 3224:     my $home=&homeserver($docuname,$docudom);    
 3225:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 3226:     if ($result eq 'ok') {	
 3227:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 3228:             my $metafile = $fname.'.meta';
 3229:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 3230: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 3231:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 3232:             my $sqlresult = 
 3233:                 &update_portfolio_table($docuname,$docudom,$file,
 3234:                                         'portfolio_metadata',$group,
 3235:                                         'delete');
 3236:         }
 3237:     }
 3238:     return $result;
 3239: }
 3240: 
 3241: sub mkdiruserfile {
 3242:     my ($docuname,$docudom,$dir)=@_;
 3243:     my $home=&homeserver($docuname,$docudom);
 3244:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 3245: }
 3246: 
 3247: sub renameuserfile {
 3248:     my ($docuname,$docudom,$old,$new)=@_;
 3249:     my $home=&homeserver($docuname,$docudom);
 3250:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 3251:                         &escape("$old").':'.&escape("$new"),$home);
 3252:     if ($result eq 'ok') {
 3253:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 3254:             my $oldmeta = $old.'.meta';
 3255:             my $newmeta = $new.'.meta';
 3256:             my $metaresult = 
 3257:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 3258: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 3259:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 3260:             my $sqlresult = 
 3261:                 &update_portfolio_table($docuname,$docudom,$file,
 3262:                                         'portfolio_metadata',$group,
 3263:                                         'delete');
 3264:         }
 3265:     }
 3266:     return $result;
 3267: }
 3268: 
 3269: # ------------------------------------------------------------------------- Log
 3270: 
 3271: sub log {
 3272:     my ($dom,$nam,$hom,$what)=@_;
 3273:     return critical("log:$dom:$nam:$what",$hom);
 3274: }
 3275: 
 3276: # ------------------------------------------------------------------ Course Log
 3277: #
 3278: # This routine flushes several buffers of non-mission-critical nature
 3279: #
 3280: 
 3281: sub flushcourselogs {
 3282:     &logthis('Flushing log buffers');
 3283: #
 3284: # course logs
 3285: # This is a log of all transactions in a course, which can be used
 3286: # for data mining purposes
 3287: #
 3288: # It also collects the courseid database, which lists last transaction
 3289: # times and course titles for all courseids
 3290: #
 3291:     my %courseidbuffer=();
 3292:     foreach my $crsid (keys(%courselogs)) {
 3293:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 3294: 		          &escape($courselogs{$crsid}),
 3295: 		          $coursehombuf{$crsid}) eq 'ok') {
 3296: 	    delete $courselogs{$crsid};
 3297:         } else {
 3298:             &logthis('Failed to flush log buffer for '.$crsid);
 3299:             if (length($courselogs{$crsid})>40000) {
 3300:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 3301:                         " exceeded maximum size, deleting.</font>");
 3302:                delete $courselogs{$crsid};
 3303:             }
 3304:         }
 3305:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 3306:             'description' => $coursedescrbuf{$crsid},
 3307:             'inst_code'    => $courseinstcodebuf{$crsid},
 3308:             'type'        => $coursetypebuf{$crsid},
 3309:             'owner'       => $courseownerbuf{$crsid},
 3310:         };
 3311:     }
 3312: #
 3313: # Write course id database (reverse lookup) to homeserver of courses 
 3314: # Is used in pickcourse
 3315: #
 3316:     foreach my $crs_home (keys(%courseidbuffer)) {
 3317:         my $response = &courseidput(&host_domain($crs_home),
 3318:                                     $courseidbuffer{$crs_home},
 3319:                                     $crs_home,'timeonly');
 3320:     }
 3321: #
 3322: # File accesses
 3323: # Writes to the dynamic metadata of resources to get hit counts, etc.
 3324: #
 3325:     foreach my $entry (keys(%accesshash)) {
 3326:         if ($entry =~ /___count$/) {
 3327:             my ($dom,$name);
 3328:             ($dom,$name,undef)=
 3329: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 3330:             if (! defined($dom) || $dom eq '' || 
 3331:                 ! defined($name) || $name eq '') {
 3332:                 my $cid = $env{'request.course.id'};
 3333:                 $dom  = $env{'request.'.$cid.'.domain'};
 3334:                 $name = $env{'request.'.$cid.'.num'};
 3335:             }
 3336:             my $value = $accesshash{$entry};
 3337:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 3338:             my %temphash=($url => $value);
 3339:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 3340:             if ($result eq 'ok') {
 3341:                 delete $accesshash{$entry};
 3342:             }
 3343:         } else {
 3344:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 3345:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 3346:             my %temphash=($entry => $accesshash{$entry});
 3347:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 3348:                 delete $accesshash{$entry};
 3349:             }
 3350:         }
 3351:     }
 3352: #
 3353: # Roles
 3354: # Reverse lookup of user roles for course faculty/staff and co-authorship
 3355: #
 3356:     foreach my $entry (keys(%userrolehash)) {
 3357:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 3358: 	    split(/\:/,$entry);
 3359:         if (&Apache::lonnet::put('nohist_userroles',
 3360:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 3361:                 $rudom,$runame) eq 'ok') {
 3362: 	    delete $userrolehash{$entry};
 3363:         }
 3364:     }
 3365: #
 3366: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 3367: #
 3368:     my %domrolebuffer = ();
 3369:     foreach my $entry (keys(%domainrolehash)) {
 3370:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 3371:         if ($domrolebuffer{$rudom}) {
 3372:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 3373:                       '='.&escape($domainrolehash{$entry});
 3374:         } else {
 3375:             $domrolebuffer{$rudom}.=&escape($entry).
 3376:                       '='.&escape($domainrolehash{$entry});
 3377:         }
 3378:         delete $domainrolehash{$entry};
 3379:     }
 3380:     foreach my $dom (keys(%domrolebuffer)) {
 3381: 	my %servers = &get_servers($dom,'library');
 3382: 	foreach my $tryserver (keys(%servers)) {
 3383: 	    unless (&reply('domroleput:'.$dom.':'.
 3384: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 3385: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 3386: 	    }
 3387:         }
 3388:     }
 3389:     $dumpcount++;
 3390: }
 3391: 
 3392: sub courselog {
 3393:     my $what=shift;
 3394:     $what=time.':'.$what;
 3395:     unless ($env{'request.course.id'}) { return ''; }
 3396:     $coursedombuf{$env{'request.course.id'}}=
 3397:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 3398:     $coursenumbuf{$env{'request.course.id'}}=
 3399:        $env{'course.'.$env{'request.course.id'}.'.num'};
 3400:     $coursehombuf{$env{'request.course.id'}}=
 3401:        $env{'course.'.$env{'request.course.id'}.'.home'};
 3402:     $coursedescrbuf{$env{'request.course.id'}}=
 3403:        $env{'course.'.$env{'request.course.id'}.'.description'};
 3404:     $courseinstcodebuf{$env{'request.course.id'}}=
 3405:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 3406:     $courseownerbuf{$env{'request.course.id'}}=
 3407:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 3408:     $coursetypebuf{$env{'request.course.id'}}=
 3409:        $env{'course.'.$env{'request.course.id'}.'.type'};
 3410:     if (defined $courselogs{$env{'request.course.id'}}) {
 3411: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 3412:     } else {
 3413: 	$courselogs{$env{'request.course.id'}}.=$what;
 3414:     }
 3415:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 3416: 	&flushcourselogs();
 3417:     }
 3418: }
 3419: 
 3420: sub courseacclog {
 3421:     my $fnsymb=shift;
 3422:     unless ($env{'request.course.id'}) { return ''; }
 3423:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 3424:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 3425:         $what.=':POST';
 3426:         # FIXME: Probably ought to escape things....
 3427: 	foreach my $key (keys(%env)) {
 3428:             if ($key=~/^form\.(.*)/) {
 3429:                 my $formitem = $1;
 3430:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 3431:                     $what.=':'.$formitem.'='.$env{$key};
 3432:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 3433:                     $what.=':'.$formitem.'='.$env{$key};
 3434:                 }
 3435:             }
 3436:         }
 3437:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 3438:         # FIXME: We should not be depending on a form parameter that someone
 3439:         # editing lonsearchcat.pm might change in the future.
 3440:         if ($env{'form.phase'} eq 'course_search') {
 3441:             $what.= ':POST';
 3442:             # FIXME: Probably ought to escape things....
 3443:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 3444:                                  'crsdiscuss') {
 3445:                 $what.=':'.$element.'='.$env{'form.'.$element};
 3446:             }
 3447:         }
 3448:     }
 3449:     &courselog($what);
 3450: }
 3451: 
 3452: sub countacc {
 3453:     my $url=&declutter(shift);
 3454:     return if (! defined($url) || $url eq '');
 3455:     unless ($env{'request.course.id'}) { return ''; }
 3456: #
 3457: # Mark that this url was used in this course
 3458: #
 3459:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 3460: #
 3461: # Increase the access count for this resource in this child process
 3462: #
 3463:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 3464:     $accesshash{$key}++;
 3465: }
 3466: 
 3467: sub linklog {
 3468:     my ($from,$to)=@_;
 3469:     $from=&declutter($from);
 3470:     $to=&declutter($to);
 3471:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 3472:     $accesshash{$to.'___'.$from.'___goto'}=1;
 3473: }
 3474: 
 3475: sub statslog {
 3476:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 3477:     if ($users<2) { return; }
 3478:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 3479:             'course'       => $env{'request.course.id'},
 3480:             'sections'     => '"all"',
 3481:             'num_students' => $users,
 3482:             'part'         => $part,
 3483:             'symb'         => $symb,
 3484:             'mean_tries'   => $av_attempts,
 3485:             'deg_of_diff'  => $degdiff});
 3486:     foreach my $key (keys(%dynstore)) {
 3487:         $accesshash{$key}=$dynstore{$key};
 3488:     }
 3489: }
 3490:   
 3491: sub userrolelog {
 3492:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 3493:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
 3494:         ($trole=~/^in/) || ($trole=~/^cc/) ||
 3495:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
 3496:         ($trole=~/^ta/) || ($trole=~/^co/)) {
 3497:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 3498:        $userrolehash
 3499:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 3500:                     =$tend.':'.$tstart;
 3501:     }
 3502:     if (($env{'request.role'} =~ /dc\./) &&
 3503: 	(($trole=~/^au/) || ($trole=~/^in/) ||
 3504: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
 3505: 	 ($trole=~/^cr/) || ($trole=~/^ta/) ||
 3506:          ($trole=~/^co/))) {
 3507:        $userrolehash
 3508:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 3509:                     =$tend.':'.$tstart;
 3510:     }
 3511:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
 3512:         ($trole=~/^li/) || ($trole=~/^li/) ||
 3513:         ($trole=~/^au/) || ($trole=~/^dg/) ||
 3514:         ($trole=~/^sc/)) {
 3515:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 3516:        $domainrolehash
 3517:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 3518:                     = $tend.':'.$tstart;
 3519:     }
 3520: }
 3521: 
 3522: sub courserolelog {
 3523:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 3524:     if (($trole eq 'cc') || ($trole eq 'in') ||
 3525:         ($trole eq 'ep') || ($trole eq 'ad') ||
 3526:         ($trole eq 'ta') || ($trole eq 'st') ||
 3527:         ($trole=~/^cr/) || ($trole eq 'gr') ||
 3528:         ($trole eq 'co')) {
 3529:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 3530:             my $cdom = $1;
 3531:             my $cnum = $2;
 3532:             my $sec = $3;
 3533:             my $namespace = 'rolelog';
 3534:             my %storehash = (
 3535:                                role    => $trole,
 3536:                                start   => $tstart,
 3537:                                end     => $tend,
 3538:                                selfenroll => $selfenroll,
 3539:                                context    => $context,
 3540:                             );
 3541:             if ($trole eq 'gr') {
 3542:                 $namespace = 'groupslog';
 3543:                 $storehash{'group'} = $sec;
 3544:             } else {
 3545:                 $storehash{'section'} = $sec;
 3546:             }
 3547:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
 3548:             if (($trole ne 'st') || ($sec ne '')) {
 3549:                 &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 3550:             }
 3551:         }
 3552:     }
 3553:     return;
 3554: }
 3555: 
 3556: sub get_course_adv_roles {
 3557:     my ($cid,$codes) = @_;
 3558:     $cid=$env{'request.course.id'} unless (defined($cid));
 3559:     my %coursehash=&coursedescription($cid);
 3560:     my $crstype = &Apache::loncommon::course_type($cid);
 3561:     my %nothide=();
 3562:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3563:         if ($user !~ /:/) {
 3564: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 3565:         } else {
 3566:             $nothide{$user}=1;
 3567:         }
 3568:     }
 3569:     my %returnhash=();
 3570:     my %dumphash=
 3571:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 3572:     my $now=time;
 3573:     my %privileged;
 3574:     foreach my $entry (keys(%dumphash)) {
 3575: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 3576:         if (($tstart) && ($tstart<0)) { next; }
 3577:         if (($tend) && ($tend<$now)) { next; }
 3578:         if (($tstart) && ($now<$tstart)) { next; }
 3579:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 3580: 	if ($username eq '' || $domain eq '') { next; }
 3581:         unless (ref($privileged{$domain}) eq 'HASH') {
 3582:             my %dompersonnel =
 3583:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
 3584:             $privileged{$domain} = {};
 3585:             foreach my $server (keys(%dompersonnel)) {
 3586:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 3587:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
 3588:                         my ($trole,$uname,$udom) = split(/:/,$user);
 3589:                         $privileged{$udom}{$uname} = 1;
 3590:                     }
 3591:                 }
 3592:             }
 3593:         }
 3594:         if ((exists($privileged{$domain}{$username})) && 
 3595:             (!$nothide{$username.':'.$domain})) { next; }
 3596: 	if ($role eq 'cr') { next; }
 3597:         if ($codes) {
 3598:             if ($section) { $role .= ':'.$section; }
 3599:             if ($returnhash{$role}) {
 3600:                 $returnhash{$role}.=','.$username.':'.$domain;
 3601:             } else {
 3602:                 $returnhash{$role}=$username.':'.$domain;
 3603:             }
 3604:         } else {
 3605:             my $key=&plaintext($role,$crstype);
 3606:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 3607:             if ($returnhash{$key}) {
 3608: 	        $returnhash{$key}.=','.$username.':'.$domain;
 3609:             } else {
 3610:                 $returnhash{$key}=$username.':'.$domain;
 3611:             }
 3612:         }
 3613:     }
 3614:     return %returnhash;
 3615: }
 3616: 
 3617: sub get_my_roles {
 3618:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 3619:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 3620:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 3621:     my (%dumphash,%nothide);
 3622:     if ($context eq 'userroles') {
 3623:         my $extra = &freeze_escape({'skipcheck' => 1});
 3624:         %dumphash = &dump('roles',$udom,$uname,'.',undef,$extra);
 3625:     } else {
 3626:         %dumphash=
 3627:             &dump('nohist_userroles',$udom,$uname);
 3628:         if ($hidepriv) {
 3629:             my %coursehash=&coursedescription($udom.'_'.$uname);
 3630:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3631:                 if ($user !~ /:/) {
 3632:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 3633:                 } else {
 3634:                     $nothide{$user} = 1;
 3635:                 }
 3636:             }
 3637:         }
 3638:     }
 3639:     my %returnhash=();
 3640:     my $now=time;
 3641:     my %privileged;
 3642:     foreach my $entry (keys(%dumphash)) {
 3643:         my ($role,$tend,$tstart);
 3644:         if ($context eq 'userroles') {
 3645:             next if ($entry =~ /^rolesdef/);
 3646: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 3647:         } else {
 3648:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 3649:         }
 3650:         if (($tstart) && ($tstart<0)) { next; }
 3651:         my $status = 'active';
 3652:         if (($tend) && ($tend<=$now)) {
 3653:             $status = 'previous';
 3654:         } 
 3655:         if (($tstart) && ($now<$tstart)) {
 3656:             $status = 'future';
 3657:         }
 3658:         if (ref($types) eq 'ARRAY') {
 3659:             if (!grep(/^\Q$status\E$/,@{$types})) {
 3660:                 next;
 3661:             } 
 3662:         } else {
 3663:             if ($status ne 'active') {
 3664:                 next;
 3665:             }
 3666:         }
 3667:         my ($rolecode,$username,$domain,$section,$area);
 3668:         if ($context eq 'userroles') {
 3669:             ($area,$rolecode) = split(/_/,$entry);
 3670:             (undef,$domain,$username,$section) = split(/\//,$area);
 3671:         } else {
 3672:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 3673:         }
 3674:         if (ref($roledoms) eq 'ARRAY') {
 3675:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 3676:                 next;
 3677:             }
 3678:         }
 3679:         if (ref($roles) eq 'ARRAY') {
 3680:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 3681:                 if ($role =~ /^cr\//) {
 3682:                     if (!grep(/^cr$/,@{$roles})) {
 3683:                         next;
 3684:                     }
 3685:                 } elsif ($role =~ /^gr\//) {
 3686:                     if (!grep(/^gr$/,@{$roles})) {
 3687:                         next;
 3688:                     }
 3689:                 } else {
 3690:                     next;
 3691:                 }
 3692:             }
 3693:         }
 3694:         if ($hidepriv) {
 3695:             if ($context eq 'userroles') {
 3696:                 if ((&privileged($username,$domain)) &&
 3697:                     (!$nothide{$username.':'.$domain})) {
 3698:                     next;
 3699:                 }
 3700:             } else {
 3701:                 unless (ref($privileged{$domain}) eq 'HASH') {
 3702:                     my %dompersonnel =
 3703:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
 3704:                     $privileged{$domain} = {};
 3705:                     if (keys(%dompersonnel)) {
 3706:                         foreach my $server (keys(%dompersonnel)) {
 3707:                             if (ref($dompersonnel{$server}) eq 'HASH') {
 3708:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
 3709:                                     my ($trole,$uname,$udom) = split(/:/,$user);
 3710:                                     $privileged{$udom}{$uname} = $trole;
 3711:                                 }
 3712:                             }
 3713:                         }
 3714:                     }
 3715:                 }
 3716:                 if (exists($privileged{$domain}{$username})) {
 3717:                     if (!$nothide{$username.':'.$domain}) {
 3718:                         next;
 3719:                     }
 3720:                 }
 3721:             }
 3722:         }
 3723:         if ($withsec) {
 3724:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 3725:                 $tstart.':'.$tend;
 3726:         } else {
 3727:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 3728:         }
 3729:     }
 3730:     return %returnhash;
 3731: }
 3732: 
 3733: # ----------------------------------------------------- Frontpage Announcements
 3734: #
 3735: #
 3736: 
 3737: sub postannounce {
 3738:     my ($server,$text)=@_;
 3739:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 3740:     unless ($text=~/\w/) { $text=''; }
 3741:     return &reply('setannounce:'.&escape($text),$server);
 3742: }
 3743: 
 3744: sub getannounce {
 3745: 
 3746:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 3747: 	my $announcement='';
 3748: 	while (my $line = <$fh>) { $announcement .= $line; }
 3749: 	close($fh);
 3750: 	if ($announcement=~/\w/) { 
 3751: 	    return 
 3752:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 3753:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 3754: 	} else {
 3755: 	    return '';
 3756: 	}
 3757:     } else {
 3758: 	return '';
 3759:     }
 3760: }
 3761: 
 3762: # ---------------------------------------------------------- Course ID routines
 3763: # Deal with domain's nohist_courseid.db files
 3764: #
 3765: 
 3766: sub courseidput {
 3767:     my ($domain,$storehash,$coursehome,$caller) = @_;
 3768:     return unless (ref($storehash) eq 'HASH');
 3769:     my $outcome;
 3770:     if ($caller eq 'timeonly') {
 3771:         my $cids = '';
 3772:         foreach my $item (keys(%$storehash)) {
 3773:             $cids.=&escape($item).'&';
 3774:         }
 3775:         $cids=~s/\&$//;
 3776:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 3777:                           $coursehome);       
 3778:     } else {
 3779:         my $items = '';
 3780:         foreach my $item (keys(%$storehash)) {
 3781:             $items.= &escape($item).'='.
 3782:                      &freeze_escape($$storehash{$item}).'&';
 3783:         }
 3784:         $items=~s/\&$//;
 3785:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 3786:                           $coursehome);
 3787:     }
 3788:     if ($outcome eq 'unknown_cmd') {
 3789:         my $what;
 3790:         foreach my $cid (keys(%$storehash)) {
 3791:             $what .= &escape($cid).'=';
 3792:             foreach my $item ('description','inst_code','owner','type') {
 3793:                 $what .= &escape($storehash->{$cid}{$item}).':';
 3794:             }
 3795:             $what =~ s/\:$/&/;
 3796:         }
 3797:         $what =~ s/\&$//;  
 3798:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 3799:     } else {
 3800:         return $outcome;
 3801:     }
 3802: }
 3803: 
 3804: sub courseiddump {
 3805:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 3806:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 3807:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 3808:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
 3809:     my $as_hash = 1;
 3810:     my %returnhash;
 3811:     if (!$domfilter) { $domfilter=''; }
 3812:     my %libserv = &all_library();
 3813:     foreach my $tryserver (keys(%libserv)) {
 3814:         if ( (  $hostidflag == 1 
 3815: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 3816: 	     || (!defined($hostidflag)) ) {
 3817: 
 3818: 	    if (($domfilter eq '') ||
 3819: 		(&host_domain($tryserver) eq $domfilter)) {
 3820:                 my $rep = 
 3821:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
 3822:                          $sincefilter.':'.&escape($descfilter).':'.
 3823:                          &escape($instcodefilter).':'.&escape($ownerfilter).
 3824:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
 3825:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
 3826:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
 3827:                          $showhidden.':'.$caller.':'.&escape($cloner).':'.
 3828:                          &escape($cc_clone).':'.$cloneonly.':'.
 3829:                          &escape($createdbefore).':'.&escape($createdafter).':'.
 3830:                          &escape($creationcontext).':'.$domcloner,
 3831:                          $tryserver);
 3832:                 my @pairs=split(/\&/,$rep);
 3833:                 foreach my $item (@pairs) {
 3834:                     my ($key,$value)=split(/\=/,$item,2);
 3835:                     $key = &unescape($key);
 3836:                     next if ($key =~ /^error: 2 /);
 3837:                     my $result = &thaw_unescape($value);
 3838:                     if (ref($result) eq 'HASH') {
 3839:                         $returnhash{$key}=$result;
 3840:                     } else {
 3841:                         my @responses = split(/:/,$value);
 3842:                         my @items = ('description','inst_code','owner','type');
 3843:                         for (my $i=0; $i<@responses; $i++) {
 3844:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 3845:                         }
 3846:                     }
 3847:                 }
 3848:             }
 3849:         }
 3850:     }
 3851:     return %returnhash;
 3852: }
 3853: 
 3854: sub courselastaccess {
 3855:     my ($cdom,$cnum,$hostidref) = @_;
 3856:     my %returnhash;
 3857:     if ($cdom && $cnum) {
 3858:         my $chome = &homeserver($cnum,$cdom);
 3859:         if ($chome ne 'no_host') {
 3860:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 3861:             &extract_lastaccess(\%returnhash,$rep);
 3862:         }
 3863:     } else {
 3864:         if (!$cdom) { $cdom=''; }
 3865:         my %libserv = &all_library();
 3866:         foreach my $tryserver (keys(%libserv)) {
 3867:             if (ref($hostidref) eq 'ARRAY') {
 3868:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 3869:             } 
 3870:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 3871:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 3872:                 &extract_lastaccess(\%returnhash,$rep);
 3873:             }
 3874:         }
 3875:     }
 3876:     return %returnhash;
 3877: }
 3878: 
 3879: sub extract_lastaccess {
 3880:     my ($returnhash,$rep) = @_;
 3881:     if (ref($returnhash) eq 'HASH') {
 3882:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 3883:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 3884:                  $rep eq '') {
 3885:             my @pairs=split(/\&/,$rep);
 3886:             foreach my $item (@pairs) {
 3887:                 my ($key,$value)=split(/\=/,$item,2);
 3888:                 $key = &unescape($key);
 3889:                 next if ($key =~ /^error: 2 /);
 3890:                 $returnhash->{$key} = &thaw_unescape($value);
 3891:             }
 3892:         }
 3893:     }
 3894:     return;
 3895: }
 3896: 
 3897: # ---------------------------------------------------------- DC e-mail
 3898: 
 3899: sub dcmailput {
 3900:     my ($domain,$msgid,$message,$server)=@_;
 3901:     my $status = &Apache::lonnet::critical(
 3902:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 3903:        &escape($message),$server);
 3904:     return $status;
 3905: }
 3906: 
 3907: sub dcmaildump {
 3908:     my ($dom,$startdate,$enddate,$senders) = @_;
 3909:     my %returnhash=();
 3910: 
 3911:     if (defined(&domain($dom,'primary'))) {
 3912:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 3913:                                                          &escape($enddate).':';
 3914: 	my @esc_senders=map { &escape($_)} @$senders;
 3915: 	$cmd.=&escape(join('&',@esc_senders));
 3916: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 3917:             my ($key,$value) = split(/\=/,$line,2);
 3918:             if (($key) && ($value)) {
 3919:                 $returnhash{&unescape($key)} = &unescape($value);
 3920:             }
 3921:         }
 3922:     }
 3923:     return %returnhash;
 3924: }
 3925: # ---------------------------------------------------------- Domain roles
 3926: 
 3927: sub get_domain_roles {
 3928:     my ($dom,$roles,$startdate,$enddate)=@_;
 3929:     if ((!defined($startdate)) || ($startdate eq '')) {
 3930:         $startdate = '.';
 3931:     }
 3932:     if ((!defined($enddate)) || ($enddate eq '')) {
 3933:         $enddate = '.';
 3934:     }
 3935:     my $rolelist;
 3936:     if (ref($roles) eq 'ARRAY') {
 3937:         $rolelist = join(':',@{$roles});
 3938:     }
 3939:     my %personnel = ();
 3940: 
 3941:     my %servers = &get_servers($dom,'library');
 3942:     foreach my $tryserver (keys(%servers)) {
 3943: 	%{$personnel{$tryserver}}=();
 3944: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 3945: 					    &escape($startdate).':'.
 3946: 					    &escape($enddate).':'.
 3947: 					    &escape($rolelist), $tryserver))) {
 3948: 	    my ($key,$value) = split(/\=/,$line,2);
 3949: 	    if (($key) && ($value)) {
 3950: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 3951: 	    }
 3952: 	}
 3953:     }
 3954:     return %personnel;
 3955: }
 3956: 
 3957: # ----------------------------------------------------------- Interval timing 
 3958: 
 3959: {
 3960: # Caches needed for speedup of navmaps
 3961: # We don't want to cache this for very long at all (5 seconds at most)
 3962: # 
 3963: # The user for whom we cache
 3964: my $cachedkey='';
 3965: # The cached times for this user
 3966: my %cachedtimes=();
 3967: # When this was last done
 3968: my $cachedtime=();
 3969: 
 3970: sub load_all_first_access {
 3971:     my ($uname,$udom)=@_;
 3972:     if (($cachedkey eq $uname.':'.$udom) &&
 3973:         (abs($cachedtime-time)<5)) {
 3974:         return;
 3975:     }
 3976:     $cachedtime=time;
 3977:     $cachedkey=$uname.':'.$udom;
 3978:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 3979: }
 3980: 
 3981: sub get_first_access {
 3982:     my ($type,$argsymb,$argmap)=@_;
 3983:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 3984:     if ($argsymb) { $symb=$argsymb; }
 3985:     my ($map,$id,$res)=&decode_symb($symb);
 3986:     if ($argmap) { $map = $argmap; }
 3987:     if ($type eq 'course') {
 3988: 	$res='course';
 3989:     } elsif ($type eq 'map') {
 3990: 	$res=&symbread($map);
 3991:     } else {
 3992: 	$res=$symb;
 3993:     }
 3994:     &load_all_first_access($uname,$udom);
 3995:     return $cachedtimes{"$courseid\0$res"};
 3996: }
 3997: 
 3998: sub set_first_access {
 3999:     my ($type,$interval)=@_;
 4000:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 4001:     my ($map,$id,$res)=&decode_symb($symb);
 4002:     if ($type eq 'course') {
 4003: 	$res='course';
 4004:     } elsif ($type eq 'map') {
 4005: 	$res=&symbread($map);
 4006:     } else {
 4007: 	$res=$symb;
 4008:     }
 4009:     $cachedkey='';
 4010:     my $firstaccess=&get_first_access($type,$symb,$map);
 4011:     if (!$firstaccess) {
 4012:         my $start = time;
 4013: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 4014:                           $udom,$uname);
 4015:         if ($putres eq 'ok') {
 4016:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 4017:                  $udom,$uname); 
 4018:             &appenv(
 4019:                      {
 4020:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 4021:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 4022:                      }
 4023:                   );
 4024:         }
 4025:         return $putres;
 4026:     }
 4027:     return 'already_set';
 4028: }
 4029: }
 4030: # --------------------------------------------- Set Expire Date for Spreadsheet
 4031: 
 4032: sub expirespread {
 4033:     my ($uname,$udom,$stype,$usymb)=@_;
 4034:     my $cid=$env{'request.course.id'}; 
 4035:     if ($cid) {
 4036:        my $now=time;
 4037:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 4038:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 4039:                             $env{'course.'.$cid.'.num'}.
 4040: 	        	    ':nohist_expirationdates:'.
 4041:                             &escape($key).'='.$now,
 4042:                             $env{'course.'.$cid.'.home'})
 4043:     }
 4044:     return 'ok';
 4045: }
 4046: 
 4047: # ----------------------------------------------------- Devalidate Spreadsheets
 4048: 
 4049: sub devalidate {
 4050:     my ($symb,$uname,$udom)=@_;
 4051:     my $cid=$env{'request.course.id'}; 
 4052:     if ($cid) {
 4053:         # delete the stored spreadsheets for
 4054:         # - the student level sheet of this user in course's homespace
 4055:         # - the assessment level sheet for this resource 
 4056:         #   for this user in user's homespace
 4057: 	# - current conditional state info
 4058: 	my $key=$uname.':'.$udom.':';
 4059:         my $status=
 4060: 	    &del('nohist_calculatedsheets',
 4061: 		 [$key.'studentcalc:'],
 4062: 		 $env{'course.'.$cid.'.domain'},
 4063: 		 $env{'course.'.$cid.'.num'})
 4064: 		.' '.
 4065: 	    &del('nohist_calculatedsheets_'.$cid,
 4066: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 4067:         unless ($status eq 'ok ok') {
 4068:            &logthis('Could not devalidate spreadsheet '.
 4069:                     $uname.' at '.$udom.' for '.
 4070: 		    $symb.': '.$status);
 4071:         }
 4072: 	&delenv('user.state.'.$cid);
 4073:     }
 4074: }
 4075: 
 4076: sub get_scalar {
 4077:     my ($string,$end) = @_;
 4078:     my $value;
 4079:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 4080: 	$value = $1;
 4081:     } elsif ($$string =~ s/^([^&]*?)&//) {
 4082: 	$value = $1;
 4083:     }
 4084:     return &unescape($value);
 4085: }
 4086: 
 4087: sub array2str {
 4088:   my (@array) = @_;
 4089:   my $result=&arrayref2str(\@array);
 4090:   $result=~s/^__ARRAY_REF__//;
 4091:   $result=~s/__END_ARRAY_REF__$//;
 4092:   return $result;
 4093: }
 4094: 
 4095: sub arrayref2str {
 4096:   my ($arrayref) = @_;
 4097:   my $result='__ARRAY_REF__';
 4098:   foreach my $elem (@$arrayref) {
 4099:     if(ref($elem) eq 'ARRAY') {
 4100:       $result.=&arrayref2str($elem).'&';
 4101:     } elsif(ref($elem) eq 'HASH') {
 4102:       $result.=&hashref2str($elem).'&';
 4103:     } elsif(ref($elem)) {
 4104:       #print("Got a ref of ".(ref($elem))." skipping.");
 4105:     } else {
 4106:       $result.=&escape($elem).'&';
 4107:     }
 4108:   }
 4109:   $result=~s/\&$//;
 4110:   $result .= '__END_ARRAY_REF__';
 4111:   return $result;
 4112: }
 4113: 
 4114: sub hash2str {
 4115:   my (%hash) = @_;
 4116:   my $result=&hashref2str(\%hash);
 4117:   $result=~s/^__HASH_REF__//;
 4118:   $result=~s/__END_HASH_REF__$//;
 4119:   return $result;
 4120: }
 4121: 
 4122: sub hashref2str {
 4123:   my ($hashref)=@_;
 4124:   my $result='__HASH_REF__';
 4125:   foreach my $key (sort(keys(%$hashref))) {
 4126:     if (ref($key) eq 'ARRAY') {
 4127:       $result.=&arrayref2str($key).'=';
 4128:     } elsif (ref($key) eq 'HASH') {
 4129:       $result.=&hashref2str($key).'=';
 4130:     } elsif (ref($key)) {
 4131:       $result.='=';
 4132:       #print("Got a ref of ".(ref($key))." skipping.");
 4133:     } else {
 4134: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 4135:     }
 4136: 
 4137:     if(ref($hashref->{$key}) eq 'ARRAY') {
 4138:       $result.=&arrayref2str($hashref->{$key}).'&';
 4139:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 4140:       $result.=&hashref2str($hashref->{$key}).'&';
 4141:     } elsif(ref($hashref->{$key})) {
 4142:        $result.='&';
 4143:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 4144:     } else {
 4145:       $result.=&escape($hashref->{$key}).'&';
 4146:     }
 4147:   }
 4148:   $result=~s/\&$//;
 4149:   $result .= '__END_HASH_REF__';
 4150:   return $result;
 4151: }
 4152: 
 4153: sub str2hash {
 4154:     my ($string)=@_;
 4155:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 4156:     return %$hash;
 4157: }
 4158: 
 4159: sub str2hashref {
 4160:   my ($string) = @_;
 4161: 
 4162:   my %hash;
 4163: 
 4164:   if($string !~ /^__HASH_REF__/) {
 4165:       if (! ($string eq '' || !defined($string))) {
 4166: 	  $hash{'error'}='Not hash reference';
 4167:       }
 4168:       return (\%hash, $string);
 4169:   }
 4170: 
 4171:   $string =~ s/^__HASH_REF__//;
 4172: 
 4173:   while($string !~ /^__END_HASH_REF__/) {
 4174:       #key
 4175:       my $key='';
 4176:       if($string =~ /^__HASH_REF__/) {
 4177:           ($key, $string)=&str2hashref($string);
 4178:           if(defined($key->{'error'})) {
 4179:               $hash{'error'}='Bad data';
 4180:               return (\%hash, $string);
 4181:           }
 4182:       } elsif($string =~ /^__ARRAY_REF__/) {
 4183:           ($key, $string)=&str2arrayref($string);
 4184:           if($key->[0] eq 'Array reference error') {
 4185:               $hash{'error'}='Bad data';
 4186:               return (\%hash, $string);
 4187:           }
 4188:       } else {
 4189:           $string =~ s/^(.*?)=//;
 4190: 	  $key=&unescape($1);
 4191:       }
 4192:       $string =~ s/^=//;
 4193: 
 4194:       #value
 4195:       my $value='';
 4196:       if($string =~ /^__HASH_REF__/) {
 4197:           ($value, $string)=&str2hashref($string);
 4198:           if(defined($value->{'error'})) {
 4199:               $hash{'error'}='Bad data';
 4200:               return (\%hash, $string);
 4201:           }
 4202:       } elsif($string =~ /^__ARRAY_REF__/) {
 4203:           ($value, $string)=&str2arrayref($string);
 4204:           if($value->[0] eq 'Array reference error') {
 4205:               $hash{'error'}='Bad data';
 4206:               return (\%hash, $string);
 4207:           }
 4208:       } else {
 4209: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 4210:       }
 4211:       $string =~ s/^&//;
 4212: 
 4213:       $hash{$key}=$value;
 4214:   }
 4215: 
 4216:   $string =~ s/^__END_HASH_REF__//;
 4217: 
 4218:   return (\%hash, $string);
 4219: }
 4220: 
 4221: sub str2array {
 4222:     my ($string)=@_;
 4223:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 4224:     return @$array;
 4225: }
 4226: 
 4227: sub str2arrayref {
 4228:   my ($string) = @_;
 4229:   my @array;
 4230: 
 4231:   if($string !~ /^__ARRAY_REF__/) {
 4232:       if (! ($string eq '' || !defined($string))) {
 4233: 	  $array[0]='Array reference error';
 4234:       }
 4235:       return (\@array, $string);
 4236:   }
 4237: 
 4238:   $string =~ s/^__ARRAY_REF__//;
 4239: 
 4240:   while($string !~ /^__END_ARRAY_REF__/) {
 4241:       my $value='';
 4242:       if($string =~ /^__HASH_REF__/) {
 4243:           ($value, $string)=&str2hashref($string);
 4244:           if(defined($value->{'error'})) {
 4245:               $array[0] ='Array reference error';
 4246:               return (\@array, $string);
 4247:           }
 4248:       } elsif($string =~ /^__ARRAY_REF__/) {
 4249:           ($value, $string)=&str2arrayref($string);
 4250:           if($value->[0] eq 'Array reference error') {
 4251:               $array[0] ='Array reference error';
 4252:               return (\@array, $string);
 4253:           }
 4254:       } else {
 4255: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 4256:       }
 4257:       $string =~ s/^&//;
 4258: 
 4259:       push(@array, $value);
 4260:   }
 4261: 
 4262:   $string =~ s/^__END_ARRAY_REF__//;
 4263: 
 4264:   return (\@array, $string);
 4265: }
 4266: 
 4267: # -------------------------------------------------------------------Temp Store
 4268: 
 4269: sub tmpreset {
 4270:   my ($symb,$namespace,$domain,$stuname) = @_;
 4271:   if (!$symb) {
 4272:     $symb=&symbread();
 4273:     if (!$symb) { $symb= $env{'request.url'}; }
 4274:   }
 4275:   $symb=escape($symb);
 4276: 
 4277:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4278:   $namespace=~s/\//\_/g;
 4279:   $namespace=~s/\W//g;
 4280: 
 4281:   if (!$domain) { $domain=$env{'user.domain'}; }
 4282:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4283:   if ($domain eq 'public' && $stuname eq 'public') {
 4284:       $stuname=$ENV{'REMOTE_ADDR'};
 4285:   }
 4286:   my $path=LONCAPA::tempdir();
 4287:   my %hash;
 4288:   if (tie(%hash,'GDBM_File',
 4289: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4290: 	  &GDBM_WRCREAT(),0640)) {
 4291:     foreach my $key (keys(%hash)) {
 4292:       if ($key=~ /:$symb/) {
 4293: 	delete($hash{$key});
 4294:       }
 4295:     }
 4296:   }
 4297: }
 4298: 
 4299: sub tmpstore {
 4300:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4301: 
 4302:   if (!$symb) {
 4303:     $symb=&symbread();
 4304:     if (!$symb) { $symb= $env{'request.url'}; }
 4305:   }
 4306:   $symb=escape($symb);
 4307: 
 4308:   if (!$namespace) {
 4309:     # I don't think we would ever want to store this for a course.
 4310:     # it seems this will only be used if we don't have a course.
 4311:     #$namespace=$env{'request.course.id'};
 4312:     #if (!$namespace) {
 4313:       $namespace=$env{'request.state'};
 4314:     #}
 4315:   }
 4316:   $namespace=~s/\//\_/g;
 4317:   $namespace=~s/\W//g;
 4318:   if (!$domain) { $domain=$env{'user.domain'}; }
 4319:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4320:   if ($domain eq 'public' && $stuname eq 'public') {
 4321:       $stuname=$ENV{'REMOTE_ADDR'};
 4322:   }
 4323:   my $now=time;
 4324:   my %hash;
 4325:   my $path=LONCAPA::tempdir();
 4326:   if (tie(%hash,'GDBM_File',
 4327: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4328: 	  &GDBM_WRCREAT(),0640)) {
 4329:     $hash{"version:$symb"}++;
 4330:     my $version=$hash{"version:$symb"};
 4331:     my $allkeys=''; 
 4332:     foreach my $key (keys(%$storehash)) {
 4333:       $allkeys.=$key.':';
 4334:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 4335:     }
 4336:     $hash{"$version:$symb:timestamp"}=$now;
 4337:     $allkeys.='timestamp';
 4338:     $hash{"$version:keys:$symb"}=$allkeys;
 4339:     if (untie(%hash)) {
 4340:       return 'ok';
 4341:     } else {
 4342:       return "error:$!";
 4343:     }
 4344:   } else {
 4345:     return "error:$!";
 4346:   }
 4347: }
 4348: 
 4349: # -----------------------------------------------------------------Temp Restore
 4350: 
 4351: sub tmprestore {
 4352:   my ($symb,$namespace,$domain,$stuname) = @_;
 4353: 
 4354:   if (!$symb) {
 4355:     $symb=&symbread();
 4356:     if (!$symb) { $symb= $env{'request.url'}; }
 4357:   }
 4358:   $symb=escape($symb);
 4359: 
 4360:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4361: 
 4362:   if (!$domain) { $domain=$env{'user.domain'}; }
 4363:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4364:   if ($domain eq 'public' && $stuname eq 'public') {
 4365:       $stuname=$ENV{'REMOTE_ADDR'};
 4366:   }
 4367:   my %returnhash;
 4368:   $namespace=~s/\//\_/g;
 4369:   $namespace=~s/\W//g;
 4370:   my %hash;
 4371:   my $path=LONCAPA::tempdir();
 4372:   if (tie(%hash,'GDBM_File',
 4373: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4374: 	  &GDBM_READER(),0640)) {
 4375:     my $version=$hash{"version:$symb"};
 4376:     $returnhash{'version'}=$version;
 4377:     my $scope;
 4378:     for ($scope=1;$scope<=$version;$scope++) {
 4379:       my $vkeys=$hash{"$scope:keys:$symb"};
 4380:       my @keys=split(/:/,$vkeys);
 4381:       my $key;
 4382:       $returnhash{"$scope:keys"}=$vkeys;
 4383:       foreach $key (@keys) {
 4384: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4385: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4386:       }
 4387:     }
 4388:     if (!(untie(%hash))) {
 4389:       return "error:$!";
 4390:     }
 4391:   } else {
 4392:     return "error:$!";
 4393:   }
 4394:   return %returnhash;
 4395: }
 4396: 
 4397: # ----------------------------------------------------------------------- Store
 4398: 
 4399: sub store {
 4400:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4401:     my $home='';
 4402: 
 4403:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4404: 
 4405:     $symb=&symbclean($symb);
 4406:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 4407: 
 4408:     if (!$domain) { $domain=$env{'user.domain'}; }
 4409:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4410: 
 4411:     &devalidate($symb,$stuname,$domain);
 4412: 
 4413:     $symb=escape($symb);
 4414:     if (!$namespace) { 
 4415:        unless ($namespace=$env{'request.course.id'}) { 
 4416:           return ''; 
 4417:        } 
 4418:     }
 4419:     if (!$home) { $home=$env{'user.home'}; }
 4420: 
 4421:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 4422:     $$storehash{'host'}=$perlvar{'lonHostID'};
 4423: 
 4424:     my $namevalue='';
 4425:     foreach my $key (keys(%$storehash)) {
 4426:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4427:     }
 4428:     $namevalue=~s/\&$//;
 4429:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 4430:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 4431: }
 4432: 
 4433: # -------------------------------------------------------------- Critical Store
 4434: 
 4435: sub cstore {
 4436:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4437:     my $home='';
 4438: 
 4439:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4440: 
 4441:     $symb=&symbclean($symb);
 4442:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 4443: 
 4444:     if (!$domain) { $domain=$env{'user.domain'}; }
 4445:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4446: 
 4447:     &devalidate($symb,$stuname,$domain);
 4448: 
 4449:     $symb=escape($symb);
 4450:     if (!$namespace) { 
 4451:        unless ($namespace=$env{'request.course.id'}) { 
 4452:           return ''; 
 4453:        } 
 4454:     }
 4455:     if (!$home) { $home=$env{'user.home'}; }
 4456: 
 4457:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 4458:     $$storehash{'host'}=$perlvar{'lonHostID'};
 4459: 
 4460:     my $namevalue='';
 4461:     foreach my $key (keys(%$storehash)) {
 4462:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4463:     }
 4464:     $namevalue=~s/\&$//;
 4465:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 4466:     return critical
 4467:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 4468: }
 4469: 
 4470: # --------------------------------------------------------------------- Restore
 4471: 
 4472: sub restore {
 4473:     my ($symb,$namespace,$domain,$stuname) = @_;
 4474:     my $home='';
 4475: 
 4476:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4477: 
 4478:     if (!$symb) {
 4479:       unless ($symb=escape(&symbread())) { return ''; }
 4480:     } else {
 4481:       $symb=&escape(&symbclean($symb));
 4482:     }
 4483:     if (!$namespace) { 
 4484:        unless ($namespace=$env{'request.course.id'}) { 
 4485:           return ''; 
 4486:        } 
 4487:     }
 4488:     if (!$domain) { $domain=$env{'user.domain'}; }
 4489:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4490:     if (!$home) { $home=$env{'user.home'}; }
 4491:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 4492: 
 4493:     my %returnhash=();
 4494:     foreach my $line (split(/\&/,$answer)) {
 4495: 	my ($name,$value)=split(/\=/,$line);
 4496:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 4497:     }
 4498:     my $version;
 4499:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 4500:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 4501:           $returnhash{$item}=$returnhash{$version.':'.$item};
 4502:        }
 4503:     }
 4504:     return %returnhash;
 4505: }
 4506: 
 4507: # ---------------------------------------------------------- Course Description
 4508: #
 4509: #  
 4510: 
 4511: sub coursedescription {
 4512:     my ($courseid,$args)=@_;
 4513:     $courseid=~s/^\///;
 4514:     $courseid=~s/\_/\//g;
 4515:     my ($cdomain,$cnum)=split(/\//,$courseid);
 4516:     my $chome=&homeserver($cnum,$cdomain);
 4517:     my $normalid=$cdomain.'_'.$cnum;
 4518:     # need to always cache even if we get errors otherwise we keep 
 4519:     # trying and trying and trying to get the course description.
 4520:     my %envhash=();
 4521:     my %returnhash=();
 4522:     
 4523:     my $expiretime=600;
 4524:     if ($env{'request.course.id'} eq $normalid) {
 4525: 	$expiretime=120;
 4526:     }
 4527: 
 4528:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 4529:     if (!$args->{'freshen_cache'}
 4530: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 4531: 	foreach my $key (keys(%env)) {
 4532: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 4533: 	    my ($setting) = $1;
 4534: 	    $returnhash{$setting} = $env{$key};
 4535: 	}
 4536: 	return %returnhash;
 4537:     }
 4538: 
 4539:     # get the data again
 4540: 
 4541:     if (!$args->{'one_time'}) {
 4542: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 4543:     }
 4544: 
 4545:     if ($chome ne 'no_host') {
 4546:        %returnhash=&dump('environment',$cdomain,$cnum);
 4547:        if (!exists($returnhash{'con_lost'})) {
 4548: 	   my $username = $env{'user.name'}; # Defult username
 4549: 	   if(defined $args->{'user'}) {
 4550: 	       $username = $args->{'user'};
 4551: 	   }
 4552:            $returnhash{'home'}= $chome;
 4553: 	   $returnhash{'domain'} = $cdomain;
 4554: 	   $returnhash{'num'} = $cnum;
 4555:            if (!defined($returnhash{'type'})) {
 4556:                $returnhash{'type'} = 'Course';
 4557:            }
 4558:            while (my ($name,$value) = each %returnhash) {
 4559:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 4560:            }
 4561:            $returnhash{'url'}=&clutter($returnhash{'url'});
 4562:            $returnhash{'fn'}=LONCAPA::tempdir() .
 4563: 	       $username.'_'.$cdomain.'_'.$cnum;
 4564:            $envhash{'course.'.$normalid.'.home'}=$chome;
 4565:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 4566:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 4567:        }
 4568:     }
 4569:     if (!$args->{'one_time'}) {
 4570: 	&appenv(\%envhash);
 4571:     }
 4572:     return %returnhash;
 4573: }
 4574: 
 4575: sub update_released_required {
 4576:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 4577:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 4578:         $cid = $env{'request.course.id'};
 4579:         $cdom = $env{'course.'.$cid.'.domain'};
 4580:         $cnum = $env{'course.'.$cid.'.num'};
 4581:         $chome = $env{'course.'.$cid.'.home'};
 4582:     }
 4583:     if ($needsrelease) {
 4584:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 4585:         my $needsupdate;
 4586:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 4587:             $needsupdate = 1;
 4588:         } else {
 4589:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 4590:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 4591:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 4592:                 $needsupdate = 1;
 4593:             }
 4594:         }
 4595:         if ($needsupdate) {
 4596:             my %needshash = (
 4597:                              'internal.releaserequired' => $needsrelease,
 4598:                             );
 4599:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 4600:             if ($putresult eq 'ok') {
 4601:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 4602:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 4603:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 4604:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 4605:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 4606:                 }
 4607:             }
 4608:         }
 4609:     }
 4610:     return;
 4611: }
 4612: 
 4613: # -------------------------------------------------See if a user is privileged
 4614: 
 4615: sub privileged {
 4616:     my ($username,$domain)=@_;
 4617:     my $rolesdump=&reply("dump:$domain:$username:roles",
 4618: 			&homeserver($username,$domain));
 4619:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
 4620:         ($rolesdump =~ /^error:/)) {
 4621:         return 0;
 4622:     }
 4623:     my $now=time;
 4624:     if ($rolesdump ne '') {
 4625:         foreach my $entry (split(/&/,$rolesdump)) {
 4626: 	    if ($entry!~/^rolesdef_/) {
 4627: 		my ($area,$role)=split(/=/,$entry);
 4628: 		$area=~s/\_\w\w$//;
 4629: 		my ($trole,$tend,$tstart)=split(/_/,$role);
 4630: 		if (($trole eq 'dc') || ($trole eq 'su')) {
 4631: 		    my $active=1;
 4632: 		    if ($tend) {
 4633: 			if ($tend<$now) { $active=0; }
 4634: 		    }
 4635: 		    if ($tstart) {
 4636: 			if ($tstart>$now) { $active=0; }
 4637: 		    }
 4638: 		    if ($active) { return 1; }
 4639: 		}
 4640: 	    }
 4641: 	}
 4642:     }
 4643:     return 0;
 4644: }
 4645: 
 4646: # -------------------------------------------------------- Get user privileges
 4647: 
 4648: sub rolesinit {
 4649:     my ($domain,$username,$authhost)=@_;
 4650:     my $now=time;
 4651:     my %userroles = ('user.login.time' => $now);
 4652:     my $extra = &freeze_escape({'skipcheck' => 1});
 4653:     my $rolesdump=reply("dump:$domain:$username:roles:.::$extra",$authhost);
 4654:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
 4655:         ($rolesdump =~ /^error:/)) {
 4656:         return \%userroles;
 4657:     }
 4658:     my %firstaccess = &dump('firstaccesstimes',$domain,$username);
 4659:     my %timerinterval = &dump('timerinterval',$domain,$username);
 4660:     my (%coursetimerstarts,%firstaccchk,%firstaccenv,
 4661:         %coursetimerintervals,%timerintchk,%timerintenv);
 4662:     foreach my $key (keys(%firstaccess)) {
 4663:         my ($cid,$rest) = split(/\0/,$key);
 4664:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 4665:     }
 4666:     foreach my $key (keys(%timerinterval)) {
 4667:         my ($cid,$rest) = split(/\0/,$key);
 4668:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 4669:     }
 4670:     my %allroles=();
 4671:     my %allgroups=();
 4672: 
 4673:     if ($rolesdump ne '') {
 4674:         foreach my $entry (split(/&/,$rolesdump)) {
 4675: 	  if ($entry!~/^rolesdef_/) {
 4676:             my ($area,$role)=split(/=/,$entry);
 4677: 	    $area=~s/\_\w\w$//;
 4678:             my ($trole,$tend,$tstart,$group_privs);
 4679: 	    if ($role=~/^cr/) { 
 4680: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 4681: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
 4682: 		    ($tend,$tstart)=split('_',$trest);
 4683: 		} else {
 4684: 		    $trole=$role;
 4685: 		}
 4686:             } elsif ($role =~ m|^gr/|) {
 4687:                 ($trole,$tend,$tstart) = split(/_/,$role);
 4688:                 next if ($tstart eq '-1');
 4689:                 ($trole,$group_privs) = split(/\//,$trole);
 4690:                 $group_privs = &unescape($group_privs);
 4691: 	    } else {
 4692: 		($trole,$tend,$tstart)=split(/_/,$role);
 4693: 	    }
 4694: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 4695: 					 $username);
 4696: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 4697:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
 4698:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
 4699:             if (($area ne '') && ($trole ne '')) {
 4700: 		my $spec=$trole.'.'.$area;
 4701: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
 4702: 		if ($trole =~ /^cr\//) {
 4703:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 4704:                 } elsif ($trole eq 'gr') {
 4705:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 4706: 		} else {
 4707:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 4708: 		}
 4709:                 if ($trole ne 'gr') {
 4710:                     my $cid = $tdomain.'_'.$trest;
 4711:                     unless ($firstaccchk{$cid}) {
 4712:                         if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 4713:                             foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 4714:                                 $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 4715:                                     $coursetimerstarts{$cid}{$item}; 
 4716:                             }
 4717:                         }
 4718:                         $firstaccchk{$cid} = 1;
 4719:                     }
 4720:                     unless ($timerintchk{$cid}) {
 4721:                         if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 4722:                             foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 4723:                                 $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 4724:                                    $coursetimerintervals{$cid}{$item};
 4725:                             }
 4726:                         }
 4727:                         $timerintchk{$cid} = 1;
 4728:                     }
 4729:                 }
 4730:             }
 4731:           }
 4732:         }
 4733:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
 4734:         $userroles{'user.adv'}    = $adv;
 4735: 	$userroles{'user.author'} = $author;
 4736:         $env{'user.adv'}=$adv;
 4737:     }
 4738:     return (\%userroles,\%firstaccenv,\%timerintenv);
 4739: }
 4740: 
 4741: sub set_arearole {
 4742:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
 4743: # log the associated role with the area
 4744:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 4745:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 4746: }
 4747: 
 4748: sub custom_roleprivs {
 4749:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 4750:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 4751:     my $homsvr=homeserver($rauthor,$rdomain);
 4752:     if (&hostname($homsvr) ne '') {
 4753:         my ($rdummy,$roledef)=
 4754:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 4755:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 4756:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 4757:             if (defined($syspriv)) {
 4758:                 if ($trest =~ /^$match_community$/) {
 4759:                     $syspriv =~ s/bre\&S//; 
 4760:                 }
 4761:                 $$allroles{'cm./'}.=':'.$syspriv;
 4762:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 4763:             }
 4764:             if ($tdomain ne '') {
 4765:                 if (defined($dompriv)) {
 4766:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 4767:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 4768:                 }
 4769:                 if (($trest ne '') && (defined($coursepriv))) {
 4770:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 4771:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 4772:                 }
 4773:             }
 4774:         }
 4775:     }
 4776: }
 4777: 
 4778: sub group_roleprivs {
 4779:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 4780:     my $access = 1;
 4781:     my $now = time;
 4782:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 4783:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 4784:     if ($access) {
 4785:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 4786:         $$allgroups{$course}{$group} .=':'.$group_privs;
 4787:     }
 4788: }
 4789: 
 4790: sub standard_roleprivs {
 4791:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 4792:     if (defined($pr{$trole.':s'})) {
 4793:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 4794:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 4795:     }
 4796:     if ($tdomain ne '') {
 4797:         if (defined($pr{$trole.':d'})) {
 4798:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 4799:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 4800:         }
 4801:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 4802:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 4803:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 4804:         }
 4805:     }
 4806: }
 4807: 
 4808: sub set_userprivs {
 4809:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 4810:     my $author=0;
 4811:     my $adv=0;
 4812:     my %grouproles = ();
 4813:     if (keys(%{$allgroups}) > 0) {
 4814:         my @groupkeys; 
 4815:         foreach my $role (keys(%{$allroles})) {
 4816:             push(@groupkeys,$role);
 4817:         }
 4818:         if (ref($groups_roles) eq 'HASH') {
 4819:             foreach my $key (keys(%{$groups_roles})) {
 4820:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 4821:                     push(@groupkeys,$key);
 4822:                 }
 4823:             }
 4824:         }
 4825:         if (@groupkeys > 0) {
 4826:             foreach my $role (@groupkeys) {
 4827:                 my ($trole,$area,$sec,$extendedarea);
 4828:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 4829:                     $trole = $1;
 4830:                     $area = $2;
 4831:                     $sec = $3;
 4832:                     $extendedarea = $area.$sec;
 4833:                     if (exists($$allgroups{$area})) {
 4834:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 4835:                             my $spec = $trole.'.'.$extendedarea;
 4836:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 4837:                                                 $$allgroups{$area}{$group};
 4838:                         }
 4839:                     }
 4840:                 }
 4841:             }
 4842:         }
 4843:     }
 4844:     foreach my $group (keys(%grouproles)) {
 4845:         $$allroles{$group} = $grouproles{$group};
 4846:     }
 4847:     foreach my $role (keys(%{$allroles})) {
 4848:         my %thesepriv;
 4849:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 4850:         foreach my $item (split(/:/,$$allroles{$role})) {
 4851:             if ($item ne '') {
 4852:                 my ($privilege,$restrictions)=split(/&/,$item);
 4853:                 if ($restrictions eq '') {
 4854:                     $thesepriv{$privilege}='F';
 4855:                 } elsif ($thesepriv{$privilege} ne 'F') {
 4856:                     $thesepriv{$privilege}.=$restrictions;
 4857:                 }
 4858:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 4859:             }
 4860:         }
 4861:         my $thesestr='';
 4862:         foreach my $priv (sort(keys(%thesepriv))) {
 4863: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 4864: 	}
 4865:         $userroles->{'user.priv.'.$role} = $thesestr;
 4866:     }
 4867:     return ($author,$adv);
 4868: }
 4869: 
 4870: sub role_status {
 4871:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 4872:     my @pwhere = ();
 4873:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 4874:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
 4875:         unless (!defined($$role) || $$role eq '') {
 4876:             $$where=join('.',@pwhere);
 4877:             $$trolecode=$$role.'.'.$$where;
 4878:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 4879:             $$tstatus='is';
 4880:             if ($$tstart && $$tstart>$update) {
 4881:                 $$tstatus='future';
 4882:                 if ($$tstart<$now) {
 4883:                     if ($$tstart && $$tstart>$refresh) {
 4884:                         if (($$where ne '') && ($$role ne '')) {
 4885:                             my (%allroles,%allgroups,$group_privs,
 4886:                                 %groups_roles,@rolecodes);
 4887:                             my %userroles = (
 4888:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 4889:                             );
 4890:                             @rolecodes = ('cm'); 
 4891:                             my $spec=$$role.'.'.$$where;
 4892:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 4893:                             if ($$role =~ /^cr\//) {
 4894:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 4895:                                 push(@rolecodes,'cr');
 4896:                             } elsif ($$role eq 'gr') {
 4897:                                 push(@rolecodes,$$role);
 4898:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 4899:                                                     $env{'user.name'});
 4900:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 4901:                                 (undef,my $group_privs) = split(/\//,$trole);
 4902:                                 $group_privs = &unescape($group_privs);
 4903:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 4904:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 4905:                                 &get_groups_roles($tdomain,$trest,
 4906:                                                   \%course_roles,\@rolecodes,
 4907:                                                   \%groups_roles);
 4908:                             } else {
 4909:                                 push(@rolecodes,$$role);
 4910:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 4911:                             }
 4912:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
 4913:                             &appenv(\%userroles,\@rolecodes);
 4914:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 4915:                         }
 4916:                     }
 4917:                     $$tstatus = 'is';
 4918:                 }
 4919:             }
 4920:             if ($$tend) {
 4921:                 if ($$tend<$update) {
 4922:                     $$tstatus='expired';
 4923:                 } elsif ($$tend<$now) {
 4924:                     $$tstatus='will_not';
 4925:                 }
 4926:             }
 4927:         }
 4928:     }
 4929: }
 4930: 
 4931: sub get_groups_roles {
 4932:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 4933:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 4934:                   (ref($rolecodes) eq 'ARRAY') && 
 4935:                   (ref($groups_roles) eq 'HASH')); 
 4936:     if (keys(%{$cdom_courseroles}) > 0) {
 4937:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 4938:         if ($cdom ne '' && $cnum ne '') {
 4939:             foreach my $key (keys(%{$cdom_courseroles})) {
 4940:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 4941:                     my $crsrole = $1;
 4942:                     my $crssec = $2;
 4943:                     if ($crsrole =~ /^cr/) {
 4944:                         unless (grep(/^cr$/,@{$rolecodes})) {
 4945:                             push(@{$rolecodes},'cr');
 4946:                         }
 4947:                     } else {
 4948:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 4949:                             push(@{$rolecodes},$crsrole);
 4950:                         }
 4951:                     }
 4952:                     my $rolekey = "$crsrole./$cdom/$cnum";
 4953:                     if ($crssec ne '') {
 4954:                         $rolekey .= "/$crssec";
 4955:                     }
 4956:                     $rolekey .= './';
 4957:                     $groups_roles->{$rolekey} = $rolecodes;
 4958:                 }
 4959:             }
 4960:         }
 4961:     }
 4962:     return;
 4963: }
 4964: 
 4965: sub delete_env_groupprivs {
 4966:     my ($where,$courseroles,$possroles) = @_;
 4967:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 4968:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 4969:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 4970:         %{$courseroles->{$udom}} =
 4971:             &get_my_roles('','','userroles',['active'],
 4972:                           $possroles,[$udom],1);
 4973:     }
 4974:     if (ref($courseroles->{$udom}) eq 'HASH') {
 4975:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 4976:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 4977:             my $area = '/'.$cdom.'/'.$cnum;
 4978:             my $privkey = "user.priv.$crsrole.$area";
 4979:             if ($crssec ne '') {
 4980:                 $privkey .= '/'.$crssec;
 4981:             }
 4982:             $privkey .= ".$area/$group";
 4983:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 4984:         }
 4985:     }
 4986:     return;
 4987: }
 4988: 
 4989: sub check_adhoc_privs {
 4990:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
 4991:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 4992:     if ($env{$cckey}) {
 4993:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 4994:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 4995:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 4996:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 4997:         }
 4998:     } else {
 4999:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 5000:     }
 5001: }
 5002: 
 5003: sub set_adhoc_privileges {
 5004: # role can be cc or ca
 5005:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
 5006:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 5007:     my $spec = $role.'.'.$area;
 5008:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 5009:                                   $env{'user.name'});
 5010:     my %ccrole = ();
 5011:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
 5012:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
 5013:     &appenv(\%userroles,[$role,'cm']);
 5014:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 5015:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
 5016:         &appenv( {'request.role'        => $spec,
 5017:                   'request.role.domain' => $dcdom,
 5018:                   'request.course.sec'  => ''
 5019:                  }
 5020:                );
 5021:         my $tadv=0;
 5022:         if (&allowed('adv') eq 'F') { $tadv=1; }
 5023:         &appenv({'request.role.adv'    => $tadv});
 5024:     }
 5025: }
 5026: 
 5027: # --------------------------------------------------------------- get interface
 5028: 
 5029: sub get {
 5030:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5031:    my $items='';
 5032:    foreach my $item (@$storearr) {
 5033:        $items.=&escape($item).'&';
 5034:    }
 5035:    $items=~s/\&$//;
 5036:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5037:    if (!$uname) { $uname=$env{'user.name'}; }
 5038:    my $uhome=&homeserver($uname,$udomain);
 5039: 
 5040:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 5041:    my @pairs=split(/\&/,$rep);
 5042:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 5043:      return @pairs;
 5044:    }
 5045:    my %returnhash=();
 5046:    my $i=0;
 5047:    foreach my $item (@$storearr) {
 5048:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 5049:       $i++;
 5050:    }
 5051:    return %returnhash;
 5052: }
 5053: 
 5054: # --------------------------------------------------------------- del interface
 5055: 
 5056: sub del {
 5057:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5058:    my $items='';
 5059:    foreach my $item (@$storearr) {
 5060:        $items.=&escape($item).'&';
 5061:    }
 5062: 
 5063:    $items=~s/\&$//;
 5064:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5065:    if (!$uname) { $uname=$env{'user.name'}; }
 5066:    my $uhome=&homeserver($uname,$udomain);
 5067:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 5068: }
 5069: 
 5070: # -------------------------------------------------------------- dump interface
 5071: 
 5072: sub dump {
 5073:     my ($namespace,$udomain,$uname,$regexp,$range,$extra)=@_;
 5074:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5075:     if (!$uname) { $uname=$env{'user.name'}; }
 5076:     my $uhome=&homeserver($uname,$udomain);
 5077:     if ($regexp) {
 5078: 	$regexp=&escape($regexp);
 5079:     } else {
 5080: 	$regexp='.';
 5081:     }
 5082:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range:$extra",$uhome);
 5083:     my @pairs=split(/\&/,$rep);
 5084:     my %returnhash=();
 5085:     if (!($rep =~ /^error/ )) {
 5086: 	foreach my $item (@pairs) {
 5087: 	    my ($key,$value)=split(/=/,$item,2);
 5088: 	    $key = &unescape($key);
 5089: 	    next if ($key =~ /^error: 2 /);
 5090: 	    $returnhash{$key}=&thaw_unescape($value);
 5091: 	}
 5092:     }
 5093:     return %returnhash;
 5094: }
 5095: 
 5096: 
 5097: # --------------------------------------------------------- dumpstore interface
 5098: 
 5099: sub dumpstore {
 5100:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 5101:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5102:    if (!$uname) { $uname=$env{'user.name'}; }
 5103:    my $uhome=&homeserver($uname,$udomain);
 5104:    if ($regexp) {
 5105:        $regexp=&escape($regexp);
 5106:    } else {
 5107:        $regexp='.';
 5108:    }
 5109:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 5110:    my @pairs=split(/\&/,$rep);
 5111:    my %returnhash=();
 5112:    foreach my $item (@pairs) {
 5113:        my ($key,$value)=split(/=/,$item,2);
 5114:        next if ($key =~ /^error: 2 /);
 5115:        $returnhash{$key}=&thaw_unescape($value);
 5116:    }
 5117:    return %returnhash;
 5118: }
 5119: 
 5120: # -------------------------------------------------------------- keys interface
 5121: 
 5122: sub getkeys {
 5123:    my ($namespace,$udomain,$uname)=@_;
 5124:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5125:    if (!$uname) { $uname=$env{'user.name'}; }
 5126:    my $uhome=&homeserver($uname,$udomain);
 5127:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 5128:    my @keyarray=();
 5129:    foreach my $key (split(/\&/,$rep)) {
 5130:       next if ($key =~ /^error: 2 /);
 5131:       push(@keyarray,&unescape($key));
 5132:    }
 5133:    return @keyarray;
 5134: }
 5135: 
 5136: # --------------------------------------------------------------- currentdump
 5137: sub currentdump {
 5138:    my ($courseid,$sdom,$sname)=@_;
 5139:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 5140:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 5141:    $sname    = $env{'user.name'}         if (! defined($sname));
 5142:    my $uhome = &homeserver($sname,$sdom);
 5143:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 5144:    return if ($rep =~ /^(error:|no_such_host)/);
 5145:    #
 5146:    my %returnhash=();
 5147:    #
 5148:    if ($rep eq "unknown_cmd") { 
 5149:        # an old lond will not know currentdump
 5150:        # Do a dump and make it look like a currentdump
 5151:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 5152:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 5153:        my %hash = @tmp;
 5154:        @tmp=();
 5155:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 5156:    } else {
 5157:        my @pairs=split(/\&/,$rep);
 5158:        foreach my $pair (@pairs) {
 5159:            my ($key,$value)=split(/=/,$pair,2);
 5160:            my ($symb,$param) = split(/:/,$key);
 5161:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 5162:                                                         &thaw_unescape($value);
 5163:        }
 5164:    }
 5165:    return %returnhash;
 5166: }
 5167: 
 5168: sub convert_dump_to_currentdump{
 5169:     my %hash = %{shift()};
 5170:     my %returnhash;
 5171:     # Code ripped from lond, essentially.  The only difference
 5172:     # here is the unescaping done by lonnet::dump().  Conceivably
 5173:     # we might run in to problems with parameter names =~ /^v\./
 5174:     while (my ($key,$value) = each(%hash)) {
 5175:         my ($v,$symb,$param) = split(/:/,$key);
 5176: 	$symb  = &unescape($symb);
 5177: 	$param = &unescape($param);
 5178:         next if ($v eq 'version' || $symb eq 'keys');
 5179:         next if (exists($returnhash{$symb}) &&
 5180:                  exists($returnhash{$symb}->{$param}) &&
 5181:                  $returnhash{$symb}->{'v.'.$param} > $v);
 5182:         $returnhash{$symb}->{$param}=$value;
 5183:         $returnhash{$symb}->{'v.'.$param}=$v;
 5184:     }
 5185:     #
 5186:     # Remove all of the keys in the hashes which keep track of
 5187:     # the version of the parameter.
 5188:     while (my ($symb,$param_hash) = each(%returnhash)) {
 5189:         # use a foreach because we are going to delete from the hash.
 5190:         foreach my $key (keys(%$param_hash)) {
 5191:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 5192:         }
 5193:     }
 5194:     return \%returnhash;
 5195: }
 5196: 
 5197: # ------------------------------------------------------ critical inc interface
 5198: 
 5199: sub cinc {
 5200:     return &inc(@_,'critical');
 5201: }
 5202: 
 5203: # --------------------------------------------------------------- inc interface
 5204: 
 5205: sub inc {
 5206:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 5207:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5208:     if (!$uname) { $uname=$env{'user.name'}; }
 5209:     my $uhome=&homeserver($uname,$udomain);
 5210:     my $items='';
 5211:     if (! ref($store)) {
 5212:         # got a single value, so use that instead
 5213:         $items = &escape($store).'=&';
 5214:     } elsif (ref($store) eq 'SCALAR') {
 5215:         $items = &escape($$store).'=&';        
 5216:     } elsif (ref($store) eq 'ARRAY') {
 5217:         $items = join('=&',map {&escape($_);} @{$store});
 5218:     } elsif (ref($store) eq 'HASH') {
 5219:         while (my($key,$value) = each(%{$store})) {
 5220:             $items.= &escape($key).'='.&escape($value).'&';
 5221:         }
 5222:     }
 5223:     $items=~s/\&$//;
 5224:     if ($critical) {
 5225: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 5226:     } else {
 5227: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 5228:     }
 5229: }
 5230: 
 5231: # --------------------------------------------------------------- put interface
 5232: 
 5233: sub put {
 5234:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5235:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5236:    if (!$uname) { $uname=$env{'user.name'}; }
 5237:    my $uhome=&homeserver($uname,$udomain);
 5238:    my $items='';
 5239:    foreach my $item (keys(%$storehash)) {
 5240:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5241:    }
 5242:    $items=~s/\&$//;
 5243:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5244: }
 5245: 
 5246: # ------------------------------------------------------------ newput interface
 5247: 
 5248: sub newput {
 5249:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5250:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5251:    if (!$uname) { $uname=$env{'user.name'}; }
 5252:    my $uhome=&homeserver($uname,$udomain);
 5253:    my $items='';
 5254:    foreach my $key (keys(%$storehash)) {
 5255:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 5256:    }
 5257:    $items=~s/\&$//;
 5258:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 5259: }
 5260: 
 5261: # ---------------------------------------------------------  putstore interface
 5262: 
 5263: sub putstore {
 5264:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 5265:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5266:    if (!$uname) { $uname=$env{'user.name'}; }
 5267:    my $uhome=&homeserver($uname,$udomain);
 5268:    my $items='';
 5269:    foreach my $key (keys(%$storehash)) {
 5270:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 5271:    }
 5272:    $items=~s/\&$//;
 5273:    my $esc_symb=&escape($symb);
 5274:    my $esc_v=&escape($version);
 5275:    my $reply =
 5276:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 5277: 	      $uhome);
 5278:    if ($reply eq 'unknown_cmd') {
 5279:        # gfall back to way things use to be done
 5280:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 5281: 			    $uname);
 5282:    }
 5283:    return $reply;
 5284: }
 5285: 
 5286: sub old_putstore {
 5287:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 5288:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5289:     if (!$uname) { $uname=$env{'user.name'}; }
 5290:     my $uhome=&homeserver($uname,$udomain);
 5291:     my %newstorehash;
 5292:     foreach my $item (keys(%$storehash)) {
 5293: 	my $key = $version.':'.&escape($symb).':'.$item;
 5294: 	$newstorehash{$key} = $storehash->{$item};
 5295:     }
 5296:     my $items='';
 5297:     my %allitems = ();
 5298:     foreach my $item (keys(%newstorehash)) {
 5299: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 5300: 	    my $key = $1.':keys:'.$2;
 5301: 	    $allitems{$key} .= $3.':';
 5302: 	}
 5303: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 5304:     }
 5305:     foreach my $item (keys(%allitems)) {
 5306: 	$allitems{$item} =~ s/\:$//;
 5307: 	$items.= $item.'='.$allitems{$item}.'&';
 5308:     }
 5309:     $items=~s/\&$//;
 5310:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5311: }
 5312: 
 5313: # ------------------------------------------------------ critical put interface
 5314: 
 5315: sub cput {
 5316:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5317:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5318:    if (!$uname) { $uname=$env{'user.name'}; }
 5319:    my $uhome=&homeserver($uname,$udomain);
 5320:    my $items='';
 5321:    foreach my $item (keys(%$storehash)) {
 5322:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5323:    }
 5324:    $items=~s/\&$//;
 5325:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 5326: }
 5327: 
 5328: # -------------------------------------------------------------- eget interface
 5329: 
 5330: sub eget {
 5331:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5332:    my $items='';
 5333:    foreach my $item (@$storearr) {
 5334:        $items.=&escape($item).'&';
 5335:    }
 5336:    $items=~s/\&$//;
 5337:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5338:    if (!$uname) { $uname=$env{'user.name'}; }
 5339:    my $uhome=&homeserver($uname,$udomain);
 5340:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 5341:    my @pairs=split(/\&/,$rep);
 5342:    my %returnhash=();
 5343:    my $i=0;
 5344:    foreach my $item (@$storearr) {
 5345:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 5346:       $i++;
 5347:    }
 5348:    return %returnhash;
 5349: }
 5350: 
 5351: # ------------------------------------------------------------ tmpput interface
 5352: sub tmpput {
 5353:     my ($storehash,$server,$context)=@_;
 5354:     my $items='';
 5355:     foreach my $item (keys(%$storehash)) {
 5356: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5357:     }
 5358:     $items=~s/\&$//;
 5359:     if (defined($context)) {
 5360:         $items .= ':'.&escape($context);
 5361:     }
 5362:     return &reply("tmpput:$items",$server);
 5363: }
 5364: 
 5365: # ------------------------------------------------------------ tmpget interface
 5366: sub tmpget {
 5367:     my ($token,$server)=@_;
 5368:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 5369:     my $rep=&reply("tmpget:$token",$server);
 5370:     my %returnhash;
 5371:     foreach my $item (split(/\&/,$rep)) {
 5372: 	my ($key,$value)=split(/=/,$item);
 5373:         next if ($key =~ /^error: 2 /);
 5374: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 5375:     }
 5376:     return %returnhash;
 5377: }
 5378: 
 5379: # ------------------------------------------------------------ tmpdel interface
 5380: sub tmpdel {
 5381:     my ($token,$server)=@_;
 5382:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 5383:     return &reply("tmpdel:$token",$server);
 5384: }
 5385: 
 5386: # -------------------------------------------------- portfolio access checking
 5387: 
 5388: sub portfolio_access {
 5389:     my ($requrl) = @_;
 5390:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 5391:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 5392:     if ($result) {
 5393:         my %setters;
 5394:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 5395:             my ($startblock,$endblock) =
 5396:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 5397:             if ($startblock && $endblock) {
 5398:                 return 'B';
 5399:             }
 5400:         } else {
 5401:             my ($startblock,$endblock) =
 5402:                 &Apache::loncommon::blockcheck(\%setters,'port');
 5403:             if ($startblock && $endblock) {
 5404:                 return 'B';
 5405:             }
 5406:         }
 5407:     }
 5408:     if ($result eq 'ok') {
 5409:        return 'F';
 5410:     } elsif ($result =~ /^[^:]+:guest_/) {
 5411:        return 'A';
 5412:     }
 5413:     return '';
 5414: }
 5415: 
 5416: sub get_portfolio_access {
 5417:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 5418: 
 5419:     if (!ref($access_hash)) {
 5420: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 5421: 	my %access_controls = &get_access_controls($current_perms,$group,
 5422: 						   $file_name);
 5423: 	$access_hash = $access_controls{$file_name};
 5424:     }
 5425: 
 5426:     my ($public,$guest,@domains,@users,@courses,@groups);
 5427:     my $now = time;
 5428:     if (ref($access_hash) eq 'HASH') {
 5429:         foreach my $key (keys(%{$access_hash})) {
 5430:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 5431:             if ($start > $now) {
 5432:                 next;
 5433:             }
 5434:             if ($end && $end<$now) {
 5435:                 next;
 5436:             }
 5437:             if ($scope eq 'public') {
 5438:                 $public = $key;
 5439:                 last;
 5440:             } elsif ($scope eq 'guest') {
 5441:                 $guest = $key;
 5442:             } elsif ($scope eq 'domains') {
 5443:                 push(@domains,$key);
 5444:             } elsif ($scope eq 'users') {
 5445:                 push(@users,$key);
 5446:             } elsif ($scope eq 'course') {
 5447:                 push(@courses,$key);
 5448:             } elsif ($scope eq 'group') {
 5449:                 push(@groups,$key);
 5450:             }
 5451:         }
 5452:         if ($public) {
 5453:             return 'ok';
 5454:         }
 5455:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 5456:             if ($guest) {
 5457:                 return $guest;
 5458:             }
 5459:         } else {
 5460:             if (@domains > 0) {
 5461:                 foreach my $domkey (@domains) {
 5462:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 5463:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 5464:                             return 'ok';
 5465:                         }
 5466:                     }
 5467:                 }
 5468:             }
 5469:             if (@users > 0) {
 5470:                 foreach my $userkey (@users) {
 5471:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 5472:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 5473:                             if (ref($item) eq 'HASH') {
 5474:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 5475:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 5476:                                     return 'ok';
 5477:                                 }
 5478:                             }
 5479:                         }
 5480:                     } 
 5481:                 }
 5482:             }
 5483:             my %roleshash;
 5484:             my @courses_and_groups = @courses;
 5485:             push(@courses_and_groups,@groups); 
 5486:             if (@courses_and_groups > 0) {
 5487:                 my (%allgroups,%allroles); 
 5488:                 my ($start,$end,$role,$sec,$group);
 5489:                 foreach my $envkey (%env) {
 5490:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 5491:                         my $cid = $2.'_'.$3; 
 5492:                         if ($1 eq 'gr') {
 5493:                             $group = $4;
 5494:                             $allgroups{$cid}{$group} = $env{$envkey};
 5495:                         } else {
 5496:                             if ($4 eq '') {
 5497:                                 $sec = 'none';
 5498:                             } else {
 5499:                                 $sec = $4;
 5500:                             }
 5501:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 5502:                         }
 5503:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 5504:                         my $cid = $2.'_'.$3;
 5505:                         if ($4 eq '') {
 5506:                             $sec = 'none';
 5507:                         } else {
 5508:                             $sec = $4;
 5509:                         }
 5510:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 5511:                     }
 5512:                 }
 5513:                 if (keys(%allroles) == 0) {
 5514:                     return;
 5515:                 }
 5516:                 foreach my $key (@courses_and_groups) {
 5517:                     my %content = %{$$access_hash{$key}};
 5518:                     my $cnum = $content{'number'};
 5519:                     my $cdom = $content{'domain'};
 5520:                     my $cid = $cdom.'_'.$cnum;
 5521:                     if (!exists($allroles{$cid})) {
 5522:                         next;
 5523:                     }    
 5524:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 5525:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 5526:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 5527:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 5528:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 5529:                         foreach my $role (keys(%{$allroles{$cid}})) {
 5530:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 5531:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 5532:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 5533:                                         if (grep/^all$/,@sections) {
 5534:                                             return 'ok';
 5535:                                         } else {
 5536:                                             if (grep/^$sec$/,@sections) {
 5537:                                                 return 'ok';
 5538:                                             }
 5539:                                         }
 5540:                                     }
 5541:                                 }
 5542:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 5543:                                     if (grep/^none$/,@groups) {
 5544:                                         return 'ok';
 5545:                                     }
 5546:                                 } else {
 5547:                                     if (grep/^all$/,@groups) {
 5548:                                         return 'ok';
 5549:                                     } 
 5550:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 5551:                                         if (grep/^$group$/,@groups) {
 5552:                                             return 'ok';
 5553:                                         }
 5554:                                     }
 5555:                                 } 
 5556:                             }
 5557:                         }
 5558:                     }
 5559:                 }
 5560:             }
 5561:             if ($guest) {
 5562:                 return $guest;
 5563:             }
 5564:         }
 5565:     }
 5566:     return;
 5567: }
 5568: 
 5569: sub course_group_datechecker {
 5570:     my ($dates,$now,$status) = @_;
 5571:     my ($start,$end) = split(/\./,$dates);
 5572:     if (!$start && !$end) {
 5573:         return 'ok';
 5574:     }
 5575:     if (grep/^active$/,@{$status}) {
 5576:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 5577:             return 'ok';
 5578:         }
 5579:     }
 5580:     if (grep/^previous$/,@{$status}) {
 5581:         if ($end > $now ) {
 5582:             return 'ok';
 5583:         }
 5584:     }
 5585:     if (grep/^future$/,@{$status}) {
 5586:         if ($start > $now) {
 5587:             return 'ok';
 5588:         }
 5589:     }
 5590:     return; 
 5591: }
 5592: 
 5593: sub parse_portfolio_url {
 5594:     my ($url) = @_;
 5595: 
 5596:     my ($type,$udom,$unum,$group,$file_name);
 5597:     
 5598:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 5599: 	$type = 1;
 5600:         $udom = $1;
 5601:         $unum = $2;
 5602:         $file_name = $3;
 5603:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 5604: 	$type = 2;
 5605:         $udom = $1;
 5606:         $unum = $2;
 5607:         $group = $3;
 5608:         $file_name = $3.'/'.$4;
 5609:     }
 5610:     if (wantarray) {
 5611: 	return ($type,$udom,$unum,$file_name,$group);
 5612:     }
 5613:     return $type;
 5614: }
 5615: 
 5616: sub is_portfolio_url {
 5617:     my ($url) = @_;
 5618:     return scalar(&parse_portfolio_url($url));
 5619: }
 5620: 
 5621: sub is_portfolio_file {
 5622:     my ($file) = @_;
 5623:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 5624:         return 1;
 5625:     }
 5626:     return;
 5627: }
 5628: 
 5629: sub usertools_access {
 5630:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 5631:     my ($access,%tools);
 5632:     if ($context eq '') {
 5633:         $context = 'tools';
 5634:     }
 5635:     if ($context eq 'requestcourses') {
 5636:         %tools = (
 5637:                       official   => 1,
 5638:                       unofficial => 1,
 5639:                       community  => 1,
 5640:                  );
 5641:     } else {
 5642:         %tools = (
 5643:                       aboutme   => 1,
 5644:                       blog      => 1,
 5645:                       portfolio => 1,
 5646:                  );
 5647:     }
 5648:     return if (!defined($tools{$tool}));
 5649: 
 5650:     if ((!defined($udom)) || (!defined($uname))) {
 5651:         $udom = $env{'user.domain'};
 5652:         $uname = $env{'user.name'};
 5653:     }
 5654: 
 5655:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 5656:         if ($action ne 'reload') {
 5657:             if ($context eq 'requestcourses') {
 5658:                 return $env{'environment.canrequest.'.$tool};
 5659:             } else {
 5660:                 return $env{'environment.availabletools.'.$tool};
 5661:             }
 5662:         }
 5663:     }
 5664: 
 5665:     my ($toolstatus,$inststatus);
 5666: 
 5667:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 5668:          ($action ne 'reload')) {
 5669:         $toolstatus = $env{'environment.'.$context.'.'.$tool};
 5670:         $inststatus = $env{'environment.inststatus'};
 5671:     } else {
 5672:         if (ref($userenvref) eq 'HASH') {
 5673:             $toolstatus = $userenvref->{$context.'.'.$tool};
 5674:             $inststatus = $userenvref->{'inststatus'};
 5675:         } else {
 5676:             my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
 5677:             $toolstatus = $userenv{$context.'.'.$tool};
 5678:             $inststatus = $userenv{'inststatus'};
 5679:         }
 5680:     }
 5681: 
 5682:     if ($toolstatus ne '') {
 5683:         if ($toolstatus) {
 5684:             $access = 1;
 5685:         } else {
 5686:             $access = 0;
 5687:         }
 5688:         return $access;
 5689:     }
 5690: 
 5691:     my ($is_adv,%domdef);
 5692:     if (ref($is_advref) eq 'HASH') {
 5693:         $is_adv = $is_advref->{'is_adv'};
 5694:     } else {
 5695:         $is_adv = &is_advanced_user($udom,$uname);
 5696:     }
 5697:     if (ref($domdefref) eq 'HASH') {
 5698:         %domdef = %{$domdefref};
 5699:     } else {
 5700:         %domdef = &get_domain_defaults($udom);
 5701:     }
 5702:     if (ref($domdef{$tool}) eq 'HASH') {
 5703:         if ($is_adv) {
 5704:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 5705:                 if ($domdef{$tool}{'_LC_adv'}) { 
 5706:                     $access = 1;
 5707:                 } else {
 5708:                     $access = 0;
 5709:                 }
 5710:                 return $access;
 5711:             }
 5712:         }
 5713:         if ($inststatus ne '') {
 5714:             my ($hasaccess,$hasnoaccess);
 5715:             foreach my $affiliation (split(/:/,$inststatus)) {
 5716:                 if ($domdef{$tool}{$affiliation} ne '') { 
 5717:                     if ($domdef{$tool}{$affiliation}) {
 5718:                         $hasaccess = 1;
 5719:                     } else {
 5720:                         $hasnoaccess = 1;
 5721:                     }
 5722:                 }
 5723:             }
 5724:             if ($hasaccess || $hasnoaccess) {
 5725:                 if ($hasaccess) {
 5726:                     $access = 1;
 5727:                 } elsif ($hasnoaccess) {
 5728:                     $access = 0; 
 5729:                 }
 5730:                 return $access;
 5731:             }
 5732:         } else {
 5733:             if ($domdef{$tool}{'default'} ne '') {
 5734:                 if ($domdef{$tool}{'default'}) {
 5735:                     $access = 1;
 5736:                 } elsif ($domdef{$tool}{'default'} == 0) {
 5737:                     $access = 0;
 5738:                 }
 5739:                 return $access;
 5740:             }
 5741:         }
 5742:     } else {
 5743:         if ($context eq 'tools') {
 5744:             $access = 1;
 5745:         } else {
 5746:             $access = 0;
 5747:         }
 5748:         return $access;
 5749:     }
 5750: }
 5751: 
 5752: sub is_course_owner {
 5753:     my ($cdom,$cnum,$udom,$uname) = @_;
 5754:     if (($udom eq '') || ($uname eq '')) {
 5755:         $udom = $env{'user.domain'};
 5756:         $uname = $env{'user.name'};
 5757:     }
 5758:     unless (($udom eq '') || ($uname eq '')) {
 5759:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 5760:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 5761:                 return 1;
 5762:             } else {
 5763:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 5764:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 5765:                     return 1;
 5766:                 }
 5767:             }
 5768:         }
 5769:     }
 5770:     return;
 5771: }
 5772: 
 5773: sub is_advanced_user {
 5774:     my ($udom,$uname) = @_;
 5775:     if ($udom ne '' && $uname ne '') {
 5776:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 5777:             if (wantarray) {
 5778:                 return ($env{'user.adv'},$env{'user.author'});
 5779:             } else {
 5780:                 return $env{'user.adv'};
 5781:             }
 5782:         }
 5783:     }
 5784:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 5785:     my %allroles;
 5786:     my ($is_adv,$is_author);
 5787:     foreach my $role (keys(%roleshash)) {
 5788:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 5789:         my $area = '/'.$tdomain.'/'.$trest;
 5790:         if ($sec ne '') {
 5791:             $area .= '/'.$sec;
 5792:         }
 5793:         if (($area ne '') && ($trole ne '')) {
 5794:             my $spec=$trole.'.'.$area;
 5795:             if ($trole =~ /^cr\//) {
 5796:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 5797:             } elsif ($trole ne 'gr') {
 5798:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 5799:             }
 5800:             if ($trole eq 'au') {
 5801:                 $is_author = 1;
 5802:             }
 5803:         }
 5804:     }
 5805:     foreach my $role (keys(%allroles)) {
 5806:         last if ($is_adv);
 5807:         foreach my $item (split(/:/,$allroles{$role})) {
 5808:             if ($item ne '') {
 5809:                 my ($privilege,$restrictions)=split(/&/,$item);
 5810:                 if ($privilege eq 'adv') {
 5811:                     $is_adv = 1;
 5812:                     last;
 5813:                 }
 5814:             }
 5815:         }
 5816:     }
 5817:     if (wantarray) {
 5818:         return ($is_adv,$is_author);
 5819:     }
 5820:     return $is_adv;
 5821: }
 5822: 
 5823: sub check_can_request {
 5824:     my ($dom,$can_request,$request_domains) = @_;
 5825:     my $canreq = 0;
 5826:     my ($types,$typename) = &Apache::loncommon::course_types();
 5827:     my @options = ('approval','validate','autolimit');
 5828:     my $optregex = join('|',@options);
 5829:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 5830:         foreach my $type (@{$types}) {
 5831:             if (&usertools_access($env{'user.name'},
 5832:                                   $env{'user.domain'},
 5833:                                   $type,undef,'requestcourses')) {
 5834:                 $canreq ++;
 5835:                 if (ref($request_domains) eq 'HASH') {
 5836:                     push(@{$request_domains->{$type}},$env{'user.domain'});
 5837:                 }
 5838:                 if ($dom eq $env{'user.domain'}) {
 5839:                     $can_request->{$type} = 1;
 5840:                 }
 5841:             }
 5842:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
 5843:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 5844:                 if (@curr > 0) {
 5845:                     foreach my $item (@curr) {
 5846:                         if (ref($request_domains) eq 'HASH') {
 5847:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 5848:                             if ($otherdom ne '') {
 5849:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 5850:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 5851:                                         push(@{$request_domains->{$type}},$otherdom);
 5852:                                     }
 5853:                                 } else {
 5854:                                     push(@{$request_domains->{$type}},$otherdom);
 5855:                                 }
 5856:                             }
 5857:                         }
 5858:                     }
 5859:                     unless($dom eq $env{'user.domain'}) {
 5860:                         $canreq ++;
 5861:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 5862:                             $can_request->{$type} = 1;
 5863:                         }
 5864:                     }
 5865:                 }
 5866:             }
 5867:         }
 5868:     }
 5869:     return $canreq;
 5870: }
 5871: 
 5872: # ---------------------------------------------- Custom access rule evaluation
 5873: 
 5874: sub customaccess {
 5875:     my ($priv,$uri)=@_;
 5876:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 5877:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 5878:     $udom = &LONCAPA::clean_domain($udom);
 5879:     $ucrs = &LONCAPA::clean_username($ucrs);
 5880:     my $access=0;
 5881:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 5882: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 5883: 	if ($type eq 'user') {
 5884: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 5885: 		my ($tdom,$tuname)=split(m{/},$scope);
 5886: 		if ($tdom) {
 5887: 		    if ($tdom ne $env{'user.domain'}) { next; }
 5888: 		}
 5889: 		if ($tuname) {
 5890: 		    if ($tuname ne $env{'user.name'}) { next; }
 5891: 		}
 5892: 		$access=($effect eq 'allow');
 5893: 		last;
 5894: 	    }
 5895: 	} else {
 5896: 	    if ($role) {
 5897: 		if ($role ne $urole) { next; }
 5898: 	    }
 5899: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 5900: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 5901: 		if ($tdom) {
 5902: 		    if ($tdom ne $udom) { next; }
 5903: 		}
 5904: 		if ($tcrs) {
 5905: 		    if ($tcrs ne $ucrs) { next; }
 5906: 		}
 5907: 		if ($tsec) {
 5908: 		    if ($tsec ne $usec) { next; }
 5909: 		}
 5910: 		$access=($effect eq 'allow');
 5911: 		last;
 5912: 	    }
 5913: 	    if ($realm eq '' && $role eq '') {
 5914: 		$access=($effect eq 'allow');
 5915: 	    }
 5916: 	}
 5917:     }
 5918:     return $access;
 5919: }
 5920: 
 5921: # ------------------------------------------------- Check for a user privilege
 5922: 
 5923: sub allowed {
 5924:     my ($priv,$uri,$symb,$role)=@_;
 5925:     my $ver_orguri=$uri;
 5926:     $uri=&deversion($uri);
 5927:     my $orguri=$uri;
 5928:     $uri=&declutter($uri);
 5929: 
 5930:     if ($priv eq 'evb') {
 5931: # Evade communication block restrictions for specified role in a course
 5932:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 5933:             return $1;
 5934:         } else {
 5935:             return;
 5936:         }
 5937:     }
 5938: 
 5939:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 5940: # Free bre access to adm and meta resources
 5941:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 5942: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 5943: 	&& ($priv eq 'bre')) {
 5944: 	return 'F';
 5945:     }
 5946: 
 5947: # Free bre access to user's own portfolio contents
 5948:     my ($space,$domain,$name,@dir)=split('/',$uri);
 5949:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 5950: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 5951:         my %setters;
 5952:         my ($startblock,$endblock) = 
 5953:             &Apache::loncommon::blockcheck(\%setters,'port');
 5954:         if ($startblock && $endblock) {
 5955:             return 'B';
 5956:         } else {
 5957:             return 'F';
 5958:         }
 5959:     }
 5960: 
 5961: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 5962:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 5963:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 5964:         if (exists($env{'request.course.id'})) {
 5965:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5966:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5967:             if (($domain eq $cdom) && ($name eq $cnum)) {
 5968:                 my $courseprivid=$env{'request.course.id'};
 5969:                 $courseprivid=~s/\_/\//;
 5970:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 5971:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 5972:                     return $1; 
 5973:                 } else {
 5974:                     if ($env{'request.course.sec'}) {
 5975:                         $courseprivid.='/'.$env{'request.course.sec'};
 5976:                     }
 5977:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 5978:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 5979:                         return $2;
 5980:                     }
 5981:                 }
 5982:             }
 5983:         }
 5984:     }
 5985: 
 5986: # Free bre to public access
 5987: 
 5988:     if ($priv eq 'bre') {
 5989:         my $copyright=&metadata($uri,'copyright');
 5990: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 5991:            return 'F'; 
 5992:         }
 5993:         if ($copyright eq 'priv') {
 5994:             $uri=~/([^\/]+)\/([^\/]+)\//;
 5995: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 5996: 		return '';
 5997:             }
 5998:         }
 5999:         if ($copyright eq 'domain') {
 6000:             $uri=~/([^\/]+)\/([^\/]+)\//;
 6001: 	    unless (($env{'user.domain'} eq $1) ||
 6002:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 6003: 		return '';
 6004:             }
 6005:         }
 6006:         if ($env{'request.role'}=~ /li\.\//) {
 6007:             # Library role, so allow browsing of resources in this domain.
 6008:             return 'F';
 6009:         }
 6010:         if ($copyright eq 'custom') {
 6011: 	    unless (&customaccess($priv,$uri)) { return ''; }
 6012:         }
 6013:     }
 6014:     # Domain coordinator is trying to create a course
 6015:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 6016:         # uri is the requested domain in this case.
 6017:         # comparison to 'request.role.domain' shows if the user has selected
 6018:         # a role of dc for the domain in question.
 6019:         return 'F' if ($uri eq $env{'request.role.domain'});
 6020:     }
 6021: 
 6022:     my $thisallowed='';
 6023:     my $statecond=0;
 6024:     my $courseprivid='';
 6025: 
 6026:     my $ownaccess;
 6027:     # Community Coordinator or Assistant Co-author browsing resource space.
 6028:     if (($priv eq 'bro') && ($env{'user.author'})) {
 6029:         if ($uri eq '') {
 6030:             $ownaccess = 1;
 6031:         } else {
 6032:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 6033:                 my $udom = $env{'user.domain'};
 6034:                 my $uname = $env{'user.name'};
 6035:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 6036:                     $ownaccess = 1;
 6037:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 6038:                     unless ($uri =~ m{\.\./}) {
 6039:                         $ownaccess = 1;
 6040:                     }
 6041:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 6042:                     my $now = time;
 6043:                     if ($uri =~ m{^([^/]+)/?$}) {
 6044:                         my $adom = $1;
 6045:                         foreach my $key (keys(%env)) {
 6046:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 6047:                                 my ($start,$end) = split('.',$env{$key});
 6048:                                 if (($now >= $start) && (!$end || $end < $now)) {
 6049:                                     $ownaccess = 1;
 6050:                                     last;
 6051:                                 }
 6052:                             }
 6053:                         }
 6054:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 6055:                         my $adom = $1;
 6056:                         my $aname = $2;
 6057:                         foreach my $role ('ca','aa') { 
 6058:                             if ($env{"user.role.$role./$adom/$aname"}) {
 6059:                                 my ($start,$end) =
 6060:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 6061:                                 if (($now >= $start) && (!$end || $end < $now)) {
 6062:                                     $ownaccess = 1;
 6063:                                     last;
 6064:                                 }
 6065:                             }
 6066:                         }
 6067:                     }
 6068:                 }
 6069:             }
 6070:         }
 6071:     }
 6072: 
 6073: # Course
 6074: 
 6075:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 6076:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6077:             $thisallowed.=$1;
 6078:         }
 6079:     }
 6080: 
 6081: # Domain
 6082: 
 6083:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 6084:        =~/\Q$priv\E\&([^\:]*)/) {
 6085:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6086:             $thisallowed.=$1;
 6087:         }
 6088:     }
 6089: 
 6090: # User who is not author or co-author might still be able to edit
 6091: # resource of an author in the domain (e.g., if Domain Coordinator).
 6092:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 6093:         (&allowed('mdc',$env{'request.course.id'}))) {
 6094:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 6095:             $thisallowed.=$1;
 6096:         }
 6097:     }
 6098: 
 6099: # Course: uri itself is a course
 6100:     my $courseuri=$uri;
 6101:     $courseuri=~s/\_(\d)/\/$1/;
 6102:     $courseuri=~s/^([^\/])/\/$1/;
 6103: 
 6104:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 6105:        =~/\Q$priv\E\&([^\:]*)/) {
 6106:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6107:             $thisallowed.=$1;
 6108:         }
 6109:     }
 6110: 
 6111: # URI is an uploaded document for this course, default permissions don't matter
 6112: # not allowing 'edit' access (editupload) to uploaded course docs
 6113:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 6114: 	$thisallowed='';
 6115:         my ($match)=&is_on_map($uri);
 6116:         if ($match) {
 6117:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 6118:                   =~/\Q$priv\E\&([^\:]*)/) {
 6119:                 my @blockers = &has_comm_blocking($priv,$symb,$uri);
 6120:                 if (@blockers > 0) {
 6121:                     $thisallowed = 'B';
 6122:                 } else {
 6123:                     $thisallowed.=$1;
 6124:                 }
 6125:             }
 6126:         } else {
 6127:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 6128:             if ($refuri) {
 6129:                 if ($refuri =~ m|^/adm/|) {
 6130:                     $thisallowed='F';
 6131:                 } else {
 6132:                     $refuri=&declutter($refuri);
 6133:                     my ($match) = &is_on_map($refuri);
 6134:                     if ($match) {
 6135:                         my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 6136:                         if (@blockers > 0) {
 6137:                             $thisallowed = 'B';
 6138:                         } else {
 6139:                             $thisallowed='F';
 6140:                         }
 6141:                     }
 6142:                 }
 6143:             }
 6144:         }
 6145:     }
 6146: 
 6147:     if ($priv eq 'bre'
 6148: 	&& $thisallowed ne 'F' 
 6149: 	&& $thisallowed ne '2'
 6150: 	&& &is_portfolio_url($uri)) {
 6151: 	$thisallowed = &portfolio_access($uri);
 6152:     }
 6153:     
 6154: # Full access at system, domain or course-wide level? Exit.
 6155:     if ($thisallowed=~/F/) {
 6156: 	return 'F';
 6157:     }
 6158: 
 6159: # If this is generating or modifying users, exit with special codes
 6160: 
 6161:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 6162: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 6163: 	    my ($audom,$auname)=split('/',$uri);
 6164: # no author name given, so this just checks on the general right to make a co-author in this domain
 6165: 	    unless ($auname) { return $thisallowed; }
 6166: # an author name is given, so we are about to actually make a co-author for a certain account
 6167: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 6168: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 6169: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 6170: 	}
 6171: 	return $thisallowed;
 6172:     }
 6173: #
 6174: # Gathered so far: system, domain and course wide privileges
 6175: #
 6176: # Course: See if uri or referer is an individual resource that is part of 
 6177: # the course
 6178: 
 6179:     if ($env{'request.course.id'}) {
 6180: 
 6181:        $courseprivid=$env{'request.course.id'};
 6182:        if ($env{'request.course.sec'}) {
 6183:           $courseprivid.='/'.$env{'request.course.sec'};
 6184:        }
 6185:        $courseprivid=~s/\_/\//;
 6186:        my $checkreferer=1;
 6187:        my ($match,$cond)=&is_on_map($uri);
 6188:        if ($match) {
 6189:            $statecond=$cond;
 6190:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 6191:                =~/\Q$priv\E\&([^\:]*)/) {
 6192:                my $value = $1;
 6193:                if ($priv eq 'bre') {
 6194:                    my @blockers = &has_comm_blocking($priv,$symb,$uri);
 6195:                    if (@blockers > 0) {
 6196:                        $thisallowed = 'B';
 6197:                    } else {
 6198:                        $thisallowed.=$value;
 6199:                    }
 6200:                } else {
 6201:                    $thisallowed.=$value;
 6202:                }
 6203:                $checkreferer=0;
 6204:            }
 6205:        }
 6206:        
 6207:        if ($checkreferer) {
 6208: 	  my $refuri=$env{'httpref.'.$orguri};
 6209:             unless ($refuri) {
 6210:                 foreach my $key (keys(%env)) {
 6211: 		    if ($key=~/^httpref\..*\*/) {
 6212: 			my $pattern=$key;
 6213:                         $pattern=~s/^httpref\.\/res\///;
 6214:                         $pattern=~s/\*/\[\^\/\]\+/g;
 6215:                         $pattern=~s/\//\\\//g;
 6216:                         if ($orguri=~/$pattern/) {
 6217: 			    $refuri=$env{$key};
 6218:                         }
 6219:                     }
 6220:                 }
 6221:             }
 6222: 
 6223:          if ($refuri) { 
 6224: 	  $refuri=&declutter($refuri);
 6225:           my ($match,$cond)=&is_on_map($refuri);
 6226:             if ($match) {
 6227:               my $refstatecond=$cond;
 6228:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 6229:                   =~/\Q$priv\E\&([^\:]*)/) {
 6230:                   my $value = $1;
 6231:                   if ($priv eq 'bre') {
 6232:                       my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 6233:                       if (@blockers > 0) {
 6234:                           $thisallowed = 'B';
 6235:                       } else {
 6236:                           $thisallowed.=$value;
 6237:                       }
 6238:                   } else {
 6239:                       $thisallowed.=$value;
 6240:                   }
 6241:                   $uri=$refuri;
 6242:                   $statecond=$refstatecond;
 6243:               }
 6244:           }
 6245:         }
 6246:        }
 6247:    }
 6248: 
 6249: #
 6250: # Gathered now: all privileges that could apply, and condition number
 6251: # 
 6252: #
 6253: # Full or no access?
 6254: #
 6255: 
 6256:     if ($thisallowed=~/F/) {
 6257: 	return 'F';
 6258:     }
 6259: 
 6260:     unless ($thisallowed) {
 6261:         return '';
 6262:     }
 6263: 
 6264: # Restrictions exist, deal with them
 6265: #
 6266: #   C:according to course preferences
 6267: #   R:according to resource settings
 6268: #   L:unless locked
 6269: #   X:according to user session state
 6270: #
 6271: 
 6272: # Possibly locked functionality, check all courses
 6273: # Locks might take effect only after 10 minutes cache expiration for other
 6274: # courses, and 2 minutes for current course
 6275: 
 6276:     my $envkey;
 6277:     if ($thisallowed=~/L/) {
 6278:         foreach $envkey (keys(%env)) {
 6279:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 6280:                my $courseid=$2;
 6281:                my $roleid=$1.'.'.$2;
 6282:                $courseid=~s/^\///;
 6283:                my $expiretime=600;
 6284:                if ($env{'request.role'} eq $roleid) {
 6285: 		  $expiretime=120;
 6286:                }
 6287: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 6288:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 6289:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 6290: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 6291:                }
 6292:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 6293:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 6294: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 6295:                        &log($env{'user.domain'},$env{'user.name'},
 6296:                             $env{'user.home'},
 6297:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 6298:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 6299:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 6300: 		       return '';
 6301:                    }
 6302:                }
 6303:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 6304:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 6305: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 6306:                        &log($env{'user.domain'},$env{'user.name'},
 6307:                             $env{'user.home'},
 6308:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 6309:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 6310:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 6311: 		       return '';
 6312:                    }
 6313:                }
 6314: 	   }
 6315:        }
 6316:     }
 6317:    
 6318: #
 6319: # Rest of the restrictions depend on selected course
 6320: #
 6321: 
 6322:     unless ($env{'request.course.id'}) {
 6323: 	if ($thisallowed eq 'A') {
 6324: 	    return 'A';
 6325:         } elsif ($thisallowed eq 'B') {
 6326:             return 'B';
 6327: 	} else {
 6328: 	    return '1';
 6329: 	}
 6330:     }
 6331: 
 6332: #
 6333: # Now user is definitely in a course
 6334: #
 6335: 
 6336: 
 6337: # Course preferences
 6338: 
 6339:    if ($thisallowed=~/C/) {
 6340:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 6341:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 6342:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 6343: 	   =~/\Q$rolecode\E/) {
 6344: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6345: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 6346: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 6347: 			$env{'request.course.id'});
 6348: 	   }
 6349:            return '';
 6350:        }
 6351: 
 6352:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 6353: 	   =~/\Q$unamedom\E/) {
 6354: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6355: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 6356: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 6357: 			$env{'request.course.id'});
 6358: 	   }
 6359:            return '';
 6360:        }
 6361:    }
 6362: 
 6363: # Resource preferences
 6364: 
 6365:    if ($thisallowed=~/R/) {
 6366:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 6367:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 6368: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6369: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 6370: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 6371: 	   }
 6372: 	   return '';
 6373:        }
 6374:    }
 6375: 
 6376: # Restricted by state or randomout?
 6377: 
 6378:    if ($thisallowed=~/X/) {
 6379:       if ($env{'acc.randomout'}) {
 6380: 	 if (!$symb) { $symb=&symbread($uri,1); }
 6381:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 6382:             return ''; 
 6383:          }
 6384:       }
 6385:       if (&condval($statecond)) {
 6386: 	 return '2';
 6387:       } else {
 6388:          return '';
 6389:       }
 6390:    }
 6391: 
 6392:     if ($thisallowed eq 'A') {
 6393: 	return 'A';
 6394:     } elsif ($thisallowed eq 'B') {
 6395:         return 'B';
 6396:     }
 6397:    return 'F';
 6398: }
 6399: 
 6400: sub get_comm_blocks {
 6401:     my ($cdom,$cnum) = @_;
 6402:     if ($cdom eq '' || $cnum eq '') {
 6403:         return unless ($env{'request.course.id'});
 6404:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6405:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6406:     }
 6407:     my %commblocks;
 6408:     my $hashid=$cdom.'_'.$cnum;
 6409:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 6410:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 6411:         %commblocks = %{$blocksref};
 6412:     } else {
 6413:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 6414:         my $cachetime = 600;
 6415:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 6416:     }
 6417:     return %commblocks;
 6418: }
 6419: 
 6420: sub has_comm_blocking {
 6421:     my ($priv,$symb,$uri,$blocks) = @_;
 6422:     return unless ($env{'request.course.id'});
 6423:     return unless ($priv eq 'bre');
 6424:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 6425:     my %commblocks;
 6426:     if (ref($blocks) eq 'HASH') {
 6427:         %commblocks = %{$blocks};
 6428:     } else {
 6429:         %commblocks = &get_comm_blocks();
 6430:     }
 6431:     return unless (keys(%commblocks) > 0);
 6432:     if (!$symb) { $symb=&symbread($uri,1); }
 6433:     my ($map,$resid,undef)=&decode_symb($symb);
 6434:     my %tocheck = (
 6435:                     maps      => $map,
 6436:                     resources => $symb,
 6437:                   );
 6438:     my @blockers;
 6439:     my $now = time;
 6440:     my $navmap = Apache::lonnavmaps::navmap->new();
 6441:     foreach my $block (keys(%commblocks)) {
 6442:         if ($block =~ /^(\d+)____(\d+)$/) {
 6443:             my ($start,$end) = ($1,$2);
 6444:             if ($start <= $now && $end >= $now) {
 6445:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 6446:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 6447:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 6448:                             if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
 6449:                                 unless (grep(/^\Q$block\E$/,@blockers)) {
 6450:                                     push(@blockers,$block);
 6451:                                 }
 6452:                             }
 6453:                         }
 6454:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 6455:                             if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
 6456:                                 unless (grep(/^\Q$block\E$/,@blockers)) {  
 6457:                                     push(@blockers,$block);
 6458:                                 }
 6459:                             }
 6460:                         }
 6461:                     }
 6462:                 }
 6463:             }
 6464:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 6465:             my $item = $1;
 6466:             my @to_test;
 6467:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 6468:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 6469:                     my $check_interval;
 6470:                     if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
 6471:                         my @interval;
 6472:                         my $type = 'map';
 6473:                         if ($item eq 'course') {
 6474:                             $type = 'course';
 6475:                             @interval=&EXT("resource.0.interval");
 6476:                         } else {
 6477:                             if ($item =~ /___\d+___/) {
 6478:                                 $type = 'resource';
 6479:                                 @interval=&EXT("resource.0.interval",$item);
 6480:                                 if (ref($navmap)) {                        
 6481:                                     my $res = $navmap->getBySymb($item); 
 6482:                                     push(@to_test,$res);
 6483:                                 }
 6484:                             } else {
 6485:                                 my $mapsymb = &symbread($item,1);
 6486:                                 if ($mapsymb) {
 6487:                                     if (ref($navmap)) {
 6488:                                         my $mapres = $navmap->getBySymb($mapsymb);
 6489:                                         @to_test = $mapres->retrieveResources($mapres,undef,0,1);
 6490:                                         foreach my $res (@to_test) {
 6491:                                             my $symb = $res->symb();
 6492:                                             next if ($symb eq $mapsymb);
 6493:                                             if ($symb ne '') {
 6494:                                                 @interval=&EXT("resource.0.interval",$symb);
 6495:                                                 last;
 6496:                                             }
 6497:                                         }
 6498:                                     }
 6499:                                 }
 6500:                             }
 6501:                         }
 6502:                         if ($interval[0] =~ /\d+/) {
 6503:                             my $first_access;
 6504:                             if ($type eq 'resource') {
 6505:                                 $first_access=&get_first_access($interval[1],$item);
 6506:                             } elsif ($type eq 'map') {
 6507:                                 $first_access=&get_first_access($interval[1],undef,$item);
 6508:                             } else {
 6509:                                 $first_access=&get_first_access($interval[1]);
 6510:                             }
 6511:                             if ($first_access) {
 6512:                                 my $timesup = $first_access+$interval[0];
 6513:                                 if ($timesup > $now) {
 6514:                                     foreach my $res (@to_test) {
 6515:                                         if ($res->is_problem()) {
 6516:                                             if ($res->completable()) {
 6517:                                                 unless (grep(/^\Q$block\E$/,@blockers)) {
 6518:                                                     push(@blockers,$block);
 6519:                                                 }
 6520:                                                 last;
 6521:                                             }
 6522:                                         }
 6523:                                     }
 6524:                                 }
 6525:                             }
 6526:                         }
 6527:                     }
 6528:                 }
 6529:             }
 6530:         }
 6531:     }
 6532:     return @blockers;
 6533: }
 6534: 
 6535: sub check_docs_block {
 6536:     my ($docsblock,$tocheck) =@_;
 6537:     if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
 6538:         return;
 6539:     }
 6540:     if (ref($docsblock->{'maps'}) eq 'HASH') {
 6541:         if ($tocheck->{'maps'}) {
 6542:             if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
 6543:                 return 1;
 6544:             }
 6545:         }
 6546:     }
 6547:     if (ref($docsblock->{'resources'}) eq 'HASH') {
 6548:         if ($tocheck->{'resources'}) {
 6549:             if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
 6550:                 return 1;
 6551:             }
 6552:         }
 6553:     }
 6554:     return;
 6555: }
 6556: 
 6557: #
 6558: #   Removes the versino from a URI and
 6559: #   splits it in to its filename and path to the filename.
 6560: #   Seems like File::Basename could have done this more clearly.
 6561: #   Parameters:
 6562: #      $uri   - input URI
 6563: #   Returns:
 6564: #     Two element list consisting of 
 6565: #     $pathname  - the URI up to and excluding the trailing /
 6566: #     $filename  - The part of the URI following the last /
 6567: #  NOTE:
 6568: #    Another realization of this is simply:
 6569: #    use File::Basename;
 6570: #    ...
 6571: #    $uri = shift;
 6572: #    $filename = basename($uri);
 6573: #    $path     = dirname($uri);
 6574: #    return ($filename, $path);
 6575: #
 6576: #     The implementation below is probably faster however.
 6577: #
 6578: sub split_uri_for_cond {
 6579:     my $uri=&deversion(&declutter(shift));
 6580:     my @uriparts=split(/\//,$uri);
 6581:     my $filename=pop(@uriparts);
 6582:     my $pathname=join('/',@uriparts);
 6583:     return ($pathname,$filename);
 6584: }
 6585: # --------------------------------------------------- Is a resource on the map?
 6586: 
 6587: sub is_on_map {
 6588:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 6589:     #Trying to find the conditional for the file
 6590:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 6591: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 6592:     if ($match) {
 6593: 	return (1,$1);
 6594:     } else {
 6595: 	return (0,0);
 6596:     }
 6597: }
 6598: 
 6599: # --------------------------------------------------------- Get symb from alias
 6600: 
 6601: sub get_symb_from_alias {
 6602:     my $symb=shift;
 6603:     my ($map,$resid,$url)=&decode_symb($symb);
 6604: # Already is a symb
 6605:     if ($url) { return $symb; }
 6606: # Must be an alias
 6607:     my $aliassymb='';
 6608:     my %bighash;
 6609:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6610:                             &GDBM_READER(),0640)) {
 6611:         my $rid=$bighash{'mapalias_'.$symb};
 6612: 	if ($rid) {
 6613: 	    my ($mapid,$resid)=split(/\./,$rid);
 6614: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 6615: 				    $resid,$bighash{'src_'.$rid});
 6616: 	}
 6617:         untie %bighash;
 6618:     }
 6619:     return $aliassymb;
 6620: }
 6621: 
 6622: # ----------------------------------------------------------------- Define Role
 6623: 
 6624: sub definerole {
 6625:   if (allowed('mcr','/')) {
 6626:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 6627:     foreach my $role (split(':',$sysrole)) {
 6628: 	my ($crole,$cqual)=split(/\&/,$role);
 6629:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 6630:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 6631: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 6632:                return "refused:s:$crole&$cqual"; 
 6633:             }
 6634:         }
 6635:     }
 6636:     foreach my $role (split(':',$domrole)) {
 6637: 	my ($crole,$cqual)=split(/\&/,$role);
 6638:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 6639:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 6640: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 6641:                return "refused:d:$crole&$cqual"; 
 6642:             }
 6643:         }
 6644:     }
 6645:     foreach my $role (split(':',$courole)) {
 6646: 	my ($crole,$cqual)=split(/\&/,$role);
 6647:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 6648:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 6649: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 6650:                return "refused:c:$crole&$cqual"; 
 6651:             }
 6652:         }
 6653:     }
 6654:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 6655:                 "$env{'user.domain'}:$env{'user.name'}:".
 6656: 	        "rolesdef_$rolename=".
 6657:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 6658:     return reply($command,$env{'user.home'});
 6659:   } else {
 6660:     return 'refused';
 6661:   }
 6662: }
 6663: 
 6664: # ---------------- Make a metadata query against the network of library servers
 6665: 
 6666: sub metadata_query {
 6667:     my ($query,$custom,$customshow,$server_array)=@_;
 6668:     my %rhash;
 6669:     my %libserv = &all_library();
 6670:     my @server_list = (defined($server_array) ? @$server_array
 6671:                                               : keys(%libserv) );
 6672:     for my $server (@server_list) {
 6673: 	unless ($custom or $customshow) {
 6674: 	    my $reply=&reply("querysend:".&escape($query),$server);
 6675: 	    $rhash{$server}=$reply;
 6676: 	}
 6677: 	else {
 6678: 	    my $reply=&reply("querysend:".&escape($query).':'.
 6679: 			     &escape($custom).':'.&escape($customshow),
 6680: 			     $server);
 6681: 	    $rhash{$server}=$reply;
 6682: 	}
 6683:     }
 6684:     return \%rhash;
 6685: }
 6686: 
 6687: # ----------------------------------------- Send log queries and wait for reply
 6688: 
 6689: sub log_query {
 6690:     my ($uname,$udom,$query,%filters)=@_;
 6691:     my $uhome=&homeserver($uname,$udom);
 6692:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 6693:     my $uhost=&hostname($uhome);
 6694:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 6695:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 6696:                        $uhome);
 6697:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 6698:     return get_query_reply($queryid);
 6699: }
 6700: 
 6701: # -------------------------- Update MySQL table for portfolio file
 6702: 
 6703: sub update_portfolio_table {
 6704:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 6705:     if ($group ne '') {
 6706:         $file_name =~s /^\Q$group\E//;
 6707:     }
 6708:     my $homeserver = &homeserver($uname,$udom);
 6709:     my $queryid=
 6710:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 6711:                ':'.&escape($file_name).':'.$action,$homeserver);
 6712:     my $reply = &get_query_reply($queryid);
 6713:     return $reply;
 6714: }
 6715: 
 6716: # -------------------------- Update MySQL allusers table
 6717: 
 6718: sub update_allusers_table {
 6719:     my ($uname,$udom,$names) = @_;
 6720:     my $homeserver = &homeserver($uname,$udom);
 6721:     my $queryid=
 6722:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 6723:                'lastname='.&escape($names->{'lastname'}).'%%'.
 6724:                'firstname='.&escape($names->{'firstname'}).'%%'.
 6725:                'middlename='.&escape($names->{'middlename'}).'%%'.
 6726:                'generation='.&escape($names->{'generation'}).'%%'.
 6727:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 6728:                'id='.&escape($names->{'id'}),$homeserver);
 6729:     return;
 6730: }
 6731: 
 6732: # ------- Request retrieval of institutional classlists for course(s)
 6733: 
 6734: sub fetch_enrollment_query {
 6735:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 6736:     my $homeserver;
 6737:     my $maxtries = 1;
 6738:     if ($context eq 'automated') {
 6739:         $homeserver = $perlvar{'lonHostID'};
 6740:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 6741:     } else {
 6742:         $homeserver = &homeserver($cnum,$dom);
 6743:     }
 6744:     my $host=&hostname($homeserver);
 6745:     my $cmd = '';
 6746:     foreach my $affiliate (keys(%{$affiliatesref})) {
 6747:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 6748:     }
 6749:     $cmd =~ s/%%$//;
 6750:     $cmd = &escape($cmd);
 6751:     my $query = 'fetchenrollment';
 6752:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 6753:     unless ($queryid=~/^\Q$host\E\_/) { 
 6754:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 6755:         return 'error: '.$queryid;
 6756:     }
 6757:     my $reply = &get_query_reply($queryid);
 6758:     my $tries = 1;
 6759:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 6760:         $reply = &get_query_reply($queryid);
 6761:         $tries ++;
 6762:     }
 6763:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 6764:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 6765:     } else {
 6766:         my @responses = split(/:/,$reply);
 6767:         if ($homeserver eq $perlvar{'lonHostID'}) {
 6768:             foreach my $line (@responses) {
 6769:                 my ($key,$value) = split(/=/,$line,2);
 6770:                 $$replyref{$key} = $value;
 6771:             }
 6772:         } else {
 6773:             my $pathname = LONCAPA::tempdir();
 6774:             foreach my $line (@responses) {
 6775:                 my ($key,$value) = split(/=/,$line);
 6776:                 $$replyref{$key} = $value;
 6777:                 if ($value > 0) {
 6778:                     foreach my $item (@{$$affiliatesref{$key}}) {
 6779:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 6780:                         my $destname = $pathname.'/'.$filename;
 6781:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 6782:                         if ($xml_classlist =~ /^error/) {
 6783:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 6784:                         } else {
 6785:                             if ( open(FILE,">$destname") ) {
 6786:                                 print FILE &unescape($xml_classlist);
 6787:                                 close(FILE);
 6788:                             } else {
 6789:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 6790:                             }
 6791:                         }
 6792:                     }
 6793:                 }
 6794:             }
 6795:         }
 6796:         return 'ok';
 6797:     }
 6798:     return 'error';
 6799: }
 6800: 
 6801: sub get_query_reply {
 6802:     my $queryid=shift;
 6803:     my $replyfile=LONCAPA::tempdir().$queryid;
 6804:     my $reply='';
 6805:     for (1..100) {
 6806: 	sleep 2;
 6807:         if (-e $replyfile.'.end') {
 6808: 	    if (open(my $fh,$replyfile)) {
 6809: 		$reply = join('',<$fh>);
 6810: 		close($fh);
 6811: 	   } else { return 'error: reply_file_error'; }
 6812:            return &unescape($reply);
 6813: 	}
 6814:     }
 6815:     return 'timeout:'.$queryid;
 6816: }
 6817: 
 6818: sub courselog_query {
 6819: #
 6820: # possible filters:
 6821: # url: url or symb
 6822: # username
 6823: # domain
 6824: # action: view, submit, grade
 6825: # start: timestamp
 6826: # end: timestamp
 6827: #
 6828:     my (%filters)=@_;
 6829:     unless ($env{'request.course.id'}) { return 'no_course'; }
 6830:     if ($filters{'url'}) {
 6831: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 6832:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 6833:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 6834:     }
 6835:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6836:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6837:     return &log_query($cname,$cdom,'courselog',%filters);
 6838: }
 6839: 
 6840: sub userlog_query {
 6841: #
 6842: # possible filters:
 6843: # action: log check role
 6844: # start: timestamp
 6845: # end: timestamp
 6846: #
 6847:     my ($uname,$udom,%filters)=@_;
 6848:     return &log_query($uname,$udom,'userlog',%filters);
 6849: }
 6850: 
 6851: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 6852: 
 6853: sub auto_run {
 6854:     my ($cnum,$cdom) = @_;
 6855:     my $response = 0;
 6856:     my $settings;
 6857:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 6858:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 6859:         $settings = $domconfig{'autoenroll'};
 6860:         if ($settings->{'run'} eq '1') {
 6861:             $response = 1;
 6862:         }
 6863:     } else {
 6864:         my $homeserver;
 6865:         if (&is_course($cdom,$cnum)) {
 6866:             $homeserver = &homeserver($cnum,$cdom);
 6867:         } else {
 6868:             $homeserver = &domain($cdom,'primary');
 6869:         }
 6870:         if ($homeserver ne 'no_host') {
 6871:             $response = &reply('autorun:'.$cdom,$homeserver);
 6872:         }
 6873:     }
 6874:     return $response;
 6875: }
 6876: 
 6877: sub auto_get_sections {
 6878:     my ($cnum,$cdom,$inst_coursecode) = @_;
 6879:     my $homeserver;
 6880:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 6881:         $homeserver = &homeserver($cnum,$cdom);
 6882:     }
 6883:     if (!defined($homeserver)) { 
 6884:         if ($cdom =~ /^$match_domain$/) {
 6885:             $homeserver = &domain($cdom,'primary');
 6886:         }
 6887:     }
 6888:     my @secs;
 6889:     if (defined($homeserver)) {
 6890:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 6891:         unless ($response eq 'refused') {
 6892:             @secs = split(/:/,$response);
 6893:         }
 6894:     }
 6895:     return @secs;
 6896: }
 6897: 
 6898: sub auto_new_course {
 6899:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 6900:     my $homeserver = &homeserver($cnum,$cdom);
 6901:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 6902:     return $response;
 6903: }
 6904: 
 6905: sub auto_validate_courseID {
 6906:     my ($cnum,$cdom,$inst_course_id) = @_;
 6907:     my $homeserver = &homeserver($cnum,$cdom);
 6908:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 6909:     return $response;
 6910: }
 6911: 
 6912: sub auto_validate_instcode {
 6913:     my ($cnum,$cdom,$instcode,$owner) = @_;
 6914:     my ($homeserver,$response);
 6915:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 6916:         $homeserver = &homeserver($cnum,$cdom);
 6917:     }
 6918:     if (!defined($homeserver)) {
 6919:         if ($cdom =~ /^$match_domain$/) {
 6920:             $homeserver = &domain($cdom,'primary');
 6921:         }
 6922:     }
 6923:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 6924:                         &escape($instcode).':'.&escape($owner),$homeserver));
 6925:     my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
 6926:     return ($outcome,$description);
 6927: }
 6928: 
 6929: sub auto_create_password {
 6930:     my ($cnum,$cdom,$authparam,$udom) = @_;
 6931:     my ($homeserver,$response);
 6932:     my $create_passwd = 0;
 6933:     my $authchk = '';
 6934:     if ($udom =~ /^$match_domain$/) {
 6935:         $homeserver = &domain($udom,'primary');
 6936:     }
 6937:     if ($homeserver eq '') {
 6938:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 6939:             $homeserver = &homeserver($cnum,$cdom);
 6940:         }
 6941:     }
 6942:     if ($homeserver eq '') {
 6943:         $authchk = 'nodomain';
 6944:     } else {
 6945:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 6946:         if ($response eq 'refused') {
 6947:             $authchk = 'refused';
 6948:         } else {
 6949:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 6950:         }
 6951:     }
 6952:     return ($authparam,$create_passwd,$authchk);
 6953: }
 6954: 
 6955: sub auto_photo_permission {
 6956:     my ($cnum,$cdom,$students) = @_;
 6957:     my $homeserver = &homeserver($cnum,$cdom);
 6958:     my ($outcome,$perm_reqd,$conditions) = 
 6959: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 6960:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 6961: 	return (undef,undef);
 6962:     }
 6963:     return ($outcome,$perm_reqd,$conditions);
 6964: }
 6965: 
 6966: sub auto_checkphotos {
 6967:     my ($uname,$udom,$pid) = @_;
 6968:     my $homeserver = &homeserver($uname,$udom);
 6969:     my ($result,$resulttype);
 6970:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 6971: 				   &escape($uname).':'.&escape($pid),
 6972: 				   $homeserver));
 6973:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 6974: 	return (undef,undef);
 6975:     }
 6976:     if ($outcome) {
 6977:         ($result,$resulttype) = split(/:/,$outcome);
 6978:     } 
 6979:     return ($result,$resulttype);
 6980: }
 6981: 
 6982: sub auto_photochoice {
 6983:     my ($cnum,$cdom) = @_;
 6984:     my $homeserver = &homeserver($cnum,$cdom);
 6985:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 6986: 						       &escape($cdom),
 6987: 						       $homeserver)));
 6988:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 6989: 	return (undef,undef);
 6990:     }
 6991:     return ($update,$comment);
 6992: }
 6993: 
 6994: sub auto_photoupdate {
 6995:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 6996:     my $homeserver = &homeserver($cnum,$dom);
 6997:     my $host=&hostname($homeserver);
 6998:     my $cmd = '';
 6999:     my $maxtries = 1;
 7000:     foreach my $affiliate (keys(%{$affiliatesref})) {
 7001:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 7002:     }
 7003:     $cmd =~ s/%%$//;
 7004:     $cmd = &escape($cmd);
 7005:     my $query = 'institutionalphotos';
 7006:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 7007:     unless ($queryid=~/^\Q$host\E\_/) {
 7008:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 7009:         return 'error: '.$queryid;
 7010:     }
 7011:     my $reply = &get_query_reply($queryid);
 7012:     my $tries = 1;
 7013:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 7014:         $reply = &get_query_reply($queryid);
 7015:         $tries ++;
 7016:     }
 7017:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 7018:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 7019:     } else {
 7020:         my @responses = split(/:/,$reply);
 7021:         my $outcome = shift(@responses); 
 7022:         foreach my $item (@responses) {
 7023:             my ($key,$value) = split(/=/,$item);
 7024:             $$photo{$key} = $value;
 7025:         }
 7026:         return $outcome;
 7027:     }
 7028:     return 'error';
 7029: }
 7030: 
 7031: sub auto_instcode_format {
 7032:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 7033: 	$cat_order) = @_;
 7034:     my $courses = '';
 7035:     my @homeservers;
 7036:     if ($caller eq 'global') {
 7037: 	my %servers = &get_servers($codedom,'library');
 7038: 	foreach my $tryserver (keys(%servers)) {
 7039: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7040: 		push(@homeservers,$tryserver);
 7041: 	    }
 7042:         }
 7043:     } elsif ($caller eq 'requests') {
 7044:         if ($codedom =~ /^$match_domain$/) {
 7045:             my $chome = &domain($codedom,'primary');
 7046:             unless ($chome eq 'no_host') {
 7047:                 push(@homeservers,$chome);
 7048:             }
 7049:         }
 7050:     } else {
 7051:         push(@homeservers,&homeserver($caller,$codedom));
 7052:     }
 7053:     foreach my $code (keys(%{$instcodes})) {
 7054:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 7055:     }
 7056:     chop($courses);
 7057:     my $ok_response = 0;
 7058:     my $response;
 7059:     while (@homeservers > 0 && $ok_response == 0) {
 7060:         my $server = shift(@homeservers); 
 7061:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 7062:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 7063:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 7064: 		split(/:/,$response);
 7065:             %{$codes} = (%{$codes},&str2hash($codes_str));
 7066:             push(@{$codetitles},&str2array($codetitles_str));
 7067:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 7068:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 7069:             $ok_response = 1;
 7070:         }
 7071:     }
 7072:     if ($ok_response) {
 7073:         return 'ok';
 7074:     } else {
 7075:         return $response;
 7076:     }
 7077: }
 7078: 
 7079: sub auto_instcode_defaults {
 7080:     my ($domain,$returnhash,$code_order) = @_;
 7081:     my @homeservers;
 7082: 
 7083:     my %servers = &get_servers($domain,'library');
 7084:     foreach my $tryserver (keys(%servers)) {
 7085: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7086: 	    push(@homeservers,$tryserver);
 7087: 	}
 7088:     }
 7089: 
 7090:     my $response;
 7091:     foreach my $server (@homeservers) {
 7092:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 7093:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 7094: 	
 7095: 	foreach my $pair (split(/\&/,$response)) {
 7096: 	    my ($name,$value)=split(/\=/,$pair);
 7097: 	    if ($name eq 'code_order') {
 7098: 		@{$code_order} = split(/\&/,&unescape($value));
 7099: 	    } else {
 7100: 		$returnhash->{&unescape($name)}=&unescape($value);
 7101: 	    }
 7102: 	}
 7103: 	return 'ok';
 7104:     }
 7105: 
 7106:     return $response;
 7107: }
 7108: 
 7109: sub auto_possible_instcodes {
 7110:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 7111:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 7112:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 7113:         return;
 7114:     }
 7115:     my (@homeservers,$uhome);
 7116:     if (defined(&domain($domain,'primary'))) {
 7117:         $uhome=&domain($domain,'primary');
 7118:         push(@homeservers,&domain($domain,'primary'));
 7119:     } else {
 7120:         my %servers = &get_servers($domain,'library');
 7121:         foreach my $tryserver (keys(%servers)) {
 7122:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7123:                 push(@homeservers,$tryserver);
 7124:             }
 7125:         }
 7126:     }
 7127:     my $response;
 7128:     foreach my $server (@homeservers) {
 7129:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 7130:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 7131:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 7132:             split(':',$response);
 7133:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 7134:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 7135:         foreach my $item (split('&',$cat_title)) {   
 7136:             my ($name,$value)=split('=',$item);
 7137:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 7138:         }
 7139:         foreach my $item (split('&',$cat_order)) {
 7140:             my ($name,$value)=split('=',$item);
 7141:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 7142:         }
 7143:         return 'ok';
 7144:     }
 7145:     return $response;
 7146: }
 7147: 
 7148: sub auto_courserequest_checks {
 7149:     my ($dom) = @_;
 7150:     my ($homeserver,%validations);
 7151:     if ($dom =~ /^$match_domain$/) {
 7152:         $homeserver = &domain($dom,'primary');
 7153:     }
 7154:     unless ($homeserver eq 'no_host') {
 7155:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 7156:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 7157:             my @items = split(/&/,$response);
 7158:             foreach my $item (@items) {
 7159:                 my ($key,$value) = split('=',$item);
 7160:                 $validations{&unescape($key)} = &thaw_unescape($value);
 7161:             }
 7162:         }
 7163:     }
 7164:     return %validations; 
 7165: }
 7166: 
 7167: sub auto_courserequest_validation {
 7168:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
 7169:     my ($homeserver,$response);
 7170:     if ($dom =~ /^$match_domain$/) {
 7171:         $homeserver = &domain($dom,'primary');
 7172:     }
 7173:     unless ($homeserver eq 'no_host') {  
 7174:           
 7175:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 7176:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 7177:                                     ':'.&escape($instcode).':'.&escape($instseclist),
 7178:                                     $homeserver));
 7179:     }
 7180:     return $response;
 7181: }
 7182: 
 7183: sub auto_validate_class_sec {
 7184:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 7185:     my $homeserver = &homeserver($cnum,$cdom);
 7186:     my $ownerlist;
 7187:     if (ref($owners) eq 'ARRAY') {
 7188:         $ownerlist = join(',',@{$owners});
 7189:     } else {
 7190:         $ownerlist = $owners;
 7191:     }
 7192:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 7193:                         &escape($ownerlist).':'.$cdom,$homeserver);
 7194:     return $response;
 7195: }
 7196: 
 7197: # ------------------------------------------------------- Course Group routines
 7198: 
 7199: sub get_coursegroups {
 7200:     my ($cdom,$cnum,$group,$namespace) = @_;
 7201:     return(&dump($namespace,$cdom,$cnum,$group));
 7202: }
 7203: 
 7204: sub modify_coursegroup {
 7205:     my ($cdom,$cnum,$groupsettings) = @_;
 7206:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 7207: }
 7208: 
 7209: sub toggle_coursegroup_status {
 7210:     my ($cdom,$cnum,$group,$action) = @_;
 7211:     my ($from_namespace,$to_namespace);
 7212:     if ($action eq 'delete') {
 7213:         $from_namespace = 'coursegroups';
 7214:         $to_namespace = 'deleted_groups';
 7215:     } else {
 7216:         $from_namespace = 'deleted_groups';
 7217:         $to_namespace = 'coursegroups';
 7218:     }
 7219:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 7220:     if (my $tmp = &error(%curr_group)) {
 7221:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 7222:         return ('read error',$tmp);
 7223:     } else {
 7224:         my %savedsettings = %curr_group; 
 7225:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 7226:         my $deloutcome;
 7227:         if ($result eq 'ok') {
 7228:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 7229:         } else {
 7230:             return ('write error',$result);
 7231:         }
 7232:         if ($deloutcome eq 'ok') {
 7233:             return 'ok';
 7234:         } else {
 7235:             return ('delete error',$deloutcome);
 7236:         }
 7237:     }
 7238: }
 7239: 
 7240: sub modify_group_roles {
 7241:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 7242:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 7243:     my $role = 'gr/'.&escape($userprivs);
 7244:     my ($uname,$udom) = split(/:/,$user);
 7245:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 7246:     if ($result eq 'ok') {
 7247:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 7248:     }
 7249:     return $result;
 7250: }
 7251: 
 7252: sub modify_coursegroup_membership {
 7253:     my ($cdom,$cnum,$membership) = @_;
 7254:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 7255:     return $result;
 7256: }
 7257: 
 7258: sub get_active_groups {
 7259:     my ($udom,$uname,$cdom,$cnum) = @_;
 7260:     my $now = time;
 7261:     my %groups = ();
 7262:     foreach my $key (keys(%env)) {
 7263:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 7264:             my ($start,$end) = split(/\./,$env{$key});
 7265:             if (($end!=0) && ($end<$now)) { next; }
 7266:             if (($start!=0) && ($start>$now)) { next; }
 7267:             if ($1 eq $cdom && $2 eq $cnum) {
 7268:                 $groups{$3} = $env{$key} ;
 7269:             }
 7270:         }
 7271:     }
 7272:     return %groups;
 7273: }
 7274: 
 7275: sub get_group_membership {
 7276:     my ($cdom,$cnum,$group) = @_;
 7277:     return(&dump('groupmembership',$cdom,$cnum,$group));
 7278: }
 7279: 
 7280: sub get_users_groups {
 7281:     my ($udom,$uname,$courseid) = @_;
 7282:     my @usersgroups;
 7283:     my $cachetime=1800;
 7284: 
 7285:     my $hashid="$udom:$uname:$courseid";
 7286:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 7287:     if (defined($cached)) {
 7288:         @usersgroups = split(/:/,$grouplist);
 7289:     } else {  
 7290:         $grouplist = '';
 7291:         my $courseurl = &courseid_to_courseurl($courseid);
 7292:         my $extra = &freeze_escape({'skipcheck' => 1});
 7293:         my %roleshash = &dump('roles',$udom,$uname,$courseurl,undef,$extra);
 7294:         my $access_end = $env{'course.'.$courseid.
 7295:                               '.default_enrollment_end_date'};
 7296:         my $now = time;
 7297:         foreach my $key (keys(%roleshash)) {
 7298:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 7299:                 my $group = $1;
 7300:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 7301:                     my $start = $2;
 7302:                     my $end = $1;
 7303:                     if ($start == -1) { next; } # deleted from group
 7304:                     if (($start!=0) && ($start>$now)) { next; }
 7305:                     if (($end!=0) && ($end<$now)) {
 7306:                         if ($access_end && $access_end < $now) {
 7307:                             if ($access_end - $end < 86400) {
 7308:                                 push(@usersgroups,$group);
 7309:                             }
 7310:                         }
 7311:                         next;
 7312:                     }
 7313:                     push(@usersgroups,$group);
 7314:                 }
 7315:             }
 7316:         }
 7317:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 7318:         $grouplist = join(':',@usersgroups);
 7319:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 7320:     }
 7321:     return @usersgroups;
 7322: }
 7323: 
 7324: sub devalidate_getgroups_cache {
 7325:     my ($udom,$uname,$cdom,$cnum)=@_;
 7326:     my $courseid = $cdom.'_'.$cnum;
 7327: 
 7328:     my $hashid="$udom:$uname:$courseid";
 7329:     &devalidate_cache_new('getgroups',$hashid);
 7330: }
 7331: 
 7332: # ------------------------------------------------------------------ Plain Text
 7333: 
 7334: sub plaintext {
 7335:     my ($short,$type,$cid,$forcedefault) = @_;
 7336:     if ($short =~ m{^cr/}) {
 7337: 	return (split('/',$short))[-1];
 7338:     }
 7339:     if (!defined($cid)) {
 7340:         $cid = $env{'request.course.id'};
 7341:     }
 7342:     my %rolenames = (
 7343:                       Course    => 'std',
 7344:                       Community => 'alt1',
 7345:                     );
 7346:     if ($cid ne '') {
 7347:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 7348:             unless ($forcedefault) {
 7349:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 7350:                 &Apache::lonlocal::mt_escape(\$roletext);
 7351:                 return &Apache::lonlocal::mt($roletext);
 7352:             }
 7353:         }
 7354:     }
 7355:     if ((defined($type)) && (defined($rolenames{$type})) &&
 7356:         (defined($rolenames{$type})) && 
 7357:         (defined($prp{$short}{$rolenames{$type}}))) {
 7358:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 7359:     } elsif ($cid ne '') {
 7360:         my $crstype = $env{'course.'.$cid.'.type'};
 7361:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
 7362:             (defined($prp{$short}{$rolenames{$crstype}}))) {
 7363:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
 7364:         }
 7365:     }
 7366:     return &Apache::lonlocal::mt($prp{$short}{'std'});
 7367: }
 7368: 
 7369: # ----------------------------------------------------------------- Assign Role
 7370: 
 7371: sub assignrole {
 7372:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 7373:         $context)=@_;
 7374:     my $mrole;
 7375:     if ($role =~ /^cr\//) {
 7376:         my $cwosec=$url;
 7377:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 7378: 	unless (&allowed('ccr',$cwosec)) {
 7379:            my $refused = 1;
 7380:            if ($context eq 'requestcourses') {
 7381:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 7382:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
 7383:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
 7384:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 7385:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 7386:                            if ($crsenv{'internal.courseowner'} eq
 7387:                                $env{'user.name'}.':'.$env{'user.domain'}) {
 7388:                                $refused = '';
 7389:                            }
 7390:                        }
 7391:                    }
 7392:                }
 7393:            }
 7394:            if ($refused) {
 7395:                &logthis('Refused custom assignrole: '.
 7396:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
 7397:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
 7398:                return 'refused';
 7399:            }
 7400:         }
 7401:         $mrole='cr';
 7402:     } elsif ($role =~ /^gr\//) {
 7403:         my $cwogrp=$url;
 7404:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 7405:         unless (&allowed('mdg',$cwogrp)) {
 7406:             &logthis('Refused group assignrole: '.
 7407:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 7408:                     $env{'user.name'}.' at '.$env{'user.domain'});
 7409:             return 'refused';
 7410:         }
 7411:         $mrole='gr';
 7412:     } else {
 7413:         my $cwosec=$url;
 7414:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 7415:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 7416:             my $refused;
 7417:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 7418:                 if (!(&allowed('c'.$role,$url))) {
 7419:                     $refused = 1;
 7420:                 }
 7421:             } else {
 7422:                 $refused = 1;
 7423:             }
 7424:             if ($refused) {
 7425:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 7426:                 if (!$selfenroll && $context eq 'course') {
 7427:                     my %crsenv;
 7428:                     if ($role eq 'cc' || $role eq 'co') {
 7429:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 7430:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
 7431:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
 7432:                                 if ($crsenv{'internal.courseowner'} eq 
 7433:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 7434:                                     $refused = '';
 7435:                                 }
 7436:                             }
 7437:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
 7438:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
 7439:                                 if ($crsenv{'internal.courseowner'} eq 
 7440:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 7441:                                     $refused = '';
 7442:                                 }
 7443:                             }
 7444:                         }
 7445:                     }
 7446:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7447:                     $refused = '';
 7448:                 } elsif ($context eq 'requestcourses') {
 7449:                     my @possroles = ('st','ta','ep','in','cc','co');
 7450:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
 7451:                         my $wrongcc;
 7452:                         if ($cnum =~ /^$match_community$/) {
 7453:                             $wrongcc = 1 if ($role eq 'cc');
 7454:                         } else {
 7455:                             $wrongcc = 1 if ($role eq 'co');
 7456:                         }
 7457:                         unless ($wrongcc) {
 7458:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 7459:                             if ($crsenv{'internal.courseowner'} eq 
 7460:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
 7461:                                 $refused = '';
 7462:                             }
 7463:                         }
 7464:                     }
 7465:                 }
 7466:                 if ($refused) {
 7467:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 7468:                              ' '.$role.' '.$end.' '.$start.' by '.
 7469: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 7470:                     return 'refused';
 7471:                 }
 7472:             }
 7473:         } elsif ($role eq 'au') {
 7474:             if ($url ne '/'.$udom.'/') {
 7475:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
 7476:                          ' to assign author role for '.$uname.':'.$udom.
 7477:                          ' in domain: '.$url.' refused (wrong domain).');
 7478:                 return 'refused';
 7479:             }
 7480:         }
 7481:         $mrole=$role;
 7482:     }
 7483:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 7484:                 "$udom:$uname:$url".'_'."$mrole=$role";
 7485:     if ($end) { $command.='_'.$end; }
 7486:     if ($start) {
 7487: 	if ($end) { 
 7488:            $command.='_'.$start; 
 7489:         } else {
 7490:            $command.='_0_'.$start;
 7491:         }
 7492:     }
 7493:     my $origstart = $start;
 7494:     my $origend = $end;
 7495:     my $delflag;
 7496: # actually delete
 7497:     if ($deleteflag) {
 7498: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 7499: # modify command to delete the role
 7500:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 7501:                 "$udom:$uname:$url".'_'."$mrole";
 7502: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 7503: # set start and finish to negative values for userrolelog
 7504:            $start=-1;
 7505:            $end=-1;
 7506:            $delflag = 1;
 7507:         }
 7508:     }
 7509: # send command
 7510:     my $answer=&reply($command,&homeserver($uname,$udom));
 7511: # log new user role if status is ok
 7512:     if ($answer eq 'ok') {
 7513: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 7514: # for course roles, perform group memberships changes triggered by role change.
 7515:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
 7516:         unless ($role =~ /^gr/) {
 7517:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 7518:                                              $origstart,$selfenroll,$context);
 7519:         }
 7520:         if ($role eq 'cc') {
 7521:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
 7522:         }
 7523:     }
 7524:     return $answer;
 7525: }
 7526: 
 7527: sub autoupdate_coowners {
 7528:     my ($url,$end,$start,$uname,$udom) = @_;
 7529:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
 7530:     if (($cdom ne '') && ($cnum ne '')) {
 7531:         my $now = time;
 7532:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
 7533:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
 7534:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
 7535:             my $instcode = $coursehash{'internal.coursecode'};
 7536:             if ($instcode ne '') {
 7537:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
 7538:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
 7539:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
 7540:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
 7541:                         if ($result eq 'valid') {
 7542:                             if ($coursehash{'internal.co-owners'}) {
 7543:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 7544:                                     push(@newcoowners,$coowner);
 7545:                                 }
 7546:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
 7547:                                     push(@newcoowners,$uname.':'.$udom);
 7548:                                 }
 7549:                                 @newcoowners = sort(@newcoowners);
 7550:                             } else {
 7551:                                 push(@newcoowners,$uname.':'.$udom);
 7552:                             }
 7553:                         } else {
 7554:                             if ($coursehash{'internal.co-owners'}) {
 7555:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 7556:                                     unless ($coowner eq $uname.':'.$udom) {
 7557:                                         push(@newcoowners,$coowner);
 7558:                                     }
 7559:                                 }
 7560:                                 unless (@newcoowners > 0) {
 7561:                                     $delcoowners = 1;
 7562:                                     $coowners = '';
 7563:                                 }
 7564:                             }
 7565:                         }
 7566:                         if (@newcoowners || $delcoowners) {
 7567:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
 7568:                                             $delcoowners,@newcoowners);
 7569:                         }
 7570:                     }
 7571:                 }
 7572:             }
 7573:         }
 7574:     }
 7575: }
 7576: 
 7577: sub store_coowners {
 7578:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
 7579:     my $cid = $cdom.'_'.$cnum;
 7580:     my ($coowners,$delresult,$putresult);
 7581:     if (@newcoowners) {
 7582:         $coowners = join(',',@newcoowners);
 7583:         my %coownershash = (
 7584:                             'internal.co-owners' => $coowners,
 7585:                            );
 7586:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
 7587:         if ($putresult eq 'ok') {
 7588:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
 7589:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
 7590:             }
 7591:         }
 7592:     }
 7593:     if ($delcoowners) {
 7594:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
 7595:         if ($delresult eq 'ok') {
 7596:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
 7597:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
 7598:             }
 7599:         }
 7600:     }
 7601:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
 7602:         my %crsinfo =
 7603:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 7604:         if (ref($crsinfo{$cid}) eq 'HASH') {
 7605:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
 7606:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
 7607:         }
 7608:     }
 7609: }
 7610: 
 7611: # -------------------------------------------------- Modify user authentication
 7612: # Overrides without validation
 7613: 
 7614: sub modifyuserauth {
 7615:     my ($udom,$uname,$umode,$upass)=@_;
 7616:     my $uhome=&homeserver($uname,$udom);
 7617:     unless (&allowed('mau',$udom)) { return 'refused'; }
 7618:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 7619:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 7620:              ' in domain '.$env{'request.role.domain'});  
 7621:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 7622: 		     &escape($upass),$uhome);
 7623:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 7624:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 7625:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 7626:     &log($udom,,$uname,$uhome,
 7627:         'Authentication changed by '.$env{'user.domain'}.', '.
 7628:                                      $env{'user.name'}.', '.$umode.
 7629:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 7630:     unless ($reply eq 'ok') {
 7631:         &logthis('Authentication mode error: '.$reply);
 7632: 	return 'error: '.$reply;
 7633:     }   
 7634:     return 'ok';
 7635: }
 7636: 
 7637: # --------------------------------------------------------------- Modify a user
 7638: 
 7639: sub modifyuser {
 7640:     my ($udom,    $uname, $uid,
 7641:         $umode,   $upass, $first,
 7642:         $middle,  $last,  $gene,
 7643:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
 7644:     $udom= &LONCAPA::clean_domain($udom);
 7645:     $uname=&LONCAPA::clean_username($uname);
 7646:     my $showcandelete = 'none';
 7647:     if (ref($candelete) eq 'ARRAY') {
 7648:         if (@{$candelete} > 0) {
 7649:             $showcandelete = join(', ',@{$candelete});
 7650:         }
 7651:     }
 7652:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 7653:              $umode.', '.$first.', '.$middle.', '.
 7654: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
 7655:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 7656:                                      ' desiredhome not specified'). 
 7657:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 7658:              ' in domain '.$env{'request.role.domain'});
 7659:     my $uhome=&homeserver($uname,$udom,'true');
 7660:     my $newuser;
 7661:     if ($uhome eq 'no_host') {
 7662:         $newuser = 1;
 7663:     }
 7664: # ----------------------------------------------------------------- Create User
 7665:     if (($uhome eq 'no_host') && 
 7666: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 7667:         my $unhome='';
 7668:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 7669:             $unhome = $desiredhome;
 7670: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 7671: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 7672:         } else { # load balancing routine for determining $unhome
 7673:             my $loadm=10000000;
 7674: 	    my %servers = &get_servers($udom,'library');
 7675: 	    foreach my $tryserver (keys(%servers)) {
 7676: 		my $answer=reply('load',$tryserver);
 7677: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 7678: 		    $loadm=$answer;
 7679: 		    $unhome=$tryserver;
 7680: 		}
 7681: 	    }
 7682:         }
 7683:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 7684: 	    return 'error: unable to find a home server for '.$uname.
 7685:                    ' in domain '.$udom;
 7686:         }
 7687:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 7688:                          &escape($upass),$unhome);
 7689: 	unless ($reply eq 'ok') {
 7690:             return 'error: '.$reply;
 7691:         }   
 7692:         $uhome=&homeserver($uname,$udom,'true');
 7693:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 7694: 	    return 'error: unable verify users home machine.';
 7695:         }
 7696:     }   # End of creation of new user
 7697: # ---------------------------------------------------------------------- Add ID
 7698:     if ($uid) {
 7699:        $uid=~tr/A-Z/a-z/;
 7700:        my %uidhash=&idrget($udom,$uname);
 7701:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 7702:          && (!$forceid)) {
 7703: 	  unless ($uid eq $uidhash{$uname}) {
 7704: 	      return 'error: user id "'.$uid.'" does not match '.
 7705:                   'current user id "'.$uidhash{$uname}.'".';
 7706:           }
 7707:        } else {
 7708: 	  &idput($udom,($uname => $uid));
 7709:        }
 7710:     }
 7711: # -------------------------------------------------------------- Add names, etc
 7712:     my @tmp=&get('environment',
 7713: 		   ['firstname','middlename','lastname','generation','id',
 7714:                     'permanentemail','inststatus'],
 7715: 		   $udom,$uname);
 7716:     my (%names,%oldnames);
 7717:     if ($tmp[0] =~ m/^error:.*/) { 
 7718:         %names=(); 
 7719:     } else {
 7720:         %names = @tmp;
 7721:         %oldnames = %names;
 7722:     }
 7723: #
 7724: # If name, email and/or uid are blank (e.g., because an uploaded file
 7725: # of users did not contain them), do not overwrite existing values
 7726: # unless field is in $candelete array ref.  
 7727: #
 7728: 
 7729:     my @fields = ('firstname','middlename','lastname','generation',
 7730:                   'permanentemail','id');
 7731:     my %newvalues;
 7732:     if (ref($candelete) eq 'ARRAY') {
 7733:         foreach my $field (@fields) {
 7734:             if (grep(/^\Q$field\E$/,@{$candelete})) {
 7735:                 if ($field eq 'firstname') {
 7736:                     $names{$field} = $first;
 7737:                 } elsif ($field eq 'middlename') {
 7738:                     $names{$field} = $middle;
 7739:                 } elsif ($field eq 'lastname') {
 7740:                     $names{$field} = $last;
 7741:                 } elsif ($field eq 'generation') { 
 7742:                     $names{$field} = $gene;
 7743:                 } elsif ($field eq 'permanentemail') {
 7744:                     $names{$field} = $email;
 7745:                 } elsif ($field eq 'id') {
 7746:                     $names{$field}  = $uid;
 7747:                 }
 7748:             }
 7749:         }
 7750:     }
 7751:     if ($first)  { $names{'firstname'}  = $first; }
 7752:     if (defined($middle)) { $names{'middlename'} = $middle; }
 7753:     if ($last)   { $names{'lastname'}   = $last; }
 7754:     if (defined($gene))   { $names{'generation'} = $gene; }
 7755:     if ($email) {
 7756:        $email=~s/[^\w\@\.\-\,]//gs;
 7757:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 7758:     }
 7759:     if ($uid) { $names{'id'}  = $uid; }
 7760:     if (defined($inststatus)) {
 7761:         $names{'inststatus'} = '';
 7762:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
 7763:         if (ref($usertypes) eq 'HASH') {
 7764:             my @okstatuses; 
 7765:             foreach my $item (split(/:/,$inststatus)) {
 7766:                 if (defined($usertypes->{$item})) {
 7767:                     push(@okstatuses,$item);  
 7768:                 }
 7769:             }
 7770:             if (@okstatuses) {
 7771:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
 7772:             }
 7773:         }
 7774:     }
 7775:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
 7776:                  $umode.', '.$first.', '.$middle.', '.
 7777:                  $last.', '.$gene.', '.$email.', '.$inststatus;
 7778:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 7779:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 7780:     } else {
 7781:         $logmsg .= ' during self creation';
 7782:     }
 7783:     my $changed;
 7784:     if ($newuser) {
 7785:         $changed = 1;
 7786:     } else {
 7787:         foreach my $field (@fields) {
 7788:             if ($names{$field} ne $oldnames{$field}) {
 7789:                 $changed = 1;
 7790:                 last;
 7791:             }
 7792:         }
 7793:     }
 7794:     unless ($changed) {
 7795:         $logmsg = 'No changes in user information needed for: '.$logmsg;
 7796:         &logthis($logmsg);
 7797:         return 'ok';
 7798:     }
 7799:     my $reply = &put('environment', \%names, $udom,$uname);
 7800:     if ($reply ne 'ok') { 
 7801:         return 'error: '.$reply;
 7802:     }
 7803:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
 7804:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
 7805:     }
 7806:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 7807:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 7808:     $logmsg = 'Success modifying user '.$logmsg;
 7809:     &logthis($logmsg);
 7810:     return 'ok';
 7811: }
 7812: 
 7813: # -------------------------------------------------------------- Modify student
 7814: 
 7815: sub modifystudent {
 7816:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 7817:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 7818:         $selfenroll,$context,$inststatus)=@_;
 7819:     if (!$cid) {
 7820: 	unless ($cid=$env{'request.course.id'}) {
 7821: 	    return 'not_in_class';
 7822: 	}
 7823:     }
 7824: # --------------------------------------------------------------- Make the user
 7825:     my $reply=&modifyuser
 7826: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 7827:          $desiredhome,$email,$inststatus);
 7828:     unless ($reply eq 'ok') { return $reply; }
 7829:     # This will cause &modify_student_enrollment to get the uid from the
 7830:     # students environment
 7831:     $uid = undef if (!$forceid);
 7832:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 7833: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
 7834:     return $reply;
 7835: }
 7836: 
 7837: sub modify_student_enrollment {
 7838:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
 7839:     my ($cdom,$cnum,$chome);
 7840:     if (!$cid) {
 7841: 	unless ($cid=$env{'request.course.id'}) {
 7842: 	    return 'not_in_class';
 7843: 	}
 7844: 	$cdom=$env{'course.'.$cid.'.domain'};
 7845: 	$cnum=$env{'course.'.$cid.'.num'};
 7846:     } else {
 7847: 	($cdom,$cnum)=split(/_/,$cid);
 7848:     }
 7849:     $chome=$env{'course.'.$cid.'.home'};
 7850:     if (!$chome) {
 7851: 	$chome=&homeserver($cnum,$cdom);
 7852:     }
 7853:     if (!$chome) { return 'unknown_course'; }
 7854:     # Make sure the user exists
 7855:     my $uhome=&homeserver($uname,$udom);
 7856:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 7857: 	return 'error: no such user';
 7858:     }
 7859:     # Get student data if we were not given enough information
 7860:     if (!defined($first)  || $first  eq '' || 
 7861:         !defined($last)   || $last   eq '' || 
 7862:         !defined($uid)    || $uid    eq '' || 
 7863:         !defined($middle) || $middle eq '' || 
 7864:         !defined($gene)   || $gene   eq '') {
 7865:         # They did not supply us with enough data to enroll the student, so
 7866:         # we need to pick up more information.
 7867:         my %tmp = &get('environment',
 7868:                        ['firstname','middlename','lastname', 'generation','id']
 7869:                        ,$udom,$uname);
 7870: 
 7871:         #foreach my $key (keys(%tmp)) {
 7872:         #    &logthis("key $key = ".$tmp{$key});
 7873:         #}
 7874:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 7875:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 7876:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 7877:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 7878:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 7879:     }
 7880:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 7881:     my $user = "$uname:$udom";
 7882:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
 7883:     my $reply=cput('classlist',
 7884: 		   {$user => 
 7885: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
 7886: 		   $cdom,$cnum);
 7887:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
 7888:         &devalidate_getsection_cache($udom,$uname,$cid);
 7889:     } else { 
 7890: 	return 'error: '.$reply;
 7891:     }
 7892:     # Add student role to user
 7893:     my $uurl='/'.$cid;
 7894:     $uurl=~s/\_/\//g;
 7895:     if ($usec) {
 7896: 	$uurl.='/'.$usec;
 7897:     }
 7898:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
 7899:                              $selfenroll,$context);
 7900:     if ($result ne 'ok') {
 7901:         if ($old_entry{$user} ne '') {
 7902:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
 7903:         } else {
 7904:             $reply = &del('classlist',[$user],$cdom,$cnum);
 7905:         }
 7906:     }
 7907:     return $result; 
 7908: }
 7909: 
 7910: sub format_name {
 7911:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 7912:     my $name;
 7913:     if ($first ne 'lastname') {
 7914: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 7915:     } else {
 7916: 	if ($lastname=~/\S/) {
 7917: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 7918: 	    $name=~s/\s+,/,/;
 7919: 	} else {
 7920: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 7921: 	}
 7922:     }
 7923:     $name=~s/^\s+//;
 7924:     $name=~s/\s+$//;
 7925:     $name=~s/\s+/ /g;
 7926:     return $name;
 7927: }
 7928: 
 7929: # ------------------------------------------------- Write to course preferences
 7930: 
 7931: sub writecoursepref {
 7932:     my ($courseid,%prefs)=@_;
 7933:     $courseid=~s/^\///;
 7934:     $courseid=~s/\_/\//g;
 7935:     my ($cdomain,$cnum)=split(/\//,$courseid);
 7936:     my $chome=homeserver($cnum,$cdomain);
 7937:     if (($chome eq '') || ($chome eq 'no_host')) { 
 7938: 	return 'error: no such course';
 7939:     }
 7940:     my $cstring='';
 7941:     foreach my $pref (keys(%prefs)) {
 7942: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 7943:     }
 7944:     $cstring=~s/\&$//;
 7945:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 7946: }
 7947: 
 7948: # ---------------------------------------------------------- Make/modify course
 7949: 
 7950: sub createcourse {
 7951:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 7952:         $course_owner,$crstype,$cnum,$context,$category)=@_;
 7953:     $url=&declutter($url);
 7954:     my $cid='';
 7955:     if ($context eq 'requestcourses') {
 7956:         my $can_create = 0;
 7957:         my ($ownername,$ownerdom) = split(':',$course_owner);
 7958:         if ($udom eq $ownerdom) {
 7959:             if (&usertools_access($ownername,$ownerdom,$category,undef,
 7960:                                   $context)) {
 7961:                 $can_create = 1;
 7962:             }
 7963:         } else {
 7964:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
 7965:                                            $category);
 7966:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
 7967:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
 7968:                 if (@curr > 0) {
 7969:                     my @options = qw(approval validate autolimit);
 7970:                     my $optregex = join('|',@options);
 7971:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
 7972:                         $can_create = 1;
 7973:                     }
 7974:                 }
 7975:             }
 7976:         }
 7977:         if ($can_create) {
 7978:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
 7979:                 unless (&allowed('ccc',$udom)) {
 7980:                     return 'refused'; 
 7981:                 }
 7982:             }
 7983:         } else {
 7984:             return 'refused';
 7985:         }
 7986:     } elsif (!&allowed('ccc',$udom)) {
 7987:         return 'refused';
 7988:     }
 7989: # --------------------------------------------------------------- Get Unique ID
 7990:     my $uname;
 7991:     if ($cnum =~ /^$match_courseid$/) {
 7992:         my $chome=&homeserver($cnum,$udom,'true');
 7993:         if (($chome eq '') || ($chome eq 'no_host')) {
 7994:             $uname = $cnum;
 7995:         } else {
 7996:             $uname = &generate_coursenum($udom,$crstype);
 7997:         }
 7998:     } else {
 7999:         $uname = &generate_coursenum($udom,$crstype);
 8000:     }
 8001:     return $uname if ($uname =~ /^error/);
 8002: # -------------------------------------------------- Check supplied server name
 8003:     if (!defined($course_server)) {
 8004:         if (defined(&domain($udom,'primary'))) {
 8005:             $course_server = &domain($udom,'primary');
 8006:         } else {
 8007:             $course_server = $env{'user.home'}; 
 8008:         }
 8009:     }
 8010:     my %host_servers =
 8011:         &Apache::lonnet::get_servers($udom,'library');
 8012:     unless ($host_servers{$course_server}) {
 8013:         return 'error: invalid home server for course: '.$course_server;
 8014:     }
 8015: # ------------------------------------------------------------- Make the course
 8016:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 8017:                       $course_server);
 8018:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 8019:     my $uhome=&homeserver($uname,$udom,'true');
 8020:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 8021: 	return 'error: no such course';
 8022:     }
 8023: # ----------------------------------------------------------------- Course made
 8024: # log existence
 8025:     my $now = time;
 8026:     my $newcourse = {
 8027:                     $udom.'_'.$uname => {
 8028:                                      description => $description,
 8029:                                      inst_code   => $inst_code,
 8030:                                      owner       => $course_owner,
 8031:                                      type        => $crstype,
 8032:                                      creator     => $env{'user.name'}.':'.
 8033:                                                     $env{'user.domain'},
 8034:                                      created     => $now,
 8035:                                      context     => $context,
 8036:                                                 },
 8037:                     };
 8038:     &courseidput($udom,$newcourse,$uhome,'notime');
 8039: # set toplevel url
 8040:     my $topurl=$url;
 8041:     unless ($nonstandard) {
 8042: # ------------------------------------------ For standard courses, make top url
 8043:         my $mapurl=&clutter($url);
 8044:         if ($mapurl eq '/res/') { $mapurl=''; }
 8045:         $env{'form.initmap'}=(<<ENDINITMAP);
 8046: <map>
 8047: <resource id="1" type="start"></resource>
 8048: <resource id="2" src="$mapurl"></resource>
 8049: <resource id="3" type="finish"></resource>
 8050: <link index="1" from="1" to="2"></link>
 8051: <link index="2" from="2" to="3"></link>
 8052: </map>
 8053: ENDINITMAP
 8054:         $topurl=&declutter(
 8055:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 8056:                           );
 8057:     }
 8058: # ----------------------------------------------------------- Write preferences
 8059:     &writecoursepref($udom.'_'.$uname,
 8060:                      ('description'              => $description,
 8061:                       'url'                      => $topurl,
 8062:                       'internal.creator'         => $env{'user.name'}.':'.
 8063:                                                     $env{'user.domain'},
 8064:                       'internal.created'         => $now,
 8065:                       'internal.creationcontext' => $context)
 8066:                     );
 8067:     return '/'.$udom.'/'.$uname;
 8068: }
 8069: 
 8070: # ------------------------------------------------------------------- Create ID
 8071: sub generate_coursenum {
 8072:     my ($udom,$crstype) = @_;
 8073:     my $domdesc = &domain($udom);
 8074:     return 'error: invalid domain' if ($domdesc eq '');
 8075:     my $first;
 8076:     if ($crstype eq 'Community') {
 8077:         $first = '0';
 8078:     } else {
 8079:         $first = int(1+rand(9)); 
 8080:     } 
 8081:     my $uname=$first.
 8082:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 8083:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
 8084:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 8085: # ----------------------------------------------- Make sure that does not exist
 8086:     my $uhome=&homeserver($uname,$udom,'true');
 8087:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
 8088:         if ($crstype eq 'Community') {
 8089:             $first = '0';
 8090:         } else {
 8091:             $first = int(1+rand(9));
 8092:         }
 8093:         $uname=$first.
 8094:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 8095:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
 8096:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 8097:         $uhome=&homeserver($uname,$udom,'true');
 8098:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
 8099:             return 'error: unable to generate unique course-ID';
 8100:         }
 8101:     }
 8102:     return $uname;
 8103: }
 8104: 
 8105: sub is_course {
 8106:     my ($cdom,$cnum) = @_;
 8107:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
 8108: 				undef,'.');
 8109:     if (exists($courses{$cdom.'_'.$cnum})) {
 8110:         return 1;
 8111:     }
 8112:     return 0;
 8113: }
 8114: 
 8115: sub store_userdata {
 8116:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
 8117:     my $result;
 8118:     if ($datakey ne '') {
 8119:         if (ref($storehash) eq 'HASH') {
 8120:             if ($udom eq '' || $uname eq '') {
 8121:                 $udom = $env{'user.domain'};
 8122:                 $uname = $env{'user.name'};
 8123:             }
 8124:             my $uhome=&homeserver($uname,$udom);
 8125:             if (($uhome eq '') || ($uhome eq 'no_host')) {
 8126:                 $result = 'error: no_host';
 8127:             } else {
 8128:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
 8129:                 $storehash->{'host'} = $perlvar{'lonHostID'};
 8130: 
 8131:                 my $namevalue='';
 8132:                 foreach my $key (keys(%{$storehash})) {
 8133:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 8134:                 }
 8135:                 $namevalue=~s/\&$//;
 8136:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
 8137:                                   $namevalue,$uhome);
 8138:             }
 8139:         } else {
 8140:             $result = 'error: data to store was not a hash reference'; 
 8141:         }
 8142:     } else {
 8143:         $result= 'error: invalid requestkey'; 
 8144:     }
 8145:     return $result;
 8146: }
 8147: 
 8148: # ---------------------------------------------------------- Assign Custom Role
 8149: 
 8150: sub assigncustomrole {
 8151:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
 8152:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 8153:                        $end,$start,$deleteflag,$selfenroll,$context);
 8154: }
 8155: 
 8156: # ----------------------------------------------------------------- Revoke Role
 8157: 
 8158: sub revokerole {
 8159:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
 8160:     my $now=time;
 8161:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
 8162: }
 8163: 
 8164: # ---------------------------------------------------------- Revoke Custom Role
 8165: 
 8166: sub revokecustomrole {
 8167:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
 8168:     my $now=time;
 8169:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 8170:            $deleteflag,$selfenroll,$context);
 8171: }
 8172: 
 8173: # ------------------------------------------------------------ Disk usage
 8174: sub diskusage {
 8175:     my ($udom,$uname,$directorypath,$getpropath)=@_;
 8176:     $directorypath =~ s/\/$//;
 8177:     my $listing=&reply('du2:'.&escape($directorypath).':'
 8178:                        .&escape($getpropath).':'.&escape($uname).':'
 8179:                        .&escape($udom),homeserver($uname,$udom));
 8180:     if ($listing eq 'unknown_cmd') {
 8181:         if ($getpropath) {
 8182:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
 8183:         }
 8184:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
 8185:     }
 8186:     return $listing;
 8187: }
 8188: 
 8189: sub is_locked {
 8190:     my ($file_name, $domain, $user, $which) = @_;
 8191:     my @check;
 8192:     my $is_locked;
 8193:     push (@check,$file_name);
 8194:     my %locked = &get('file_permissions',\@check,
 8195: 		      $env{'user.domain'},$env{'user.name'});
 8196:     my ($tmp)=keys(%locked);
 8197:     if ($tmp=~/^error:/) { undef(%locked); }
 8198:     
 8199:     if (ref($locked{$file_name}) eq 'ARRAY') {
 8200:         $is_locked = 'false';
 8201:         foreach my $entry (@{$locked{$file_name}}) {
 8202:            if (ref($entry) eq 'ARRAY') {
 8203:                $is_locked = 'true';
 8204:                if (ref($which) eq 'ARRAY') {
 8205:                    push(@{$which},$entry);
 8206:                } else {
 8207:                    last;
 8208:                }
 8209:            }
 8210:        }
 8211:     } else {
 8212:         $is_locked = 'false';
 8213:     }
 8214:     return $is_locked;
 8215: }
 8216: 
 8217: sub declutter_portfile {
 8218:     my ($file) = @_;
 8219:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 8220:     return $file;
 8221: }
 8222: 
 8223: # ------------------------------------------------------------- Mark as Read Only
 8224: 
 8225: sub mark_as_readonly {
 8226:     my ($domain,$user,$files,$what) = @_;
 8227:     my %current_permissions = &dump('file_permissions',$domain,$user);
 8228:     my ($tmp)=keys(%current_permissions);
 8229:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 8230:     foreach my $file (@{$files}) {
 8231: 	$file = &declutter_portfile($file);
 8232:         push(@{$current_permissions{$file}},$what);
 8233:     }
 8234:     &put('file_permissions',\%current_permissions,$domain,$user);
 8235:     return;
 8236: }
 8237: 
 8238: # ------------------------------------------------------------Save Selected Files
 8239: 
 8240: sub save_selected_files {
 8241:     my ($user, $path, @files) = @_;
 8242:     my $filename = $user."savedfiles";
 8243:     my @other_files = &files_not_in_path($user, $path);
 8244:     open (OUT, '>'.$tmpdir.$filename);
 8245:     foreach my $file (@files) {
 8246:         print (OUT $env{'form.currentpath'}.$file."\n");
 8247:     }
 8248:     foreach my $file (@other_files) {
 8249:         print (OUT $file."\n");
 8250:     }
 8251:     close (OUT);
 8252:     return 'ok';
 8253: }
 8254: 
 8255: sub clear_selected_files {
 8256:     my ($user) = @_;
 8257:     my $filename = $user."savedfiles";
 8258:     open (OUT, '>'.LONCAPA::tempdir().$filename);
 8259:     print (OUT undef);
 8260:     close (OUT);
 8261:     return ("ok");    
 8262: }
 8263: 
 8264: sub files_in_path {
 8265:     my ($user, $path) = @_;
 8266:     my $filename = $user."savedfiles";
 8267:     my %return_files;
 8268:     open (IN, '<'.LONCAPA::tempdir().$filename);
 8269:     while (my $line_in = <IN>) {
 8270:         chomp ($line_in);
 8271:         my @paths_and_file = split (m!/!, $line_in);
 8272:         my $file_part = pop (@paths_and_file);
 8273:         my $path_part = join ('/', @paths_and_file);
 8274:         $path_part.='/';
 8275:         my $path_and_file = $path_part.$file_part;
 8276:         if ($path_part eq $path) {
 8277:             $return_files{$file_part}= 'selected';
 8278:         }
 8279:     }
 8280:     close (IN);
 8281:     return (\%return_files);
 8282: }
 8283: 
 8284: # called in portfolio select mode, to show files selected NOT in current directory
 8285: sub files_not_in_path {
 8286:     my ($user, $path) = @_;
 8287:     my $filename = $user."savedfiles";
 8288:     my @return_files;
 8289:     my $path_part;
 8290:     open(IN, '<'.LONCAPA::.$filename);
 8291:     while (my $line = <IN>) {
 8292:         #ok, I know it's clunky, but I want it to work
 8293:         my @paths_and_file = split(m|/|, $line);
 8294:         my $file_part = pop(@paths_and_file);
 8295:         chomp($file_part);
 8296:         my $path_part = join('/', @paths_and_file);
 8297:         $path_part .= '/';
 8298:         my $path_and_file = $path_part.$file_part;
 8299:         if ($path_part ne $path) {
 8300:             push(@return_files, ($path_and_file));
 8301:         }
 8302:     }
 8303:     close(OUT);
 8304:     return (@return_files);
 8305: }
 8306: 
 8307: #----------------------------------------------Get portfolio file permissions
 8308: 
 8309: sub get_portfile_permissions {
 8310:     my ($domain,$user) = @_;
 8311:     my %current_permissions = &dump('file_permissions',$domain,$user);
 8312:     my ($tmp)=keys(%current_permissions);
 8313:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 8314:     return \%current_permissions;
 8315: }
 8316: 
 8317: #---------------------------------------------Get portfolio file access controls
 8318: 
 8319: sub get_access_controls {
 8320:     my ($current_permissions,$group,$file) = @_;
 8321:     my %access;
 8322:     my $real_file = $file;
 8323:     $file =~ s/\.meta$//;
 8324:     if (defined($file)) {
 8325:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 8326:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 8327:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 8328:             }
 8329:         }
 8330:     } else {
 8331:         foreach my $key (keys(%{$current_permissions})) {
 8332:             if ($key =~ /\0accesscontrol$/) {
 8333:                 if (defined($group)) {
 8334:                     if ($key !~ m-^\Q$group\E/-) {
 8335:                         next;
 8336:                     }
 8337:                 }
 8338:                 my ($fullpath) = split(/\0/,$key);
 8339:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 8340:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 8341:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 8342:                     }
 8343:                 }
 8344:             }
 8345:         }
 8346:     }
 8347:     return %access;
 8348: }
 8349: 
 8350: sub modify_access_controls {
 8351:     my ($file_name,$changes,$domain,$user)=@_;
 8352:     my ($outcome,$deloutcome);
 8353:     my %store_permissions;
 8354:     my %new_values;
 8355:     my %new_control;
 8356:     my %translation;
 8357:     my @deletions = ();
 8358:     my $now = time;
 8359:     if (exists($$changes{'activate'})) {
 8360:         if (ref($$changes{'activate'}) eq 'HASH') {
 8361:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 8362:             my $numnew = scalar(@newitems);
 8363:             for (my $i=0; $i<$numnew; $i++) {
 8364:                 my $newkey = $newitems[$i];
 8365:                 my $newid = &Apache::loncommon::get_cgi_id();
 8366:                 if ($newkey =~ /^\d+:/) { 
 8367:                     $newkey =~ s/^(\d+)/$newid/;
 8368:                     $translation{$1} = $newid;
 8369:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 8370:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 8371:                     $translation{$1} = $newid;
 8372:                 }
 8373:                 $new_values{$file_name."\0".$newkey} = 
 8374:                                           $$changes{'activate'}{$newitems[$i]};
 8375:                 $new_control{$newkey} = $now;
 8376:             }
 8377:         }
 8378:     }
 8379:     my %todelete;
 8380:     my %changed_items;
 8381:     foreach my $action ('delete','update') {
 8382:         if (exists($$changes{$action})) {
 8383:             if (ref($$changes{$action}) eq 'HASH') {
 8384:                 foreach my $key (keys(%{$$changes{$action}})) {
 8385:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 8386:                     if ($action eq 'delete') { 
 8387:                         $todelete{$itemnum} = 1;
 8388:                     } else {
 8389:                         $changed_items{$itemnum} = $key;
 8390:                     }
 8391:                 }
 8392:             }
 8393:         }
 8394:     }
 8395:     # get lock on access controls for file.
 8396:     my $lockhash = {
 8397:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 8398:                                                        ':'.$env{'user.domain'},
 8399:                    }; 
 8400:     my $tries = 0;
 8401:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 8402:    
 8403:     while (($gotlock ne 'ok') && $tries <3) {
 8404:         $tries ++;
 8405:         sleep 1;
 8406:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 8407:     }
 8408:     if ($gotlock eq 'ok') {
 8409:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 8410:         my ($tmp)=keys(%curr_permissions);
 8411:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 8412:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 8413:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 8414:             if (ref($curr_controls) eq 'HASH') {
 8415:                 foreach my $control_item (keys(%{$curr_controls})) {
 8416:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 8417:                     if (defined($todelete{$itemnum})) {
 8418:                         push(@deletions,$file_name."\0".$control_item);
 8419:                     } else {
 8420:                         if (defined($changed_items{$itemnum})) {
 8421:                             $new_control{$changed_items{$itemnum}} = $now;
 8422:                             push(@deletions,$file_name."\0".$control_item);
 8423:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 8424:                         } else {
 8425:                             $new_control{$control_item} = $$curr_controls{$control_item};
 8426:                         }
 8427:                     }
 8428:                 }
 8429:             }
 8430:         }
 8431:         my ($group);
 8432:         if (&is_course($domain,$user)) {
 8433:             ($group,my $file) = split(/\//,$file_name,2);
 8434:         }
 8435:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 8436:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 8437:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 8438:         #  remove lock
 8439:         my @del_lock = ($file_name."\0".'locked_access_records');
 8440:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 8441:         my $sqlresult =
 8442:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
 8443:                                     $group);
 8444:     } else {
 8445:         $outcome = "error: could not obtain lockfile\n";  
 8446:     }
 8447:     return ($outcome,$deloutcome,\%new_values,\%translation);
 8448: }
 8449: 
 8450: sub make_public_indefinitely {
 8451:     my ($requrl) = @_;
 8452:     my $now = time;
 8453:     my $action = 'activate';
 8454:     my $aclnum = 0;
 8455:     if (&is_portfolio_url($requrl)) {
 8456:         my (undef,$udom,$unum,$file_name,$group) =
 8457:             &parse_portfolio_url($requrl);
 8458:         my $current_perms = &get_portfile_permissions($udom,$unum);
 8459:         my %access_controls = &get_access_controls($current_perms,
 8460:                                                    $group,$file_name);
 8461:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 8462:             my ($num,$scope,$end,$start) = 
 8463:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 8464:             if ($scope eq 'public') {
 8465:                 if ($start <= $now && $end == 0) {
 8466:                     $action = 'none';
 8467:                 } else {
 8468:                     $action = 'update';
 8469:                     $aclnum = $num;
 8470:                 }
 8471:                 last;
 8472:             }
 8473:         }
 8474:         if ($action eq 'none') {
 8475:              return 'ok';
 8476:         } else {
 8477:             my %changes;
 8478:             my $newend = 0;
 8479:             my $newstart = $now;
 8480:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 8481:             $changes{$action}{$newkey} = {
 8482:                 type => 'public',
 8483:                 time => {
 8484:                     start => $newstart,
 8485:                     end   => $newend,
 8486:                 },
 8487:             };
 8488:             my ($outcome,$deloutcome,$new_values,$translation) =
 8489:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 8490:             return $outcome;
 8491:         }
 8492:     } else {
 8493:         return 'invalid';
 8494:     }
 8495: }
 8496: 
 8497: #------------------------------------------------------Get Marked as Read Only
 8498: 
 8499: sub get_marked_as_readonly {
 8500:     my ($domain,$user,$what,$group) = @_;
 8501:     my $current_permissions = &get_portfile_permissions($domain,$user);
 8502:     my @readonly_files;
 8503:     my $cmp1=$what;
 8504:     if (ref($what)) { $cmp1=join('',@{$what}) };
 8505:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 8506:         if (defined($group)) {
 8507:             if ($file_name !~ m-^\Q$group\E/-) {
 8508:                 next;
 8509:             }
 8510:         }
 8511:         if (ref($value) eq "ARRAY"){
 8512:             foreach my $stored_what (@{$value}) {
 8513:                 my $cmp2=$stored_what;
 8514:                 if (ref($stored_what) eq 'ARRAY') {
 8515:                     $cmp2=join('',@{$stored_what});
 8516:                 }
 8517:                 if ($cmp1 eq $cmp2) {
 8518:                     push(@readonly_files, $file_name);
 8519:                     last;
 8520:                 } elsif (!defined($what)) {
 8521:                     push(@readonly_files, $file_name);
 8522:                     last;
 8523:                 }
 8524:             }
 8525:         }
 8526:     }
 8527:     return @readonly_files;
 8528: }
 8529: #-----------------------------------------------------------Get Marked as Read Only Hash
 8530: 
 8531: sub get_marked_as_readonly_hash {
 8532:     my ($current_permissions,$group,$what) = @_;
 8533:     my %readonly_files;
 8534:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 8535:         if (defined($group)) {
 8536:             if ($file_name !~ m-^\Q$group\E/-) {
 8537:                 next;
 8538:             }
 8539:         }
 8540:         if (ref($value) eq "ARRAY"){
 8541:             foreach my $stored_what (@{$value}) {
 8542:                 if (ref($stored_what) eq 'ARRAY') {
 8543:                     foreach my $lock_descriptor(@{$stored_what}) {
 8544:                         if ($lock_descriptor eq 'graded') {
 8545:                             $readonly_files{$file_name} = 'graded';
 8546:                         } elsif ($lock_descriptor eq 'handback') {
 8547:                             $readonly_files{$file_name} = 'handback';
 8548:                         } else {
 8549:                             if (!exists($readonly_files{$file_name})) {
 8550:                                 $readonly_files{$file_name} = 'locked';
 8551:                             }
 8552:                         }
 8553:                     }
 8554:                 } 
 8555:             }
 8556:         } 
 8557:     }
 8558:     return %readonly_files;
 8559: }
 8560: # ------------------------------------------------------------ Unmark as Read Only
 8561: 
 8562: sub unmark_as_readonly {
 8563:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 8564:     # for portfolio submissions, $what contains [$symb,$crsid] 
 8565:     my ($domain,$user,$what,$file_name,$group) = @_;
 8566:     $file_name = &declutter_portfile($file_name);
 8567:     my $symb_crs = $what;
 8568:     if (ref($what)) { $symb_crs=join('',@$what); }
 8569:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 8570:     my ($tmp)=keys(%current_permissions);
 8571:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 8572:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 8573:     foreach my $file (@readonly_files) {
 8574: 	my $clean_file = &declutter_portfile($file);
 8575: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 8576: 	my $current_locks = $current_permissions{$file};
 8577:         my @new_locks;
 8578:         my @del_keys;
 8579:         if (ref($current_locks) eq "ARRAY"){
 8580:             foreach my $locker (@{$current_locks}) {
 8581:                 my $compare=$locker;
 8582:                 if (ref($locker) eq 'ARRAY') {
 8583:                     $compare=join('',@{$locker});
 8584:                     if ($compare ne $symb_crs) {
 8585:                         push(@new_locks, $locker);
 8586:                     }
 8587:                 }
 8588:             }
 8589:             if (scalar(@new_locks) > 0) {
 8590:                 $current_permissions{$file} = \@new_locks;
 8591:             } else {
 8592:                 push(@del_keys, $file);
 8593:                 &del('file_permissions',\@del_keys, $domain, $user);
 8594:                 delete($current_permissions{$file});
 8595:             }
 8596:         }
 8597:     }
 8598:     &put('file_permissions',\%current_permissions,$domain,$user);
 8599:     return;
 8600: }
 8601: 
 8602: # ------------------------------------------------------------ Directory lister
 8603: 
 8604: sub dirlist {
 8605:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
 8606:     $uri=~s/^\///;
 8607:     $uri=~s/\/$//;
 8608:     my ($udom, $uname);
 8609:     if ($getuserdir) {
 8610:         $udom = $userdomain;
 8611:         $uname = $username;
 8612:     } else {
 8613:         (undef,$udom,$uname)=split(/\//,$uri);
 8614:         if(defined($userdomain)) {
 8615:             $udom = $userdomain;
 8616:         }
 8617:         if(defined($username)) {
 8618:             $uname = $username;
 8619:         }
 8620:     }
 8621:     my ($dirRoot,$listing,@listing_results);
 8622: 
 8623:     $dirRoot = $perlvar{'lonDocRoot'};
 8624:     if (defined($getpropath)) {
 8625:         $dirRoot = &propath($udom,$uname);
 8626:         $dirRoot =~ s/\/$//;
 8627:     } elsif (defined($getuserdir)) {
 8628:         my $subdir=$uname.'__';
 8629:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 8630:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
 8631:                    ."/$udom/$subdir/$uname";
 8632:     } elsif (defined($alternateRoot)) {
 8633:         $dirRoot = $alternateRoot;
 8634:     }
 8635: 
 8636:     if($udom) {
 8637:         if($uname) {
 8638:             my $uhome = &homeserver($uname,$udom);
 8639:             if ($uhome eq 'no_host') {
 8640:                 return ([],'no_host');
 8641:             }
 8642:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
 8643:                               .$getuserdir.':'.&escape($dirRoot)
 8644:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
 8645:             if ($listing eq 'unknown_cmd') {
 8646:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
 8647:             } else {
 8648:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 8649:             }
 8650:             if ($listing eq 'unknown_cmd') {
 8651:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
 8652:                 @listing_results = split(/:/,$listing);
 8653:             } else {
 8654:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 8655:             }
 8656:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
 8657:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
 8658:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 8659:                 return ([],$listing);
 8660:             } else {
 8661:                 return (\@listing_results);
 8662:             }
 8663:         } elsif(!$alternateRoot) {
 8664:             my (%allusers,%listerror);
 8665: 	    my %servers = &get_servers($udom,'library');
 8666:  	    foreach my $tryserver (keys(%servers)) {
 8667:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
 8668:                                   &escape($udom),$tryserver);
 8669:                 if ($listing eq 'unknown_cmd') {
 8670: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 8671: 				      $udom, $tryserver);
 8672:                 } else {
 8673:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
 8674:                 }
 8675: 		if ($listing eq 'unknown_cmd') {
 8676: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 8677: 				      $udom, $tryserver);
 8678: 		    @listing_results = split(/:/,$listing);
 8679: 		} else {
 8680: 		    @listing_results =
 8681: 			map { &unescape($_); } split(/:/,$listing);
 8682: 		}
 8683:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
 8684:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
 8685:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 8686:                     $listerror{$tryserver} = $listing;
 8687:                 } else {
 8688: 		    foreach my $line (@listing_results) {
 8689: 			my ($entry) = split(/&/,$line,2);
 8690: 			$allusers{$entry} = 1;
 8691: 		    }
 8692: 		}
 8693:             }
 8694:             my @alluserslist=();
 8695:             foreach my $user (sort(keys(%allusers))) {
 8696:                 push(@alluserslist,$user.'&user');
 8697:             }
 8698:             return (\@alluserslist);
 8699:         } else {
 8700:             return ([],'missing username');
 8701:         }
 8702:     } elsif(!defined($getpropath)) {
 8703:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
 8704:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
 8705:         return (\@all_domains);
 8706:     } else {
 8707:         return ([],'missing domain');
 8708:     }
 8709: }
 8710: 
 8711: # --------------------------------------------- GetFileTimestamp
 8712: # This function utilizes dirlist and returns the date stamp for
 8713: # when it was last modified.  It will also return an error of -1
 8714: # if an error occurs
 8715: 
 8716: sub GetFileTimestamp {
 8717:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
 8718:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 8719:     $studentName   = &LONCAPA::clean_username($studentName);
 8720:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
 8721:                                     undef,$getuserdir);
 8722:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 8723:         return -1;
 8724:     }
 8725:     if (ref($fileref) eq 'ARRAY') {
 8726:         my @stats = split('&',$fileref->[0]);
 8727:         # @stats contains first the filename, then the stat output
 8728:         return $stats[10]; # so this is 10 instead of 9.
 8729:     } else {
 8730:         return -1;
 8731:     }
 8732: }
 8733: 
 8734: sub stat_file {
 8735:     my ($uri) = @_;
 8736:     $uri = &clutter_with_no_wrapper($uri);
 8737: 
 8738:     my ($udom,$uname,$file);
 8739:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 8740: 	($udom,$uname,$file) =
 8741: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 8742: 	$file = 'userfiles/'.$file;
 8743:     }
 8744:     if ($uri =~ m-^/res/-) {
 8745: 	($udom,$uname) = 
 8746: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 8747: 	$file = $uri;
 8748:     }
 8749: 
 8750:     if (!$udom || !$uname || !$file) {
 8751: 	# unable to handle the uri
 8752: 	return ();
 8753:     }
 8754:     my $getpropath;
 8755:     if ($file =~ /^userfiles\//) {
 8756:         $getpropath = 1;
 8757:     }
 8758:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
 8759:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 8760:         return ();
 8761:     } else {
 8762:         if (ref($listref) eq 'ARRAY') {
 8763:             my @stats = split('&',$listref->[0]);
 8764: 	    shift(@stats); #filename is first
 8765: 	    return @stats;
 8766:         }
 8767:     }
 8768:     return ();
 8769: }
 8770: 
 8771: # -------------------------------------------------------- Value of a Condition
 8772: 
 8773: # gets the value of a specific preevaluated condition
 8774: #    stored in the string  $env{user.state.<cid>}
 8775: # or looks up a condition reference in the bighash and if if hasn't
 8776: # already been evaluated recurses into docondval to get the value of
 8777: # the condition, then memoizing it to 
 8778: #   $env{user.state.<cid>.<condition>}
 8779: sub directcondval {
 8780:     my $number=shift;
 8781:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 8782: 	&Apache::lonuserstate::evalstate();
 8783:     }
 8784:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 8785: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 8786:     } elsif ($number =~ /^_/) {
 8787: 	my $sub_condition;
 8788: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8789: 		&GDBM_READER(),0640)) {
 8790: 	    $sub_condition=$bighash{'conditions'.$number};
 8791: 	    untie(%bighash);
 8792: 	}
 8793: 	my $value = &docondval($sub_condition);
 8794: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
 8795: 	return $value;
 8796:     }
 8797:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 8798:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 8799:     } else {
 8800:        return 2;
 8801:     }
 8802: }
 8803: 
 8804: # get the collection of conditions for this resource
 8805: sub condval {
 8806:     my $condidx=shift;
 8807:     my $allpathcond='';
 8808:     foreach my $cond (split(/\|/,$condidx)) {
 8809: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 8810: 	    $allpathcond.=
 8811: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 8812: 	}
 8813:     }
 8814:     $allpathcond=~s/\|$//;
 8815:     return &docondval($allpathcond);
 8816: }
 8817: 
 8818: #evaluates an expression of conditions
 8819: sub docondval {
 8820:     my ($allpathcond) = @_;
 8821:     my $result=0;
 8822:     if ($env{'request.course.id'}
 8823: 	&& defined($allpathcond)) {
 8824: 	my $operand='|';
 8825: 	my @stack;
 8826: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 8827: 	    if ($chunk eq '(') {
 8828: 		push @stack,($operand,$result);
 8829: 	    } elsif ($chunk eq ')') {
 8830: 		my $before=pop @stack;
 8831: 		if (pop @stack eq '&') {
 8832: 		    $result=$result>$before?$before:$result;
 8833: 		} else {
 8834: 		    $result=$result>$before?$result:$before;
 8835: 		}
 8836: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 8837: 		$operand=$chunk;
 8838: 	    } else {
 8839: 		my $new=directcondval($chunk);
 8840: 		if ($operand eq '&') {
 8841: 		    $result=$result>$new?$new:$result;
 8842: 		} else {
 8843: 		    $result=$result>$new?$result:$new;
 8844: 		}
 8845: 	    }
 8846: 	}
 8847:     }
 8848:     return $result;
 8849: }
 8850: 
 8851: # ---------------------------------------------------- Devalidate courseresdata
 8852: 
 8853: sub devalidatecourseresdata {
 8854:     my ($coursenum,$coursedomain)=@_;
 8855:     my $hashid=$coursenum.':'.$coursedomain;
 8856:     &devalidate_cache_new('courseres',$hashid);
 8857: }
 8858: 
 8859: 
 8860: # --------------------------------------------------- Course Resourcedata Query
 8861: #
 8862: #  Parameters:
 8863: #      $coursenum    - Number of the course.
 8864: #      $coursedomain - Domain at which the course was created.
 8865: #  Returns:
 8866: #     A hash of the course parameters along (I think) with timestamps
 8867: #     and version info.
 8868: 
 8869: sub get_courseresdata {
 8870:     my ($coursenum,$coursedomain)=@_;
 8871:     my $coursehom=&homeserver($coursenum,$coursedomain);
 8872:     my $hashid=$coursenum.':'.$coursedomain;
 8873:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 8874:     my %dumpreply;
 8875:     unless (defined($cached)) {
 8876: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 8877: 	$result=\%dumpreply;
 8878: 	my ($tmp) = keys(%dumpreply);
 8879: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 8880: 	    &do_cache_new('courseres',$hashid,$result,600);
 8881: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 8882: 	    return $tmp;
 8883: 	} elsif ($tmp =~ /^(error)/) {
 8884: 	    $result=undef;
 8885: 	    &do_cache_new('courseres',$hashid,$result,600);
 8886: 	}
 8887:     }
 8888:     return $result;
 8889: }
 8890: 
 8891: sub devalidateuserresdata {
 8892:     my ($uname,$udom)=@_;
 8893:     my $hashid="$udom:$uname";
 8894:     &devalidate_cache_new('userres',$hashid);
 8895: }
 8896: 
 8897: sub get_userresdata {
 8898:     my ($uname,$udom)=@_;
 8899:     #most student don\'t have any data set, check if there is some data
 8900:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 8901: 
 8902:     my $hashid="$udom:$uname";
 8903:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 8904:     if (!defined($cached)) {
 8905: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 8906: 	$result=\%resourcedata;
 8907: 	&do_cache_new('userres',$hashid,$result,600);
 8908:     }
 8909:     my ($tmp)=keys(%$result);
 8910:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 8911: 	return $result;
 8912:     }
 8913:     #error 2 occurs when the .db doesn't exist
 8914:     if ($tmp!~/error: 2 /) {
 8915: 	&logthis("<font color=\"blue\">WARNING:".
 8916: 		 " Trying to get resource data for ".
 8917: 		 $uname." at ".$udom.": ".
 8918: 		 $tmp."</font>");
 8919:     } elsif ($tmp=~/error: 2 /) {
 8920: 	#&EXT_cache_set($udom,$uname);
 8921: 	&do_cache_new('userres',$hashid,undef,600);
 8922: 	undef($tmp); # not really an error so don't send it back
 8923:     }
 8924:     return $tmp;
 8925: }
 8926: #----------------------------------------------- resdata - return resource data
 8927: #  Purpose:
 8928: #    Return resource data for either users or for a course.
 8929: #  Parameters:
 8930: #     $name      - Course/user name.
 8931: #     $domain    - Name of the domain the user/course is registered on.
 8932: #     $type      - Type of thing $name is (must be 'course' or 'user'
 8933: #     @which     - Array of names of resources desired.
 8934: #  Returns:
 8935: #     The value of the first reasource in @which that is found in the
 8936: #     resource hash.
 8937: #  Exceptional Conditions:
 8938: #     If the $type passed in is not valid (not the string 'course' or 
 8939: #     'user', an undefined  reference is returned.
 8940: #     If none of the resources are found, an undef is returned
 8941: sub resdata {
 8942:     my ($name,$domain,$type,@which)=@_;
 8943:     my $result;
 8944:     if ($type eq 'course') {
 8945: 	$result=&get_courseresdata($name,$domain);
 8946:     } elsif ($type eq 'user') {
 8947: 	$result=&get_userresdata($name,$domain);
 8948:     }
 8949:     if (!ref($result)) { return $result; }    
 8950:     foreach my $item (@which) {
 8951: 	if (defined($result->{$item->[0]})) {
 8952: 	    return [$result->{$item->[0]},$item->[1]];
 8953: 	}
 8954:     }
 8955:     return undef;
 8956: }
 8957: 
 8958: #
 8959: # EXT resource caching routines
 8960: #
 8961: 
 8962: sub clear_EXT_cache_status {
 8963:     &delenv('cache.EXT.');
 8964: }
 8965: 
 8966: sub EXT_cache_status {
 8967:     my ($target_domain,$target_user) = @_;
 8968:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 8969:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 8970:         # We know already the user has no data
 8971:         return 1;
 8972:     } else {
 8973:         return 0;
 8974:     }
 8975: }
 8976: 
 8977: sub EXT_cache_set {
 8978:     my ($target_domain,$target_user) = @_;
 8979:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 8980:     #&appenv({$cachename => time});
 8981: }
 8982: 
 8983: # --------------------------------------------------------- Value of a Variable
 8984: sub EXT {
 8985: 
 8986:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
 8987:     unless ($varname) { return ''; }
 8988:     #get real user name/domain, courseid and symb
 8989:     my $courseid;
 8990:     my $publicuser;
 8991:     if ($symbparm) {
 8992: 	$symbparm=&get_symb_from_alias($symbparm);
 8993:     }
 8994:     if (!($uname && $udom)) {
 8995:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 8996:       if (!$symbparm) {	$symbparm=$cursymb; }
 8997:     } else {
 8998: 	$courseid=$env{'request.course.id'};
 8999:     }
 9000:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 9001:     my $rest;
 9002:     if (defined($therest[0])) {
 9003:        $rest=join('.',@therest);
 9004:     } else {
 9005:        $rest='';
 9006:     }
 9007: 
 9008:     my $qualifierrest=$qualifier;
 9009:     if ($rest) { $qualifierrest.='.'.$rest; }
 9010:     my $spacequalifierrest=$space;
 9011:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 9012:     if ($realm eq 'user') {
 9013: # --------------------------------------------------------------- user.resource
 9014: 	if ($space eq 'resource') {
 9015: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 9016: 		  || defined($Apache::lonhomework::parsing_a_task))
 9017: 		 &&
 9018: 		 ($symbparm eq &symbread()) ) {	
 9019: 		# if we are in the middle of processing the resource the
 9020: 		# get the value we are planning on committing
 9021:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 9022:                     return $Apache::lonhomework::results{$qualifierrest};
 9023:                 } else {
 9024:                     return $Apache::lonhomework::history{$qualifierrest};
 9025:                 }
 9026: 	    } else {
 9027: 		my %restored;
 9028: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 9029: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 9030: 		} else {
 9031: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 9032: 		}
 9033: 		return $restored{$qualifierrest};
 9034: 	    }
 9035: # ----------------------------------------------------------------- user.access
 9036:         } elsif ($space eq 'access') {
 9037: 	    # FIXME - not supporting calls for a specific user
 9038:             return &allowed($qualifier,$rest);
 9039: # ------------------------------------------ user.preferences, user.environment
 9040:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 9041: 	    if (($uname eq $env{'user.name'}) &&
 9042: 		($udom eq $env{'user.domain'})) {
 9043: 		return $env{join('.',('environment',$qualifierrest))};
 9044: 	    } else {
 9045: 		my %returnhash;
 9046: 		if (!$publicuser) {
 9047: 		    %returnhash=&userenvironment($udom,$uname,
 9048: 						 $qualifierrest);
 9049: 		}
 9050: 		return $returnhash{$qualifierrest};
 9051: 	    }
 9052: # ----------------------------------------------------------------- user.course
 9053:         } elsif ($space eq 'course') {
 9054: 	    # FIXME - not supporting calls for a specific user
 9055:             return $env{join('.',('request.course',$qualifier))};
 9056: # ------------------------------------------------------------------- user.role
 9057:         } elsif ($space eq 'role') {
 9058: 	    # FIXME - not supporting calls for a specific user
 9059:             my ($role,$where)=split(/\./,$env{'request.role'});
 9060:             if ($qualifier eq 'value') {
 9061: 		return $role;
 9062:             } elsif ($qualifier eq 'extent') {
 9063:                 return $where;
 9064:             }
 9065: # ----------------------------------------------------------------- user.domain
 9066:         } elsif ($space eq 'domain') {
 9067:             return $udom;
 9068: # ------------------------------------------------------------------- user.name
 9069:         } elsif ($space eq 'name') {
 9070:             return $uname;
 9071: # ---------------------------------------------------- Any other user namespace
 9072:         } else {
 9073: 	    my %reply;
 9074: 	    if (!$publicuser) {
 9075: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 9076: 	    }
 9077: 	    return $reply{$qualifierrest};
 9078:         }
 9079:     } elsif ($realm eq 'query') {
 9080: # ---------------------------------------------- pull stuff out of query string
 9081:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 9082: 						[$spacequalifierrest]);
 9083: 	return $env{'form.'.$spacequalifierrest}; 
 9084:    } elsif ($realm eq 'request') {
 9085: # ------------------------------------------------------------- request.browser
 9086:         if ($space eq 'browser') {
 9087:             return $env{'browser.'.$qualifier};
 9088: # ------------------------------------------------------------ request.filename
 9089:         } else {
 9090:             return $env{'request.'.$spacequalifierrest};
 9091:         }
 9092:     } elsif ($realm eq 'course') {
 9093: # ---------------------------------------------------------- course.description
 9094:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 9095:     } elsif ($realm eq 'resource') {
 9096: 
 9097: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 9098: 	    if (!$symbparm) { $symbparm=&symbread(); }
 9099: 	}
 9100: 
 9101: 	if ($space eq 'title') {
 9102: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 9103: 	    return &gettitle($symbparm);
 9104: 	}
 9105: 	
 9106: 	if ($space eq 'map') {
 9107: 	    my ($map) = &decode_symb($symbparm);
 9108: 	    return &symbread($map);
 9109: 	}
 9110: 	if ($space eq 'filename') {
 9111: 	    if ($symbparm) {
 9112: 		return &clutter((&decode_symb($symbparm))[2]);
 9113: 	    }
 9114: 	    return &hreflocation('',$env{'request.filename'});
 9115: 	}
 9116: 
 9117: 	my ($section, $group, @groups);
 9118: 	my ($courselevelm,$courselevel);
 9119: 	if ($symbparm && defined($courseid) && 
 9120: 	    $courseid eq $env{'request.course.id'}) {
 9121: 
 9122: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 9123: 
 9124: # ----------------------------------------------------- Cascading lookup scheme
 9125: 	    my $symbp=$symbparm;
 9126: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 9127: 
 9128: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 9129: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 9130: 
 9131: 	    if (($env{'user.name'} eq $uname) &&
 9132: 		($env{'user.domain'} eq $udom)) {
 9133: 		$section=$env{'request.course.sec'};
 9134:                 @groups = split(/:/,$env{'request.course.groups'});  
 9135:                 @groups=&sort_course_groups($courseid,@groups); 
 9136: 	    } else {
 9137: 		if (! defined($usection)) {
 9138: 		    $section=&getsection($udom,$uname,$courseid);
 9139: 		} else {
 9140: 		    $section = $usection;
 9141: 		}
 9142:                 @groups = &get_users_groups($udom,$uname,$courseid);
 9143: 	    }
 9144: 
 9145: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 9146: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 9147: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 9148: 
 9149: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 9150: 	    my $courselevelr=$courseid.'.'.$symbparm;
 9151: 	    $courselevelm=$courseid.'.'.$mapparm;
 9152: 
 9153: # ----------------------------------------------------------- first, check user
 9154: 
 9155: 	    my $userreply=&resdata($uname,$udom,'user',
 9156: 				       ([$courselevelr,'resource'],
 9157: 					[$courselevelm,'map'     ],
 9158: 					[$courselevel, 'course'  ]));
 9159: 	    if (defined($userreply)) { return &get_reply($userreply); }
 9160: 
 9161: # ------------------------------------------------ second, check some of course
 9162:             my $coursereply;
 9163:             if (@groups > 0) {
 9164:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 9165:                                        $mapparm,$spacequalifierrest);
 9166:                 if (defined($coursereply)) { return &get_reply($coursereply); }
 9167:             }
 9168: 
 9169: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 9170: 				  $env{'course.'.$courseid.'.domain'},
 9171: 				  'course',
 9172: 				  ([$seclevelr,   'resource'],
 9173: 				   [$seclevelm,   'map'     ],
 9174: 				   [$seclevel,    'course'  ],
 9175: 				   [$courselevelr,'resource']));
 9176: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 9177: 
 9178: # ------------------------------------------------------ third, check map parms
 9179: 	    my %parmhash=();
 9180: 	    my $thisparm='';
 9181: 	    if (tie(%parmhash,'GDBM_File',
 9182: 		    $env{'request.course.fn'}.'_parms.db',
 9183: 		    &GDBM_READER(),0640)) {
 9184: 		$thisparm=$parmhash{$symbparm};
 9185: 		untie(%parmhash);
 9186: 	    }
 9187: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
 9188: 	}
 9189: # ------------------------------------------ fourth, look in resource metadata
 9190: 
 9191: 	$spacequalifierrest=~s/\./\_/;
 9192: 	my $filename;
 9193: 	if (!$symbparm) { $symbparm=&symbread(); }
 9194: 	if ($symbparm) {
 9195: 	    $filename=(&decode_symb($symbparm))[2];
 9196: 	} else {
 9197: 	    $filename=$env{'request.filename'};
 9198: 	}
 9199: 	my $metadata=&metadata($filename,$spacequalifierrest);
 9200: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 9201: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 9202: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 9203: 
 9204: # ---------------------------------------------- fourth, look in rest of course
 9205: 	if ($symbparm && defined($courseid) && 
 9206: 	    $courseid eq $env{'request.course.id'}) {
 9207: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 9208: 				     $env{'course.'.$courseid.'.domain'},
 9209: 				     'course',
 9210: 				     ([$courselevelm,'map'   ],
 9211: 				      [$courselevel, 'course']));
 9212: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 9213: 	}
 9214: # ------------------------------------------------------------------ Cascade up
 9215: 	unless ($space eq '0') {
 9216: 	    my @parts=split(/_/,$space);
 9217: 	    my $id=pop(@parts);
 9218: 	    my $part=join('_',@parts);
 9219: 	    if ($part eq '') { $part='0'; }
 9220: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 9221: 				 $symbparm,$udom,$uname,$section,1);
 9222: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
 9223: 	}
 9224: 	if ($recurse) { return undef; }
 9225: 	my $pack_def=&packages_tab_default($filename,$varname);
 9226: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
 9227: # ---------------------------------------------------- Any other user namespace
 9228:     } elsif ($realm eq 'environment') {
 9229: # ----------------------------------------------------------------- environment
 9230: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 9231: 	    return $env{'environment.'.$spacequalifierrest};
 9232: 	} else {
 9233: 	    if ($uname eq 'anonymous' && $udom eq '') {
 9234: 		return '';
 9235: 	    }
 9236: 	    my %returnhash=&userenvironment($udom,$uname,
 9237: 					    $spacequalifierrest);
 9238: 	    return $returnhash{$spacequalifierrest};
 9239: 	}
 9240:     } elsif ($realm eq 'system') {
 9241: # ----------------------------------------------------------------- system.time
 9242: 	if ($space eq 'time') {
 9243: 	    return time;
 9244:         }
 9245:     } elsif ($realm eq 'server') {
 9246: # ----------------------------------------------------------------- system.time
 9247: 	if ($space eq 'name') {
 9248: 	    return $ENV{'SERVER_NAME'};
 9249:         }
 9250:     }
 9251:     return '';
 9252: }
 9253: 
 9254: sub get_reply {
 9255:     my ($reply_value) = @_;
 9256:     if (ref($reply_value) eq 'ARRAY') {
 9257:         if (wantarray) {
 9258: 	    return @$reply_value;
 9259:         }
 9260:         return $reply_value->[0];
 9261:     } else {
 9262:         return $reply_value;
 9263:     }
 9264: }
 9265: 
 9266: sub check_group_parms {
 9267:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
 9268:     my @groupitems = ();
 9269:     my $resultitem;
 9270:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
 9271:     foreach my $group (@{$groups}) {
 9272:         foreach my $level (@levels) {
 9273:              my $item = $courseid.'.['.$group.'].'.$level->[0];
 9274:              push(@groupitems,[$item,$level->[1]]);
 9275:         }
 9276:     }
 9277:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
 9278:                             $env{'course.'.$courseid.'.domain'},
 9279:                                      'course',@groupitems);
 9280:     return $coursereply;
 9281: }
 9282: 
 9283: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
 9284:     my ($courseid,@groups) = @_;
 9285:     @groups = sort(@groups);
 9286:     return @groups;
 9287: }
 9288: 
 9289: sub packages_tab_default {
 9290:     my ($uri,$varname)=@_;
 9291:     my (undef,$part,$name)=split(/\./,$varname);
 9292: 
 9293:     my (@extension,@specifics,$do_default);
 9294:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
 9295: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 9296: 	if ($pack_type eq 'default') {
 9297: 	    $do_default=1;
 9298: 	} elsif ($pack_type eq 'extension') {
 9299: 	    push(@extension,[$package,$pack_type,$pack_part]);
 9300: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
 9301: 	    # only look at packages defaults for packages that this id is
 9302: 	    push(@specifics,[$package,$pack_type,$pack_part]);
 9303: 	}
 9304:     }
 9305:     # first look for a package that matches the requested part id
 9306:     foreach my $package (@specifics) {
 9307: 	my (undef,$pack_type,$pack_part)=@{$package};
 9308: 	next if ($pack_part ne $part);
 9309: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 9310: 	    return $packagetab{"$pack_type&$name&default"};
 9311: 	}
 9312:     }
 9313:     # look for any possible matching non extension_ package
 9314:     foreach my $package (@specifics) {
 9315: 	my (undef,$pack_type,$pack_part)=@{$package};
 9316: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 9317: 	    return $packagetab{"$pack_type&$name&default"};
 9318: 	}
 9319: 	if ($pack_type eq 'part') { $pack_part='0'; }
 9320: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
 9321: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
 9322: 	}
 9323:     }
 9324:     # look for any posible extension_ match
 9325:     foreach my $package (@extension) {
 9326: 	my ($package,$pack_type)=@{$package};
 9327: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 9328: 	    return $packagetab{"$pack_type&$name&default"};
 9329: 	}
 9330: 	if (defined($packagetab{$package."&$name&default"})) {
 9331: 	    return $packagetab{$package."&$name&default"};
 9332: 	}
 9333:     }
 9334:     # look for a global default setting
 9335:     if ($do_default && defined($packagetab{"default&$name&default"})) {
 9336: 	return $packagetab{"default&$name&default"};
 9337:     }
 9338:     return undef;
 9339: }
 9340: 
 9341: sub add_prefix_and_part {
 9342:     my ($prefix,$part)=@_;
 9343:     my $keyroot;
 9344:     if (defined($prefix) && $prefix !~ /^__/) {
 9345: 	# prefix that has a part already
 9346: 	$keyroot=$prefix;
 9347:     } elsif (defined($prefix)) {
 9348: 	# prefix that is missing a part
 9349: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 9350:     } else {
 9351: 	# no prefix at all
 9352: 	if (defined($part)) { $keyroot='_'.$part; }
 9353:     }
 9354:     return $keyroot;
 9355: }
 9356: 
 9357: # ---------------------------------------------------------------- Get metadata
 9358: 
 9359: my %metaentry;
 9360: my %importedpartids;
 9361: sub metadata {
 9362:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 9363:     $uri=&declutter($uri);
 9364:     # if it is a non metadata possible uri return quickly
 9365:     if (($uri eq '') || 
 9366: 	(($uri =~ m|^/*adm/|) && 
 9367: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
 9368:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
 9369: 	return undef;
 9370:     }
 9371:     if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) 
 9372: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
 9373: 	return undef;
 9374:     }
 9375:     my $filename=$uri;
 9376:     $uri=~s/\.meta$//;
 9377: #
 9378: # Is the metadata already cached?
 9379: # Look at timestamp of caching
 9380: # Everything is cached by the main uri, libraries are never directly cached
 9381: #
 9382:     if (!defined($liburi)) {
 9383: 	my ($result,$cached)=&is_cached_new('meta',$uri);
 9384: 	if (defined($cached)) { return $result->{':'.$what}; }
 9385:     }
 9386:     {
 9387: # Imported parts would go here
 9388:         my %importedids=();
 9389:         my @origfileimportpartids=();
 9390:         my $importedparts=0;
 9391: #
 9392: # Is this a recursive call for a library?
 9393: #
 9394: #	if (! exists($metacache{$uri})) {
 9395: #	    $metacache{$uri}={};
 9396: #	}
 9397: 	my $cachetime = 60*60;
 9398:         if ($liburi) {
 9399: 	    $liburi=&declutter($liburi);
 9400:             $filename=$liburi;
 9401:         } else {
 9402: 	    &devalidate_cache_new('meta',$uri);
 9403: 	    undef(%metaentry);
 9404: 	}
 9405:         my %metathesekeys=();
 9406:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 9407: 	my $metastring;
 9408: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
 9409: 	    my $which = &hreflocation('','/'.($liburi || $uri));
 9410: 	    $metastring = 
 9411: 		&Apache::lonnet::ssi_body($which,
 9412: 					  ('grade_target' => 'meta'));
 9413: 	    $cachetime = 1; # only want this cached in the child not long term
 9414: 	} elsif (($uri !~ m -^(editupload)/-) && 
 9415:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
 9416: 	    my $file=&filelocation('',&clutter($filename));
 9417: 	    #push(@{$metaentry{$uri.'.file'}},$file);
 9418: 	    $metastring=&getfile($file);
 9419: 	}
 9420:         my $parser=HTML::LCParser->new(\$metastring);
 9421:         my $token;
 9422:         undef %metathesekeys;
 9423:         while ($token=$parser->get_token) {
 9424: 	    if ($token->[0] eq 'S') {
 9425: 		if (defined($token->[2]->{'package'})) {
 9426: #
 9427: # This is a package - get package info
 9428: #
 9429: 		    my $package=$token->[2]->{'package'};
 9430: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 9431: 		    if (defined($token->[2]->{'id'})) { 
 9432: 			$keyroot.='_'.$token->[2]->{'id'}; 
 9433: 		    }
 9434: 		    if ($metaentry{':packages'}) {
 9435: 			$metaentry{':packages'}.=','.$package.$keyroot;
 9436: 		    } else {
 9437: 			$metaentry{':packages'}=$package.$keyroot;
 9438: 		    }
 9439: 		    foreach my $pack_entry (keys(%packagetab)) {
 9440: 			my $part=$keyroot;
 9441: 			$part=~s/^\_//;
 9442: 			if ($pack_entry=~/^\Q$package\E\&/ || 
 9443: 			    $pack_entry=~/^\Q$package\E_0\&/) {
 9444: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
 9445: 			    # ignore package.tab specified default values
 9446:                             # here &package_tab_default() will fetch those
 9447: 			    if ($subp eq 'default') { next; }
 9448: 			    my $value=$packagetab{$pack_entry};
 9449: 			    my $unikey;
 9450: 			    if ($pack =~ /_0$/) {
 9451: 				$unikey='parameter_0_'.$name;
 9452: 				$part=0;
 9453: 			    } else {
 9454: 				$unikey='parameter'.$keyroot.'_'.$name;
 9455: 			    }
 9456: 			    if ($subp eq 'display') {
 9457: 				$value.=' [Part: '.$part.']';
 9458: 			    }
 9459: 			    $metaentry{':'.$unikey.'.part'}=$part;
 9460: 			    $metathesekeys{$unikey}=1;
 9461: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 9462: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
 9463: 			    }
 9464: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
 9465: 				$metaentry{':'.$unikey}=
 9466: 				    $metaentry{':'.$unikey.'.default'};
 9467: 			    }
 9468: 			}
 9469: 		    }
 9470: 		} else {
 9471: #
 9472: # This is not a package - some other kind of start tag
 9473: #
 9474: 		    my $entry=$token->[1];
 9475: 		    my $unikey='';
 9476: 
 9477: 		    if ($entry eq 'import') {
 9478: #
 9479: # Importing a library here
 9480: #
 9481:                         my $location=$parser->get_text('/import');
 9482:                         my $dir=$filename;
 9483:                         $dir=~s|[^/]*$||;
 9484:                         $location=&filelocation($dir,$location);
 9485:                        
 9486:                         my $importmode=$token->[2]->{'importmode'};
 9487:                         if ($importmode eq 'problem') {
 9488: # Import as problem/response
 9489:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 9490:                         } elsif ($importmode eq 'part') {
 9491: # Import as part(s)
 9492:                            $importedparts=1;
 9493: # We need to get the original file and the imported file to get the part order correct
 9494: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
 9495: # Load and inspect original file
 9496:                            if ($#origfileimportpartids<0) {
 9497:                               undef(%importedpartids);
 9498:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
 9499:                               my $origfile=&getfile($origfilelocation);
 9500:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
 9501:                            }
 9502: 
 9503: # Load and inspect imported file
 9504:                            my $impfile=&getfile($location);
 9505:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
 9506:                            if ($#impfilepartids>=0) {
 9507: # This problem had parts
 9508:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
 9509:                            } else {
 9510: # Importing by turning a single problem into a problem part
 9511: # It gets the import-tags ID as part-ID
 9512:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
 9513:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
 9514:                            }
 9515:                         } else {
 9516: # Normal import
 9517:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 9518:                            if (defined($token->[2]->{'id'})) {
 9519:                               $unikey.='_'.$token->[2]->{'id'};
 9520:                            }
 9521:                         }
 9522: 
 9523: 			if ($depthcount<20) {
 9524: 			    my $metadata = 
 9525: 				&metadata($uri,'keys', $location,$unikey,
 9526: 					  $depthcount+1);
 9527: 			    foreach my $meta (split(',',$metadata)) {
 9528: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
 9529: 				$metathesekeys{$meta}=1;
 9530: 			    }
 9531: 			
 9532:                         }
 9533: 		    } else {
 9534: #
 9535: # Not importing, some other kind of non-package, non-library start tag
 9536: # 
 9537:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
 9538:                         if (defined($token->[2]->{'id'})) {
 9539:                             $unikey.='_'.$token->[2]->{'id'};
 9540:                         }
 9541: 			if (defined($token->[2]->{'name'})) { 
 9542: 			    $unikey.='_'.$token->[2]->{'name'}; 
 9543: 			}
 9544: 			$metathesekeys{$unikey}=1;
 9545: 			foreach my $param (@{$token->[3]}) {
 9546: 			    $metaentry{':'.$unikey.'.'.$param} =
 9547: 				$token->[2]->{$param};
 9548: 			}
 9549: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
 9550: 			my $default=$metaentry{':'.$unikey.'.default'};
 9551: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
 9552: 		 # only ws inside the tag, and not in default, so use default
 9553: 		 # as value
 9554: 			    $metaentry{':'.$unikey}=$default;
 9555: 			} elsif ( $internaltext =~ /\S/ ) {
 9556: 		  # something interesting inside the tag
 9557: 			    $metaentry{':'.$unikey}=$internaltext;
 9558: 			} else {
 9559: 		  # no interesting values, don't set a default
 9560: 			}
 9561: # end of not-a-package not-a-library import
 9562: 		    }
 9563: # end of not-a-package start tag
 9564: 		}
 9565: # the next is the end of "start tag"
 9566: 	    }
 9567: 	}
 9568: 	my ($extension) = ($uri =~ /\.(\w+)$/);
 9569: 	$extension = lc($extension);
 9570: 	if ($extension eq 'htm') { $extension='html'; }
 9571: 
 9572: 	foreach my $key (keys(%packagetab)) {
 9573: 	    #no specific packages #how's our extension
 9574: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
 9575: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
 9576: 					 \%metathesekeys);
 9577: 	}
 9578: 
 9579: 	if (!exists($metaentry{':packages'})
 9580: 	    || $packagetab{"import_defaults&extension_$extension"}) {
 9581: 	    foreach my $key (keys(%packagetab)) {
 9582: 		#no specific packages well let's get default then
 9583: 		if ($key!~/^default&/) { next; }
 9584: 		&metadata_create_package_def($uri,$key,'default',
 9585: 					     \%metathesekeys);
 9586: 	    }
 9587: 	}
 9588: # are there custom rights to evaluate
 9589: 	if ($metaentry{':copyright'} eq 'custom') {
 9590: 
 9591:     #
 9592:     # Importing a rights file here
 9593:     #
 9594: 	    unless ($depthcount) {
 9595: 		my $location=$metaentry{':customdistributionfile'};
 9596: 		my $dir=$filename;
 9597: 		$dir=~s|[^/]*$||;
 9598: 		$location=&filelocation($dir,$location);
 9599: 		my $rights_metadata =
 9600: 		    &metadata($uri,'keys',$location,'_rights',
 9601: 			      $depthcount+1);
 9602: 		foreach my $rights (split(',',$rights_metadata)) {
 9603: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
 9604: 		    $metathesekeys{$rights}=1;
 9605: 		}
 9606: 	    }
 9607: 	}
 9608: 	# uniqifiy package listing
 9609: 	my %seen;
 9610: 	my @uniq_packages =
 9611: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
 9612: 	$metaentry{':packages'} = join(',',@uniq_packages);
 9613: 
 9614:         if ($importedparts) {
 9615: # We had imported parts and need to rebuild partorder
 9616:            $metaentry{':partorder'}='';
 9617:            $metathesekeys{'partorder'}=1;
 9618:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
 9619:                if ($origfileimportpartids[$index] eq 'part') {
 9620: # original part, part of the problem
 9621:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
 9622:                } else {
 9623: # we have imported parts at this position
 9624:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
 9625:                }
 9626:            }
 9627:            $metaentry{':partorder'}=~s/^\,//;
 9628:         }
 9629: 
 9630: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
 9631: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
 9632: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
 9633: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
 9634: # this is the end of "was not already recently cached
 9635:     }
 9636:     return $metaentry{':'.$what};
 9637: }
 9638: 
 9639: sub metadata_create_package_def {
 9640:     my ($uri,$key,$package,$metathesekeys)=@_;
 9641:     my ($pack,$name,$subp)=split(/\&/,$key);
 9642:     if ($subp eq 'default') { next; }
 9643:     
 9644:     if (defined($metaentry{':packages'})) {
 9645: 	$metaentry{':packages'}.=','.$package;
 9646:     } else {
 9647: 	$metaentry{':packages'}=$package;
 9648:     }
 9649:     my $value=$packagetab{$key};
 9650:     my $unikey;
 9651:     $unikey='parameter_0_'.$name;
 9652:     $metaentry{':'.$unikey.'.part'}=0;
 9653:     $$metathesekeys{$unikey}=1;
 9654:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 9655: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
 9656:     }
 9657:     if (defined($metaentry{':'.$unikey.'.default'})) {
 9658: 	$metaentry{':'.$unikey}=
 9659: 	    $metaentry{':'.$unikey.'.default'};
 9660:     }
 9661: }
 9662: 
 9663: sub metadata_generate_part0 {
 9664:     my ($metadata,$metacache,$uri) = @_;
 9665:     my %allnames;
 9666:     foreach my $metakey (keys(%$metadata)) {
 9667: 	if ($metakey=~/^parameter\_(.*)/) {
 9668: 	  my $part=$$metacache{':'.$metakey.'.part'};
 9669: 	  my $name=$$metacache{':'.$metakey.'.name'};
 9670: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
 9671: 	    $allnames{$name}=$part;
 9672: 	  }
 9673: 	}
 9674:     }
 9675:     foreach my $name (keys(%allnames)) {
 9676:       $$metadata{"parameter_0_$name"}=1;
 9677:       my $key=":parameter_0_$name";
 9678:       $$metacache{"$key.part"}='0';
 9679:       $$metacache{"$key.name"}=$name;
 9680:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
 9681: 					   $allnames{$name}.'_'.$name.
 9682: 					   '.type'};
 9683:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
 9684: 			     '.display'};
 9685:       my $expr='[Part: '.$allnames{$name}.']';
 9686:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
 9687:       $$metacache{"$key.display"}=$olddis;
 9688:     }
 9689: }
 9690: 
 9691: # ------------------------------------------------------ Devalidate title cache
 9692: 
 9693: sub devalidate_title_cache {
 9694:     my ($url)=@_;
 9695:     if (!$env{'request.course.id'}) { return; }
 9696:     my $symb=&symbread($url);
 9697:     if (!$symb) { return; }
 9698:     my $key=$env{'request.course.id'}."\0".$symb;
 9699:     &devalidate_cache_new('title',$key);
 9700: }
 9701: 
 9702: # ------------------------------------------------- Get the title of a course
 9703: 
 9704: sub current_course_title {
 9705:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
 9706: }
 9707: # ------------------------------------------------- Get the title of a resource
 9708: 
 9709: sub gettitle {
 9710:     my $urlsymb=shift;
 9711:     my $symb=&symbread($urlsymb);
 9712:     if ($symb) {
 9713: 	my $key=$env{'request.course.id'}."\0".$symb;
 9714: 	my ($result,$cached)=&is_cached_new('title',$key);
 9715: 	if (defined($cached)) { 
 9716: 	    return $result;
 9717: 	}
 9718: 	my ($map,$resid,$url)=&decode_symb($symb);
 9719: 	my $title='';
 9720: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
 9721: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
 9722: 	} else {
 9723: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9724: 		    &GDBM_READER(),0640)) {
 9725: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
 9726: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
 9727: 		untie(%bighash);
 9728: 	    }
 9729: 	}
 9730: 	$title=~s/\&colon\;/\:/gs;
 9731: 	if ($title) {
 9732: # Remember both $symb and $title for dynamic metadata
 9733:             $accesshash{$symb.'___crstitle'}=$title;
 9734:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
 9735: # Cache this title and then return it
 9736: 	    return &do_cache_new('title',$key,$title,600);
 9737: 	}
 9738: 	$urlsymb=$url;
 9739:     }
 9740:     my $title=&metadata($urlsymb,'title');
 9741:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
 9742:     return $title;
 9743: }
 9744: 
 9745: sub get_slot {
 9746:     my ($which,$cnum,$cdom)=@_;
 9747:     if (!$cnum || !$cdom) {
 9748: 	(undef,my $courseid)=&whichuser();
 9749: 	$cdom=$env{'course.'.$courseid.'.domain'};
 9750: 	$cnum=$env{'course.'.$courseid.'.num'};
 9751:     }
 9752:     my $key=join("\0",'slots',$cdom,$cnum,$which);
 9753:     my %slotinfo;
 9754:     if (exists($remembered{$key})) {
 9755: 	$slotinfo{$which} = $remembered{$key};
 9756:     } else {
 9757: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
 9758: 	&Apache::lonhomework::showhash(%slotinfo);
 9759: 	my ($tmp)=keys(%slotinfo);
 9760: 	if ($tmp=~/^error:/) { return (); }
 9761: 	$remembered{$key} = $slotinfo{$which};
 9762:     }
 9763:     if (ref($slotinfo{$which}) eq 'HASH') {
 9764: 	return %{$slotinfo{$which}};
 9765:     }
 9766:     return $slotinfo{$which};
 9767: }
 9768: 
 9769: sub get_reservable_slots {
 9770:     my ($cnum,$cdom,$uname,$udom) = @_;
 9771:     my $now = time;
 9772:     my $reservable_info;
 9773:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
 9774:     if (exists($remembered{$key})) {
 9775:         $reservable_info = $remembered{$key};
 9776:     } else {
 9777:         my %resv;
 9778:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
 9779:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
 9780:         $reservable_info = \%resv;
 9781:         $remembered{$key} = $reservable_info;
 9782:     }
 9783:     return $reservable_info;
 9784: }
 9785: 
 9786: sub get_course_slots {
 9787:     my ($cnum,$cdom) = @_;
 9788:     my $hashid=$cnum.':'.$cdom;
 9789:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
 9790:     if (defined($cached)) {
 9791:         if (ref($result) eq 'HASH') {
 9792:             return %{$result};
 9793:         }
 9794:     } else {
 9795:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
 9796:         my ($tmp) = keys(%slots);
 9797:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 9798:             &Apache::lonnet::do_cache_new('allslots',$hashid,\%slots,600);
 9799:             return %slots;
 9800:         }
 9801:     }
 9802:     return;
 9803: }
 9804: 
 9805: sub devalidate_slots_cache {
 9806:     my ($cnum,$cdom)=@_;
 9807:     my $hashid=$cnum.':'.$cdom;
 9808:     &devalidate_cache_new('allslots',$hashid);
 9809: }
 9810: 
 9811: # ------------------------------------------------- Update symbolic store links
 9812: 
 9813: sub symblist {
 9814:     my ($mapname,%newhash)=@_;
 9815:     $mapname=&deversion(&declutter($mapname));
 9816:     my %hash;
 9817:     if (($env{'request.course.fn'}) && (%newhash)) {
 9818:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 9819:                       &GDBM_WRCREAT(),0640)) {
 9820: 	    foreach my $url (keys(%newhash)) {
 9821: 		next if ($url eq 'last_known'
 9822: 			 && $env{'form.no_update_last_known'});
 9823: 		$hash{declutter($url)}=&encode_symb($mapname,
 9824: 						    $newhash{$url}->[1],
 9825: 						    $newhash{$url}->[0]);
 9826:             }
 9827:             if (untie(%hash)) {
 9828: 		return 'ok';
 9829:             }
 9830:         }
 9831:     }
 9832:     return 'error';
 9833: }
 9834: 
 9835: # --------------------------------------------------------------- Verify a symb
 9836: 
 9837: sub symbverify {
 9838:     my ($symb,$thisurl)=@_;
 9839:     my $thisfn=$thisurl;
 9840:     $thisfn=&declutter($thisfn);
 9841: # direct jump to resource in page or to a sequence - will construct own symbs
 9842:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
 9843: # check URL part
 9844:     my ($map,$resid,$url)=&decode_symb($symb);
 9845: 
 9846:     unless ($url eq $thisfn) { return 0; }
 9847: 
 9848:     $symb=&symbclean($symb);
 9849:     $thisurl=&deversion($thisurl);
 9850:     $thisfn=&deversion($thisfn);
 9851: 
 9852:     my %bighash;
 9853:     my $okay=0;
 9854: 
 9855:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9856:                             &GDBM_READER(),0640)) {
 9857:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
 9858:             $thisurl =~ s/\?.+$//;
 9859:         }
 9860:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
 9861:         unless ($ids) {
 9862:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
 9863:             $ids=$bighash{$idkey};
 9864:         }
 9865:         if ($ids) {
 9866: # ------------------------------------------------------------------- Has ID(s)
 9867: 	    foreach my $id (split(/\,/,$ids)) {
 9868: 	       my ($mapid,$resid)=split(/\./,$id);
 9869:                if ($thisfn =~ m{^/adm/wrapper/ext/}) {
 9870:                    $symb =~ s/\?.+$//;
 9871:                }
 9872:                if (
 9873:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
 9874:    eq $symb) { 
 9875: 		   if (($env{'request.role.adv'}) ||
 9876: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
 9877:                        ($thisurl eq '/adm/navmaps')) {
 9878: 		       $okay=1; 
 9879: 		   }
 9880: 	       }
 9881: 	   }
 9882:         }
 9883: 	untie(%bighash);
 9884:     }
 9885:     return $okay;
 9886: }
 9887: 
 9888: # --------------------------------------------------------------- Clean-up symb
 9889: 
 9890: sub symbclean {
 9891:     my $symb=shift;
 9892:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 9893: # remove version from map
 9894:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
 9895: 
 9896: # remove version from URL
 9897:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
 9898: 
 9899: # remove wrapper
 9900: 
 9901:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
 9902:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
 9903:     return $symb;
 9904: }
 9905: 
 9906: # ---------------------------------------------- Split symb to find map and url
 9907: 
 9908: sub encode_symb {
 9909:     my ($map,$resid,$url)=@_;
 9910:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
 9911: }
 9912: 
 9913: sub decode_symb {
 9914:     my $symb=shift;
 9915:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 9916:     my ($map,$resid,$url)=split(/___/,$symb);
 9917:     return (&fixversion($map),$resid,&fixversion($url));
 9918: }
 9919: 
 9920: sub fixversion {
 9921:     my $fn=shift;
 9922:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
 9923:     my %bighash;
 9924:     my $uri=&clutter($fn);
 9925:     my $key=$env{'request.course.id'}.'_'.$uri;
 9926: # is this cached?
 9927:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
 9928:     if (defined($cached)) { return $result; }
 9929: # unfortunately not cached, or expired
 9930:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9931: 	    &GDBM_READER(),0640)) {
 9932:  	if ($bighash{'version_'.$uri}) {
 9933:  	    my $version=$bighash{'version_'.$uri};
 9934:  	    unless (($version eq 'mostrecent') || 
 9935: 		    ($version==&getversion($uri))) {
 9936:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
 9937:  	    }
 9938:  	}
 9939:  	untie %bighash;
 9940:     }
 9941:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
 9942: }
 9943: 
 9944: sub deversion {
 9945:     my $url=shift;
 9946:     $url=~s/\.\d+\.(\w+)$/\.$1/;
 9947:     return $url;
 9948: }
 9949: 
 9950: # ------------------------------------------------------ Return symb list entry
 9951: 
 9952: sub symbread {
 9953:     my ($thisfn,$donotrecurse)=@_;
 9954:     my $cache_str='request.symbread.cached.'.$thisfn;
 9955:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
 9956: # no filename provided? try from environment
 9957:     unless ($thisfn) {
 9958:         if ($env{'request.symb'}) {
 9959: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
 9960: 	}
 9961: 	$thisfn=$env{'request.filename'};
 9962:     }
 9963:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 9964: # is that filename actually a symb? Verify, clean, and return
 9965:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
 9966: 	if (&symbverify($thisfn,$1)) {
 9967: 	    return $env{$cache_str}=&symbclean($thisfn);
 9968: 	}
 9969:     }
 9970:     $thisfn=declutter($thisfn);
 9971:     my %hash;
 9972:     my %bighash;
 9973:     my $syval='';
 9974:     if (($env{'request.course.fn'}) && ($thisfn)) {
 9975:         my $targetfn = $thisfn;
 9976:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
 9977:             $targetfn = 'adm/wrapper/'.$thisfn;
 9978:         }
 9979: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
 9980: 	    $targetfn=$1;
 9981: 	}
 9982:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 9983:                       &GDBM_READER(),0640)) {
 9984: 	    $syval=$hash{$targetfn};
 9985:             untie(%hash);
 9986:         }
 9987: # ---------------------------------------------------------- There was an entry
 9988:         if ($syval) {
 9989: 	    #unless ($syval=~/\_\d+$/) {
 9990: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
 9991: 		    #&appenv({'request.ambiguous' => $thisfn});
 9992: 		    #return $env{$cache_str}='';
 9993: 		#}    
 9994: 		#$syval.=$1;
 9995: 	    #}
 9996:         } else {
 9997: # ------------------------------------------------------- Was not in symb table
 9998:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9999:                             &GDBM_READER(),0640)) {
10000: # ---------------------------------------------- Get ID(s) for current resource
10001:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
10002:               unless ($ids) { 
10003:                  $ids=$bighash{'ids_/'.$thisfn};
10004:               }
10005:               unless ($ids) {
10006: # alias?
10007: 		  $ids=$bighash{'mapalias_'.$thisfn};
10008:               }
10009:               if ($ids) {
10010: # ------------------------------------------------------------------- Has ID(s)
10011:                  my @possibilities=split(/\,/,$ids);
10012:                  if ($#possibilities==0) {
10013: # ----------------------------------------------- There is only one possibility
10014: 		     my ($mapid,$resid)=split(/\./,$ids);
10015: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
10016: 						    $resid,$thisfn);
10017:                  } elsif (!$donotrecurse) {
10018: # ------------------------------------------ There is more than one possibility
10019:                      my $realpossible=0;
10020:                      foreach my $id (@possibilities) {
10021: 			 my $file=$bighash{'src_'.$id};
10022:                          if (&allowed('bre',$file)) {
10023:          		    my ($mapid,$resid)=split(/\./,$id);
10024:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
10025: 				$realpossible++;
10026:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
10027: 						    $resid,$thisfn);
10028:                             }
10029: 			 }
10030:                      }
10031: 		     if ($realpossible!=1) { $syval=''; }
10032:                  } else {
10033:                      $syval='';
10034:                  }
10035: 	      }
10036:               untie(%bighash)
10037:            }
10038:         }
10039:         if ($syval) {
10040: 	    return $env{$cache_str}=$syval;
10041:         }
10042:     }
10043:     &appenv({'request.ambiguous' => $thisfn});
10044:     return $env{$cache_str}='';
10045: }
10046: 
10047: # ---------------------------------------------------------- Return random seed
10048: 
10049: sub numval {
10050:     my $txt=shift;
10051:     $txt=~tr/A-J/0-9/;
10052:     $txt=~tr/a-j/0-9/;
10053:     $txt=~tr/K-T/0-9/;
10054:     $txt=~tr/k-t/0-9/;
10055:     $txt=~tr/U-Z/0-5/;
10056:     $txt=~tr/u-z/0-5/;
10057:     $txt=~s/\D//g;
10058:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
10059:     return int($txt);
10060: }
10061: 
10062: sub numval2 {
10063:     my $txt=shift;
10064:     $txt=~tr/A-J/0-9/;
10065:     $txt=~tr/a-j/0-9/;
10066:     $txt=~tr/K-T/0-9/;
10067:     $txt=~tr/k-t/0-9/;
10068:     $txt=~tr/U-Z/0-5/;
10069:     $txt=~tr/u-z/0-5/;
10070:     $txt=~s/\D//g;
10071:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10072:     my $total;
10073:     foreach my $val (@txts) { $total+=$val; }
10074:     if ($_64bit) { if ($total > 2**32) { return -1; } }
10075:     return int($total);
10076: }
10077: 
10078: sub numval3 {
10079:     use integer;
10080:     my $txt=shift;
10081:     $txt=~tr/A-J/0-9/;
10082:     $txt=~tr/a-j/0-9/;
10083:     $txt=~tr/K-T/0-9/;
10084:     $txt=~tr/k-t/0-9/;
10085:     $txt=~tr/U-Z/0-5/;
10086:     $txt=~tr/u-z/0-5/;
10087:     $txt=~s/\D//g;
10088:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10089:     my $total;
10090:     foreach my $val (@txts) { $total+=$val; }
10091:     if ($_64bit) { $total=(($total<<32)>>32); }
10092:     return $total;
10093: }
10094: 
10095: sub digest {
10096:     my ($data)=@_;
10097:     my $digest=&Digest::MD5::md5($data);
10098:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
10099:     my ($e,$f);
10100:     {
10101:         use integer;
10102:         $e=($a+$b);
10103:         $f=($c+$d);
10104:         if ($_64bit) {
10105:             $e=(($e<<32)>>32);
10106:             $f=(($f<<32)>>32);
10107:         }
10108:     }
10109:     if (wantarray) {
10110: 	return ($e,$f);
10111:     } else {
10112: 	my $g;
10113: 	{
10114: 	    use integer;
10115: 	    $g=($e+$f);
10116: 	    if ($_64bit) {
10117: 		$g=(($g<<32)>>32);
10118: 	    }
10119: 	}
10120: 	return $g;
10121:     }
10122: }
10123: 
10124: sub latest_rnd_algorithm_id {
10125:     return '64bit5';
10126: }
10127: 
10128: sub get_rand_alg {
10129:     my ($courseid)=@_;
10130:     if (!$courseid) { $courseid=(&whichuser())[1]; }
10131:     if ($courseid) {
10132: 	return $env{"course.$courseid.rndseed"};
10133:     }
10134:     return &latest_rnd_algorithm_id();
10135: }
10136: 
10137: sub validCODE {
10138:     my ($CODE)=@_;
10139:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
10140:     return 0;
10141: }
10142: 
10143: sub getCODE {
10144:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
10145:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
10146: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
10147: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
10148: 	return $Apache::lonhomework::history{'resource.CODE'};
10149:     }
10150:     return undef;
10151: }
10152: #
10153: #  Determines the random seed for a specific context:
10154: #
10155: # parameters:
10156: #   symb      - in course context the symb for the seed.
10157: #   course_id - The course id of the form domain_coursenum.
10158: #   domain    - Domain for the user.
10159: #   course    - Course for the user.
10160: #   cenv      - environment of the course.
10161: #
10162: # NOTE:
10163: #   All parameters are picked out of the environment if missing
10164: #   or not defined.
10165: #   If a symb cannot be determined the current time is used instead.
10166: #
10167: #  For a given well defined symb, courside, domain, username,
10168: #  and course environment, the seed is reproducible.
10169: #
10170: sub rndseed {
10171:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
10172:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
10173:     if (!defined($symb)) {
10174: 	unless ($symb=$wsymb) { return time; }
10175:     }
10176:     if (!defined $courseid) { 
10177: 	$courseid=$wcourseid; 
10178:     }
10179:     if (!defined $domain) { $domain=$wdomain; }
10180:     if (!defined $username) { $username=$wusername }
10181: 
10182:     my $which;
10183:     if (defined($cenv->{'rndseed'})) {
10184: 	$which = $cenv->{'rndseed'};
10185:     } else {
10186: 	$which =&get_rand_alg($courseid);
10187:     }
10188:     if (defined(&getCODE())) {
10189: 
10190: 	if ($which eq '64bit5') {
10191: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
10192: 	} elsif ($which eq '64bit4') {
10193: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
10194: 	} else {
10195: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
10196: 	}
10197:     } elsif ($which eq '64bit5') {
10198: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
10199:     } elsif ($which eq '64bit4') {
10200: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
10201:     } elsif ($which eq '64bit3') {
10202: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
10203:     } elsif ($which eq '64bit2') {
10204: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
10205:     } elsif ($which eq '64bit') {
10206: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
10207:     }
10208:     return &rndseed_32bit($symb,$courseid,$domain,$username);
10209: }
10210: 
10211: sub rndseed_32bit {
10212:     my ($symb,$courseid,$domain,$username)=@_;
10213:     {
10214: 	use integer;
10215: 	my $symbchck=unpack("%32C*",$symb) << 27;
10216: 	my $symbseed=numval($symb) << 22;
10217: 	my $namechck=unpack("%32C*",$username) << 17;
10218: 	my $nameseed=numval($username) << 12;
10219: 	my $domainseed=unpack("%32C*",$domain) << 7;
10220: 	my $courseseed=unpack("%32C*",$courseid);
10221: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
10222: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10223: 	#&logthis("rndseed :$num:$symb");
10224: 	if ($_64bit) { $num=(($num<<32)>>32); }
10225: 	return $num;
10226:     }
10227: }
10228: 
10229: sub rndseed_64bit {
10230:     my ($symb,$courseid,$domain,$username)=@_;
10231:     {
10232: 	use integer;
10233: 	my $symbchck=unpack("%32S*",$symb) << 21;
10234: 	my $symbseed=numval($symb) << 10;
10235: 	my $namechck=unpack("%32S*",$username);
10236: 	
10237: 	my $nameseed=numval($username) << 21;
10238: 	my $domainseed=unpack("%32S*",$domain) << 10;
10239: 	my $courseseed=unpack("%32S*",$courseid);
10240: 	
10241: 	my $num1=$symbchck+$symbseed+$namechck;
10242: 	my $num2=$nameseed+$domainseed+$courseseed;
10243: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10244: 	#&logthis("rndseed :$num:$symb");
10245: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10246: 	return "$num1,$num2";
10247:     }
10248: }
10249: 
10250: sub rndseed_64bit2 {
10251:     my ($symb,$courseid,$domain,$username)=@_;
10252:     {
10253: 	use integer;
10254: 	# strings need to be an even # of cahracters long, it it is odd the
10255:         # last characters gets thrown away
10256: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
10257: 	my $symbseed=numval($symb) << 10;
10258: 	my $namechck=unpack("%32S*",$username.' ');
10259: 	
10260: 	my $nameseed=numval($username) << 21;
10261: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
10262: 	my $courseseed=unpack("%32S*",$courseid.' ');
10263: 	
10264: 	my $num1=$symbchck+$symbseed+$namechck;
10265: 	my $num2=$nameseed+$domainseed+$courseseed;
10266: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10267: 	#&logthis("rndseed :$num:$symb");
10268: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10269: 	return "$num1,$num2";
10270:     }
10271: }
10272: 
10273: sub rndseed_64bit3 {
10274:     my ($symb,$courseid,$domain,$username)=@_;
10275:     {
10276: 	use integer;
10277: 	# strings need to be an even # of cahracters long, it it is odd the
10278:         # last characters gets thrown away
10279: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
10280: 	my $symbseed=numval2($symb) << 10;
10281: 	my $namechck=unpack("%32S*",$username.' ');
10282: 	
10283: 	my $nameseed=numval2($username) << 21;
10284: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
10285: 	my $courseseed=unpack("%32S*",$courseid.' ');
10286: 	
10287: 	my $num1=$symbchck+$symbseed+$namechck;
10288: 	my $num2=$nameseed+$domainseed+$courseseed;
10289: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10290: 	#&logthis("rndseed :$num1:$num2:$_64bit");
10291: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10292: 	
10293: 	return "$num1:$num2";
10294:     }
10295: }
10296: 
10297: sub rndseed_64bit4 {
10298:     my ($symb,$courseid,$domain,$username)=@_;
10299:     {
10300: 	use integer;
10301: 	# strings need to be an even # of cahracters long, it it is odd the
10302:         # last characters gets thrown away
10303: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
10304: 	my $symbseed=numval3($symb) << 10;
10305: 	my $namechck=unpack("%32S*",$username.' ');
10306: 	
10307: 	my $nameseed=numval3($username) << 21;
10308: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
10309: 	my $courseseed=unpack("%32S*",$courseid.' ');
10310: 	
10311: 	my $num1=$symbchck+$symbseed+$namechck;
10312: 	my $num2=$nameseed+$domainseed+$courseseed;
10313: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10314: 	#&logthis("rndseed :$num1:$num2:$_64bit");
10315: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10316: 	
10317: 	return "$num1:$num2";
10318:     }
10319: }
10320: 
10321: sub rndseed_64bit5 {
10322:     my ($symb,$courseid,$domain,$username)=@_;
10323:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
10324:     return "$num1:$num2";
10325: }
10326: 
10327: sub rndseed_CODE_64bit {
10328:     my ($symb,$courseid,$domain,$username)=@_;
10329:     {
10330: 	use integer;
10331: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
10332: 	my $symbseed=numval2($symb);
10333: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
10334: 	my $CODEseed=numval(&getCODE());
10335: 	my $courseseed=unpack("%32S*",$courseid.' ');
10336: 	my $num1=$symbseed+$CODEchck;
10337: 	my $num2=$CODEseed+$courseseed+$symbchck;
10338: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
10339: 	#&logthis("rndseed :$num1:$num2:$symb");
10340: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
10341: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
10342: 	return "$num1:$num2";
10343:     }
10344: }
10345: 
10346: sub rndseed_CODE_64bit4 {
10347:     my ($symb,$courseid,$domain,$username)=@_;
10348:     {
10349: 	use integer;
10350: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
10351: 	my $symbseed=numval3($symb);
10352: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
10353: 	my $CODEseed=numval3(&getCODE());
10354: 	my $courseseed=unpack("%32S*",$courseid.' ');
10355: 	my $num1=$symbseed+$CODEchck;
10356: 	my $num2=$CODEseed+$courseseed+$symbchck;
10357: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
10358: 	#&logthis("rndseed :$num1:$num2:$symb");
10359: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
10360: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
10361: 	return "$num1:$num2";
10362:     }
10363: }
10364: 
10365: sub rndseed_CODE_64bit5 {
10366:     my ($symb,$courseid,$domain,$username)=@_;
10367:     my $code = &getCODE();
10368:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
10369:     return "$num1:$num2";
10370: }
10371: 
10372: sub setup_random_from_rndseed {
10373:     my ($rndseed)=@_;
10374:     if ($rndseed =~/([,:])/) {
10375: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
10376: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
10377:     } else {
10378: 	&Math::Random::random_set_seed_from_phrase($rndseed);
10379:     }
10380: }
10381: 
10382: sub latest_receipt_algorithm_id {
10383:     return 'receipt3';
10384: }
10385: 
10386: sub recunique {
10387:     my $fucourseid=shift;
10388:     my $unique;
10389:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
10390: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
10391: 	$unique=$env{"course.$fucourseid.internal.encseed"};
10392:     } else {
10393: 	$unique=$perlvar{'lonReceipt'};
10394:     }
10395:     return unpack("%32C*",$unique);
10396: }
10397: 
10398: sub recprefix {
10399:     my $fucourseid=shift;
10400:     my $prefix;
10401:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
10402: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
10403: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
10404:     } else {
10405: 	$prefix=$perlvar{'lonHostID'};
10406:     }
10407:     return unpack("%32C*",$prefix);
10408: }
10409: 
10410: sub ireceipt {
10411:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
10412: 
10413:     my $return =&recprefix($fucourseid).'-';
10414: 
10415:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
10416: 	$env{'request.state'} eq 'construct') {
10417: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
10418: 	return $return;
10419:     }
10420: 
10421:     my $cuname=unpack("%32C*",$funame);
10422:     my $cudom=unpack("%32C*",$fudom);
10423:     my $cucourseid=unpack("%32C*",$fucourseid);
10424:     my $cusymb=unpack("%32C*",$fusymb);
10425:     my $cunique=&recunique($fucourseid);
10426:     my $cpart=unpack("%32S*",$part);
10427:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
10428: 
10429: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
10430: 			       
10431: 	$return.= ($cunique%$cuname+
10432: 		   $cunique%$cudom+
10433: 		   $cusymb%$cuname+
10434: 		   $cusymb%$cudom+
10435: 		   $cucourseid%$cuname+
10436: 		   $cucourseid%$cudom+
10437: 		   $cpart%$cuname+
10438: 		   $cpart%$cudom);
10439:     } else {
10440: 	$return.= ($cunique%$cuname+
10441: 		   $cunique%$cudom+
10442: 		   $cusymb%$cuname+
10443: 		   $cusymb%$cudom+
10444: 		   $cucourseid%$cuname+
10445: 		   $cucourseid%$cudom);
10446:     }
10447:     return $return;
10448: }
10449: 
10450: sub receipt {
10451:     my ($part)=@_;
10452:     my ($symb,$courseid,$domain,$name) = &whichuser();
10453:     return &ireceipt($name,$domain,$courseid,$symb,$part);
10454: }
10455: 
10456: sub whichuser {
10457:     my ($passedsymb)=@_;
10458:     my ($symb,$courseid,$domain,$name,$publicuser);
10459:     if (defined($env{'form.grade_symb'})) {
10460: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
10461: 	my $allowed=&allowed('vgr',$tmp_courseid);
10462: 	if (!$allowed &&
10463: 	    exists($env{'request.course.sec'}) &&
10464: 	    $env{'request.course.sec'} !~ /^\s*$/) {
10465: 	    $allowed=&allowed('vgr',$tmp_courseid.
10466: 			      '/'.$env{'request.course.sec'});
10467: 	}
10468: 	if ($allowed) {
10469: 	    ($symb)=&get_env_multiple('form.grade_symb');
10470: 	    $courseid=$tmp_courseid;
10471: 	    ($domain)=&get_env_multiple('form.grade_domain');
10472: 	    ($name)=&get_env_multiple('form.grade_username');
10473: 	    return ($symb,$courseid,$domain,$name,$publicuser);
10474: 	}
10475:     }
10476:     if (!$passedsymb) {
10477: 	$symb=&symbread();
10478:     } else {
10479: 	$symb=$passedsymb;
10480:     }
10481:     $courseid=$env{'request.course.id'};
10482:     $domain=$env{'user.domain'};
10483:     $name=$env{'user.name'};
10484:     if ($name eq 'public' && $domain eq 'public') {
10485: 	if (!defined($env{'form.username'})) {
10486: 	    $env{'form.username'}.=time.rand(10000000);
10487: 	}
10488: 	$name.=$env{'form.username'};
10489:     }
10490:     return ($symb,$courseid,$domain,$name,$publicuser);
10491: 
10492: }
10493: 
10494: # ------------------------------------------------------------ Serves up a file
10495: # returns either the contents of the file or 
10496: # -1 if the file doesn't exist
10497: #
10498: # if the target is a file that was uploaded via DOCS, 
10499: # a check will be made to see if a current copy exists on the local server,
10500: # if it does this will be served, otherwise a copy will be retrieved from
10501: # the home server for the course and stored in /home/httpd/html/userfiles on
10502: # the local server.   
10503: 
10504: sub getfile {
10505:     my ($file) = @_;
10506:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
10507:     &repcopy($file);
10508:     return &readfile($file);
10509: }
10510: 
10511: sub repcopy_userfile {
10512:     my ($file)=@_;
10513:     my $londocroot = $perlvar{'lonDocRoot'};
10514:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
10515:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
10516:     my ($cdom,$cnum,$filename) = 
10517: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
10518:     my $uri="/uploaded/$cdom/$cnum/$filename";
10519:     if (-e "$file") {
10520: # we already have a local copy, check it out
10521: 	my @fileinfo = stat($file);
10522: 	my $rtncode;
10523: 	my $info;
10524: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
10525: 	if ($lwpresp ne 'ok') {
10526: # there is no such file anymore, even though we had a local copy
10527: 	    if ($rtncode eq '404') {
10528: 		unlink($file);
10529: 	    }
10530: 	    return -1;
10531: 	}
10532: 	if ($info < $fileinfo[9]) {
10533: # nice, the file we have is up-to-date, just say okay
10534: 	    return 'ok';
10535: 	} else {
10536: # the file is outdated, get rid of it
10537: 	    unlink($file);
10538: 	}
10539:     }
10540: # one way or the other, at this point, we don't have the file
10541: # construct the correct path for the file
10542:     my @parts = ($cdom,$cnum); 
10543:     if ($filename =~ m|^(.+)/[^/]+$|) {
10544: 	push @parts, split(/\//,$1);
10545:     }
10546:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
10547:     foreach my $part (@parts) {
10548: 	$path .= '/'.$part;
10549: 	if (!-e $path) {
10550: 	    mkdir($path,0770);
10551: 	}
10552:     }
10553: # now the path exists for sure
10554: # get a user agent
10555:     my $ua=new LWP::UserAgent;
10556:     my $transferfile=$file.'.in.transfer';
10557: # FIXME: this should flock
10558:     if (-e $transferfile) { return 'ok'; }
10559:     my $request;
10560:     $uri=~s/^\///;
10561:     my $homeserver = &homeserver($cnum,$cdom);
10562:     my $protocol = $protocol{$homeserver};
10563:     $protocol = 'http' if ($protocol ne 'https');
10564:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
10565:     my $response=$ua->request($request,$transferfile);
10566: # did it work?
10567:     if ($response->is_error()) {
10568: 	unlink($transferfile);
10569: 	&logthis("Userfile repcopy failed for $uri");
10570: 	return -1;
10571:     }
10572: # worked, rename the transfer file
10573:     rename($transferfile,$file);
10574:     return 'ok';
10575: }
10576: 
10577: sub tokenwrapper {
10578:     my $uri=shift;
10579:     $uri=~s|^https?\://([^/]+)||;
10580:     $uri=~s|^/||;
10581:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
10582:     my $token=$1;
10583:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
10584:     if ($udom && $uname && $file) {
10585: 	$file=~s|(\?\.*)*$||;
10586:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
10587:         my $homeserver = &homeserver($uname,$udom);
10588:         my $protocol = $protocol{$homeserver};
10589:         $protocol = 'http' if ($protocol ne 'https');
10590:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
10591:                (($uri=~/\?/)?'&':'?').'token='.$token.
10592:                                '&tokenissued='.$perlvar{'lonHostID'};
10593:     } else {
10594:         return '/adm/notfound.html';
10595:     }
10596: }
10597: 
10598: # call with reqtype HEAD: get last modification time
10599: # call with reqtype GET: get the file contents
10600: # Do not call this with reqtype GET for large files! It loads everything into memory
10601: #
10602: sub getuploaded {
10603:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
10604:     $uri=~s/^\///;
10605:     my $homeserver = &homeserver($cnum,$cdom);
10606:     my $protocol = $protocol{$homeserver};
10607:     $protocol = 'http' if ($protocol ne 'https');
10608:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
10609:     my $ua=new LWP::UserAgent;
10610:     my $request=new HTTP::Request($reqtype,$uri);
10611:     my $response=$ua->request($request);
10612:     $$rtncode = $response->code;
10613:     if (! $response->is_success()) {
10614: 	return 'failed';
10615:     }      
10616:     if ($reqtype eq 'HEAD') {
10617: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
10618:     } elsif ($reqtype eq 'GET') {
10619: 	$$info = $response->content;
10620:     }
10621:     return 'ok';
10622: }
10623: 
10624: sub readfile {
10625:     my $file = shift;
10626:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
10627:     my $fh;
10628:     open($fh,"<$file");
10629:     my $a='';
10630:     while (my $line = <$fh>) { $a .= $line; }
10631:     return $a;
10632: }
10633: 
10634: sub filelocation {
10635:     my ($dir,$file) = @_;
10636:     my $location;
10637:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
10638: 
10639:     if ($file =~ m-^/adm/-) {
10640: 	$file=~s-^/adm/wrapper/-/-;
10641: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
10642:     }
10643: 
10644:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
10645:         $location = $file;
10646:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
10647:         my ($udom,$uname,$filename)=
10648:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
10649:         my $home=&homeserver($uname,$udom);
10650:         my $is_me=0;
10651:         my @ids=&current_machine_ids();
10652:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
10653:         if ($is_me) {
10654:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
10655:         } else {
10656:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
10657:   	      $udom.'/'.$uname.'/'.$filename;
10658:         }
10659:     } elsif ($file =~ m-^/adm/-) {
10660: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
10661:     } else {
10662:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
10663:         $file=~s:^/(res|priv)/:/:;
10664:         my $space=$1;
10665:         if ( !( $file =~ m:^/:) ) {
10666:             $location = $dir. '/'.$file;
10667:         } else {
10668:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
10669:         }
10670:     }
10671:     $location=~s://+:/:g; # remove duplicate /
10672:     while ($location=~m{/\.\./}) {
10673: 	if ($location =~ m{/[^/]+/\.\./}) {
10674: 	    $location=~ s{/[^/]+/\.\./}{/}g;
10675: 	} else {
10676: 	    $location=~ s{/\.\./}{/}g;
10677: 	}
10678:     } #remove dir/..
10679:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
10680:     return $location;
10681: }
10682: 
10683: sub hreflocation {
10684:     my ($dir,$file)=@_;
10685:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
10686: 	$file=filelocation($dir,$file);
10687:     } elsif ($file=~m-^/adm/-) {
10688: 	$file=~s-^/adm/wrapper/-/-;
10689: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
10690:     }
10691:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
10692: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
10693:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
10694: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
10695: 	        {/uploaded/$1/$2/}x;
10696:     }
10697:     if ($file=~ m{^/userfiles/}) {
10698: 	$file =~ s{^/userfiles/}{/uploaded/};
10699:     }
10700:     return $file;
10701: }
10702: 
10703: 
10704: 
10705: 
10706: 
10707: sub current_machine_domains {
10708:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
10709: }
10710: 
10711: sub machine_domains {
10712:     my ($hostname) = @_;
10713:     my @domains;
10714:     my %hostname = &all_hostnames();
10715:     while( my($id, $name) = each(%hostname)) {
10716: #	&logthis("-$id-$name-$hostname-");
10717: 	if ($hostname eq $name) {
10718: 	    push(@domains,&host_domain($id));
10719: 	}
10720:     }
10721:     return @domains;
10722: }
10723: 
10724: sub current_machine_ids {
10725:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
10726: }
10727: 
10728: sub machine_ids {
10729:     my ($hostname) = @_;
10730:     $hostname ||= &hostname($perlvar{'lonHostID'});
10731:     my @ids;
10732:     my %name_to_host = &all_names();
10733:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
10734: 	return @{ $name_to_host{$hostname} };
10735:     }
10736:     return;
10737: }
10738: 
10739: sub additional_machine_domains {
10740:     my @domains;
10741:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
10742:     while( my $line = <$fh>) {
10743:         $line =~ s/\s//g;
10744:         push(@domains,$line);
10745:     }
10746:     return @domains;
10747: }
10748: 
10749: sub default_login_domain {
10750:     my $domain = $perlvar{'lonDefDomain'};
10751:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
10752:     foreach my $posdom (&current_machine_domains(),
10753:                         &additional_machine_domains()) {
10754:         if (lc($posdom) eq lc($testdomain)) {
10755:             $domain=$posdom;
10756:             last;
10757:         }
10758:     }
10759:     return $domain;
10760: }
10761: 
10762: # ------------------------------------------------------------- Declutters URLs
10763: 
10764: sub declutter {
10765:     my $thisfn=shift;
10766:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
10767:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
10768:     $thisfn=~s/^\///;
10769:     $thisfn=~s|^adm/wrapper/||;
10770:     $thisfn=~s|^adm/coursedocs/showdoc/||;
10771:     $thisfn=~s/^res\///;
10772:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
10773:         $thisfn=~s/\?.+$//;
10774:     }
10775:     return $thisfn;
10776: }
10777: 
10778: # ------------------------------------------------------------- Clutter up URLs
10779: 
10780: sub clutter {
10781:     my $thisfn='/'.&declutter(shift);
10782:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
10783: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
10784:        $thisfn='/res'.$thisfn; 
10785:     }
10786:     if ($thisfn !~m|^/adm|) {
10787: 	if ($thisfn =~ m|^/ext/|) {
10788: 	    $thisfn='/adm/wrapper'.$thisfn;
10789: 	} else {
10790: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
10791: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
10792: 	    if ($embstyle eq 'ssi'
10793: 		|| ($embstyle eq 'hdn')
10794: 		|| ($embstyle eq 'rat')
10795: 		|| ($embstyle eq 'prv')
10796: 		|| ($embstyle eq 'ign')) {
10797: 		#do nothing with these
10798: 	    } elsif (($embstyle eq 'img') 
10799: 		|| ($embstyle eq 'emb')
10800: 		|| ($embstyle eq 'wrp')) {
10801: 		$thisfn='/adm/wrapper'.$thisfn;
10802: 	    } elsif ($embstyle eq 'unk'
10803: 		     && $thisfn!~/\.(sequence|page)$/) {
10804: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
10805: 	    } else {
10806: #		&logthis("Got a blank emb style");
10807: 	    }
10808: 	}
10809:     }
10810:     return $thisfn;
10811: }
10812: 
10813: sub clutter_with_no_wrapper {
10814:     my $uri = &clutter(shift);
10815:     if ($uri =~ m-^/adm/-) {
10816: 	$uri =~ s-^/adm/wrapper/-/-;
10817: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
10818:     }
10819:     return $uri;
10820: }
10821: 
10822: sub freeze_escape {
10823:     my ($value)=@_;
10824:     if (ref($value)) {
10825: 	$value=&nfreeze($value);
10826: 	return '__FROZEN__'.&escape($value);
10827:     }
10828:     return &escape($value);
10829: }
10830: 
10831: 
10832: sub thaw_unescape {
10833:     my ($value)=@_;
10834:     if ($value =~ /^__FROZEN__/) {
10835: 	substr($value,0,10,undef);
10836: 	$value=&unescape($value);
10837: 	return &thaw($value);
10838:     }
10839:     return &unescape($value);
10840: }
10841: 
10842: sub correct_line_ends {
10843:     my ($result)=@_;
10844:     $$result =~s/\r\n/\n/mg;
10845:     $$result =~s/\r/\n/mg;
10846: }
10847: # ================================================================ Main Program
10848: 
10849: sub goodbye {
10850:    &logthis("Starting Shut down");
10851: #not converted to using infrastruture and probably shouldn't be
10852:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
10853: #converted
10854: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
10855:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
10856: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
10857: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
10858: #1.1 only
10859: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
10860: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
10861: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
10862: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
10863:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
10864:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
10865:    &logthis(sprintf("%-20s is %s",'hits',$hits));
10866:    &flushcourselogs();
10867:    &logthis("Shutting down");
10868: }
10869: 
10870: sub get_dns {
10871:     my ($url,$func,$ignore_cache) = @_;
10872:     if (!$ignore_cache) {
10873: 	my ($content,$cached)=
10874: 	    &Apache::lonnet::is_cached_new('dns',$url);
10875: 	if ($cached) {
10876: 	    &$func($content);
10877: 	    return;
10878: 	}
10879:     }
10880: 
10881:     my %alldns;
10882:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
10883:     foreach my $dns (<$config>) {
10884: 	next if ($dns !~ /^\^(\S*)/x);
10885:         my $line = $1;
10886:         my ($host,$protocol) = split(/:/,$line);
10887:         if ($protocol ne 'https') {
10888:             $protocol = 'http';
10889:         }
10890: 	$alldns{$host} = $protocol;
10891:     }
10892:     while (%alldns) {
10893: 	my ($dns) = keys(%alldns);
10894: 	my $ua=new LWP::UserAgent;
10895:         $ua->timeout(30);
10896: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
10897: 	my $response=$ua->request($request);
10898:         delete($alldns{$dns});
10899: 	next if ($response->is_error());
10900: 	my @content = split("\n",$response->content);
10901: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
10902: 	&$func(\@content);
10903: 	return;
10904:     }
10905:     close($config);
10906:     my $which = (split('/',$url))[3];
10907:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
10908:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
10909:     my @content = <$config>;
10910:     &$func(\@content);
10911:     return;
10912: }
10913: # ------------------------------------------------------------ Read domain file
10914: {
10915:     my $loaded;
10916:     my %domain;
10917: 
10918:     sub parse_domain_tab {
10919: 	my ($lines) = @_;
10920: 	foreach my $line (@$lines) {
10921: 	    next if ($line =~ /^(\#|\s*$ )/x);
10922: 
10923: 	    chomp($line);
10924: 	    my ($name,@elements) = split(/:/,$line,9);
10925: 	    my %this_domain;
10926: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
10927: 			       'lang_def', 'city', 'longi', 'lati',
10928: 			       'primary') {
10929: 		$this_domain{$field} = shift(@elements);
10930: 	    }
10931: 	    $domain{$name} = \%this_domain;
10932: 	}
10933:     }
10934: 
10935:     sub reset_domain_info {
10936: 	undef($loaded);
10937: 	undef(%domain);
10938:     }
10939: 
10940:     sub load_domain_tab {
10941: 	my ($ignore_cache) = @_;
10942: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
10943: 	my $fh;
10944: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
10945: 	    my @lines = <$fh>;
10946: 	    &parse_domain_tab(\@lines);
10947: 	}
10948: 	close($fh);
10949: 	$loaded = 1;
10950:     }
10951: 
10952:     sub domain {
10953: 	&load_domain_tab() if (!$loaded);
10954: 
10955: 	my ($name,$what) = @_;
10956: 	return if ( !exists($domain{$name}) );
10957: 
10958: 	if (!$what) {
10959: 	    return $domain{$name}{'description'};
10960: 	}
10961: 	return $domain{$name}{$what};
10962:     }
10963: 
10964:     sub domain_info {
10965:         &load_domain_tab() if (!$loaded);
10966:         return %domain;
10967:     }
10968: 
10969: }
10970: 
10971: 
10972: # ------------------------------------------------------------- Read hosts file
10973: {
10974:     my %hostname;
10975:     my %hostdom;
10976:     my %libserv;
10977:     my $loaded;
10978:     my %name_to_host;
10979:     my %internetdom;
10980:     my %LC_dns_serv;
10981: 
10982:     sub parse_hosts_tab {
10983: 	my ($file) = @_;
10984: 	foreach my $configline (@$file) {
10985: 	    next if ($configline =~ /^(\#|\s*$ )/x);
10986:             chomp($configline);
10987: 	    if ($configline =~ /^\^/) {
10988:                 if ($configline =~ /^\^([\w.\-]+)/) {
10989:                     $LC_dns_serv{$1} = 1;
10990:                 }
10991:                 next;
10992:             }
10993: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
10994: 	    $name=~s/\s//g;
10995: 	    if ($id && $domain && $role && $name) {
10996: 		$hostname{$id}=$name;
10997: 		push(@{$name_to_host{$name}}, $id);
10998: 		$hostdom{$id}=$domain;
10999: 		if ($role eq 'library') { $libserv{$id}=$name; }
11000:                 if (defined($protocol)) {
11001:                     if ($protocol eq 'https') {
11002:                         $protocol{$id} = $protocol;
11003:                     } else {
11004:                         $protocol{$id} = 'http'; 
11005:                     }
11006:                 } else {
11007:                     $protocol{$id} = 'http';
11008:                 }
11009:                 if (defined($intdom)) {
11010:                     $internetdom{$id} = $intdom;
11011:                 }
11012: 	    }
11013: 	}
11014:     }
11015:     
11016:     sub reset_hosts_info {
11017: 	&purge_remembered();
11018: 	&reset_domain_info();
11019: 	&reset_hosts_ip_info();
11020: 	undef(%name_to_host);
11021: 	undef(%hostname);
11022: 	undef(%hostdom);
11023: 	undef(%libserv);
11024: 	undef($loaded);
11025:     }
11026: 
11027:     sub load_hosts_tab {
11028: 	my ($ignore_cache) = @_;
11029: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
11030: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11031: 	my @config = <$config>;
11032: 	&parse_hosts_tab(\@config);
11033: 	close($config);
11034: 	$loaded=1;
11035:     }
11036: 
11037:     sub hostname {
11038: 	&load_hosts_tab() if (!$loaded);
11039: 
11040: 	my ($lonid) = @_;
11041: 	return $hostname{$lonid};
11042:     }
11043: 
11044:     sub all_hostnames {
11045: 	&load_hosts_tab() if (!$loaded);
11046: 
11047: 	return %hostname;
11048:     }
11049: 
11050:     sub all_names {
11051: 	&load_hosts_tab() if (!$loaded);
11052: 
11053: 	return %name_to_host;
11054:     }
11055: 
11056:     sub all_host_domain {
11057:         &load_hosts_tab() if (!$loaded);
11058:         return %hostdom;
11059:     }
11060: 
11061:     sub is_library {
11062: 	&load_hosts_tab() if (!$loaded);
11063: 
11064: 	return exists($libserv{$_[0]});
11065:     }
11066: 
11067:     sub all_library {
11068: 	&load_hosts_tab() if (!$loaded);
11069: 
11070: 	return %libserv;
11071:     }
11072: 
11073:     sub unique_library {
11074: 	#2x reverse removes all hostnames that appear more than once
11075:         my %unique = reverse &all_library();
11076:         return reverse %unique;
11077:     }
11078: 
11079:     sub get_servers {
11080: 	&load_hosts_tab() if (!$loaded);
11081: 
11082: 	my ($domain,$type) = @_;
11083: 	my %possible_hosts = ($type eq 'library') ? %libserv
11084: 	                                          : %hostname;
11085: 	my %result;
11086: 	if (ref($domain) eq 'ARRAY') {
11087: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
11088: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
11089: 		    $result{$host} = $hostname;
11090: 		}
11091: 	    }
11092: 	} else {
11093: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
11094: 		if ($hostdom{$host} eq $domain) {
11095: 		    $result{$host} = $hostname;
11096: 		}
11097: 	    }
11098: 	}
11099: 	return %result;
11100:     }
11101: 
11102:     sub get_unique_servers {
11103:         my %unique = reverse &get_servers(@_);
11104: 	return reverse %unique;
11105:     }
11106: 
11107:     sub host_domain {
11108: 	&load_hosts_tab() if (!$loaded);
11109: 
11110: 	my ($lonid) = @_;
11111: 	return $hostdom{$lonid};
11112:     }
11113: 
11114:     sub all_domains {
11115: 	&load_hosts_tab() if (!$loaded);
11116: 
11117: 	my %seen;
11118: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
11119: 	return @uniq;
11120:     }
11121: 
11122:     sub internet_dom {
11123:         &load_hosts_tab() if (!$loaded);
11124: 
11125:         my ($lonid) = @_;
11126:         return $internetdom{$lonid};
11127:     }
11128: 
11129:     sub is_LC_dns {
11130:         &load_hosts_tab() if (!$loaded);
11131: 
11132:         my ($hostname) = @_;
11133:         return exists($LC_dns_serv{$hostname});
11134:     }
11135: 
11136: }
11137: 
11138: { 
11139:     my %iphost;
11140:     my %name_to_ip;
11141:     my %lonid_to_ip;
11142: 
11143:     sub get_hosts_from_ip {
11144: 	my ($ip) = @_;
11145: 	my %iphosts = &get_iphost();
11146: 	if (ref($iphosts{$ip})) {
11147: 	    return @{$iphosts{$ip}};
11148: 	}
11149: 	return;
11150:     }
11151:     
11152:     sub reset_hosts_ip_info {
11153: 	undef(%iphost);
11154: 	undef(%name_to_ip);
11155: 	undef(%lonid_to_ip);
11156:     }
11157: 
11158:     sub get_host_ip {
11159: 	my ($lonid) = @_;
11160: 	if (exists($lonid_to_ip{$lonid})) {
11161: 	    return $lonid_to_ip{$lonid};
11162: 	}
11163: 	my $name=&hostname($lonid);
11164:    	my $ip = gethostbyname($name);
11165: 	return if (!$ip || length($ip) ne 4);
11166: 	$ip=inet_ntoa($ip);
11167: 	$name_to_ip{$name}   = $ip;
11168: 	$lonid_to_ip{$lonid} = $ip;
11169: 	return $ip;
11170:     }
11171:     
11172:     sub get_iphost {
11173: 	my ($ignore_cache) = @_;
11174: 
11175: 	if (!$ignore_cache) {
11176: 	    if (%iphost) {
11177: 		return %iphost;
11178: 	    }
11179: 	    my ($ip_info,$cached)=
11180: 		&Apache::lonnet::is_cached_new('iphost','iphost');
11181: 	    if ($cached) {
11182: 		%iphost      = %{$ip_info->[0]};
11183: 		%name_to_ip  = %{$ip_info->[1]};
11184: 		%lonid_to_ip = %{$ip_info->[2]};
11185: 		return %iphost;
11186: 	    }
11187: 	}
11188: 
11189: 	# get yesterday's info for fallback
11190: 	my %old_name_to_ip;
11191: 	my ($ip_info,$cached)=
11192: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
11193: 	if ($cached) {
11194: 	    %old_name_to_ip = %{$ip_info->[1]};
11195: 	}
11196: 
11197: 	my %name_to_host = &all_names();
11198: 	foreach my $name (keys(%name_to_host)) {
11199: 	    my $ip;
11200: 	    if (!exists($name_to_ip{$name})) {
11201: 		$ip = gethostbyname($name);
11202: 		if (!$ip || length($ip) ne 4) {
11203: 		    if (defined($old_name_to_ip{$name})) {
11204: 			$ip = $old_name_to_ip{$name};
11205: 			&logthis("Can't find $name defaulting to old $ip");
11206: 		    } else {
11207: 			&logthis("Name $name no IP found");
11208: 			next;
11209: 		    }
11210: 		} else {
11211: 		    $ip=inet_ntoa($ip);
11212: 		}
11213: 		$name_to_ip{$name} = $ip;
11214: 	    } else {
11215: 		$ip = $name_to_ip{$name};
11216: 	    }
11217: 	    foreach my $id (@{ $name_to_host{$name} }) {
11218: 		$lonid_to_ip{$id} = $ip;
11219: 	    }
11220: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
11221: 	}
11222: 	&Apache::lonnet::do_cache_new('iphost','iphost',
11223: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
11224: 				      48*60*60);
11225: 
11226: 	return %iphost;
11227:     }
11228: 
11229:     #
11230:     #  Given a DNS returns the loncapa host name for that DNS 
11231:     # 
11232:     sub host_from_dns {
11233:         my ($dns) = @_;
11234:         my @hosts;
11235:         my $ip;
11236: 
11237:         if (exists($name_to_ip{$dns})) {
11238:             $ip = $name_to_ip{$dns};
11239:         }
11240:         if (!$ip) {
11241:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
11242:             if (length($ip) == 4) { 
11243: 	        $ip   = &IO::Socket::inet_ntoa($ip);
11244:             }
11245:         }
11246:         if ($ip) {
11247: 	    @hosts = get_hosts_from_ip($ip);
11248: 	    return $hosts[0];
11249:         }
11250:         return undef;
11251:     }
11252: 
11253:     sub get_internet_names {
11254:         my ($lonid) = @_;
11255:         return if ($lonid eq '');
11256:         my ($idnref,$cached)=
11257:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
11258:         if ($cached) {
11259:             return $idnref;
11260:         }
11261:         my $ip = &get_host_ip($lonid);
11262:         my @hosts = &get_hosts_from_ip($ip);
11263:         my %iphost = &get_iphost();
11264:         my (@idns,%seen);
11265:         foreach my $id (@hosts) {
11266:             my $dom = &host_domain($id);
11267:             my $prim_id = &domain($dom,'primary');
11268:             my $prim_ip = &get_host_ip($prim_id);
11269:             next if ($seen{$prim_ip});
11270:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
11271:                 foreach my $id (@{$iphost{$prim_ip}}) {
11272:                     my $intdom = &internet_dom($id);
11273:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
11274:                         push(@idns,$intdom);
11275:                     }
11276:                 }
11277:             }
11278:             $seen{$prim_ip} = 1;
11279:         }
11280:         return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
11281:     }
11282: 
11283: }
11284: 
11285: sub all_loncaparevs {
11286:     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);
11287: }
11288: 
11289: BEGIN {
11290: 
11291: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
11292:     unless ($readit) {
11293: {
11294:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
11295:     %perlvar = (%perlvar,%{$configvars});
11296: }
11297: 
11298: 
11299: # ------------------------------------------------------ Read spare server file
11300: {
11301:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
11302: 
11303:     while (my $configline=<$config>) {
11304:        chomp($configline);
11305:        if ($configline) {
11306: 	   my ($host,$type) = split(':',$configline,2);
11307: 	   if (!defined($type) || $type eq '') { $type = 'default' };
11308: 	   push(@{ $spareid{$type} }, $host);
11309:        }
11310:     }
11311:     close($config);
11312: }
11313: # ------------------------------------------------------------ Read permissions
11314: {
11315:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
11316: 
11317:     while (my $configline=<$config>) {
11318: 	chomp($configline);
11319: 	if ($configline) {
11320: 	    my ($role,$perm)=split(/ /,$configline);
11321: 	    if ($perm ne '') { $pr{$role}=$perm; }
11322: 	}
11323:     }
11324:     close($config);
11325: }
11326: 
11327: # -------------------------------------------- Read plain texts for permissions
11328: {
11329:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
11330: 
11331:     while (my $configline=<$config>) {
11332: 	chomp($configline);
11333: 	if ($configline) {
11334: 	    my ($short,@plain)=split(/:/,$configline);
11335:             %{$prp{$short}} = ();
11336: 	    if (@plain > 0) {
11337:                 $prp{$short}{'std'} = $plain[0];
11338:                 for (my $i=1; $i<@plain; $i++) {
11339:                     $prp{$short}{'alt'.$i} = $plain[$i];  
11340:                 }
11341:             }
11342: 	}
11343:     }
11344:     close($config);
11345: }
11346: 
11347: # ---------------------------------------------------------- Read package table
11348: {
11349:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
11350: 
11351:     while (my $configline=<$config>) {
11352: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
11353: 	chomp($configline);
11354: 	my ($short,$plain)=split(/:/,$configline);
11355: 	my ($pack,$name)=split(/\&/,$short);
11356: 	if ($plain ne '') {
11357: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
11358: 	    $packagetab{$short}=$plain; 
11359: 	}
11360:     }
11361:     close($config);
11362: }
11363: 
11364: # ---------------------------------------------------------- Read loncaparev table
11365: {
11366:     if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
11367:         if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
11368:             while (my $configline=<$config>) {
11369:                 chomp($configline);
11370:                 my ($hostid,$loncaparev)=split(/:/,$configline);
11371:                 $loncaparevs{$hostid}=$loncaparev;
11372:             }
11373:             close($config);
11374:         }
11375:     }
11376: }
11377: 
11378: # ---------------------------------------------------------- Read serverhostID table
11379: {
11380:     if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
11381:         if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
11382:             while (my $configline=<$config>) {
11383:                 chomp($configline);
11384:                 my ($name,$id)=split(/:/,$configline);
11385:                 $serverhomeIDs{$name}=$id;
11386:             }
11387:             close($config);
11388:         }
11389:     }
11390: }
11391: 
11392: {
11393:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
11394:     if (-e $file) {
11395:         my $parser = HTML::LCParser->new($file);
11396:         while (my $token = $parser->get_token()) {
11397:             if ($token->[0] eq 'S') {
11398:                 my $item = $token->[1];
11399:                 my $name = $token->[2]{'name'};
11400:                 my $value = $token->[2]{'value'};
11401:                 if ($item ne '' && $name ne '' && $value ne '') {
11402:                     my $release = $parser->get_text();
11403:                     $release =~ s/(^\s*|\s*$ )//gx;
11404:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
11405:                 }
11406:             }
11407:         }
11408:     }
11409: }
11410: 
11411: # ---------------------------------------------------------- Read managers table
11412: {
11413:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
11414:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
11415:             while (my $configline=<$config>) {
11416:                 chomp($configline);
11417:                 next if ($configline =~ /^\#/);
11418:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
11419:                     $managerstab{$configline} = 1;
11420:                 }
11421:             }
11422:             close($config);
11423:         }
11424:     }
11425: }
11426: 
11427: # ------------- set up temporary directory
11428: {
11429:     $tmpdir = LONCAPA::tempdir();
11430: 
11431: }
11432: 
11433: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
11434: 				'compress_threshold'=> 20_000,
11435:  			        });
11436: 
11437: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
11438: $dumpcount=0;
11439: $locknum=0;
11440: 
11441: &logtouch();
11442: &logthis('<font color="yellow">INFO: Read configuration</font>');
11443: $readit=1;
11444:     {
11445: 	use integer;
11446: 	my $test=(2**32)+1;
11447: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
11448: 	&logthis(" Detected 64bit platform ($_64bit)");
11449:     }
11450: }
11451: }
11452: 
11453: 1;
11454: __END__
11455: 
11456: =pod
11457: 
11458: =head1 NAME
11459: 
11460: Apache::lonnet - Subroutines to ask questions about things in the network.
11461: 
11462: =head1 SYNOPSIS
11463: 
11464: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
11465: 
11466:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
11467: 
11468: Common parameters:
11469: 
11470: =over 4
11471: 
11472: =item *
11473: 
11474: $uname : an internal username (if $cname expecting a course Id specifically)
11475: 
11476: =item *
11477: 
11478: $udom : a domain (if $cdom expecting a course's domain specifically)
11479: 
11480: =item *
11481: 
11482: $symb : a resource instance identifier
11483: 
11484: =item *
11485: 
11486: $namespace : the name of a .db file that contains the data needed or
11487: being set.
11488: 
11489: =back
11490: 
11491: =head1 OVERVIEW
11492: 
11493: lonnet provides subroutines which interact with the
11494: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
11495: about classes, users, and resources.
11496: 
11497: For many of these objects you can also use this to store data about
11498: them or modify them in various ways.
11499: 
11500: =head2 Symbs
11501: 
11502: To identify a specific instance of a resource, LON-CAPA uses symbols
11503: or "symbs"X<symb>. These identifiers are built from the URL of the
11504: map, the resource number of the resource in the map, and the URL of
11505: the resource itself. The latter is somewhat redundant, but might help
11506: if maps change.
11507: 
11508: An example is
11509: 
11510:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
11511: 
11512: The respective map entry is
11513: 
11514:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
11515:   title="Problem 2">
11516:  </resource>
11517: 
11518: Symbs are used by the random number generator, as well as to store and
11519: restore data specific to a certain instance of for example a problem.
11520: 
11521: =head2 Storing And Retrieving Data
11522: 
11523: X<store()>X<cstore()>X<restore()>Three of the most important functions
11524: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
11525: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
11526: is is the non-critical message twin of cstore. These functions are for
11527: handlers to store a perl hash to a user's permanent data space in an
11528: easy manner, and to retrieve it again on another call. It is expected
11529: that a handler would use this once at the beginning to retrieve data,
11530: and then again once at the end to send only the new data back.
11531: 
11532: The data is stored in the user's data directory on the user's
11533: homeserver under the ID of the course.
11534: 
11535: The hash that is returned by restore will have all of the previous
11536: value for all of the elements of the hash.
11537: 
11538: Example:
11539: 
11540:  #creating a hash
11541:  my %hash;
11542:  $hash{'foo'}='bar';
11543: 
11544:  #storing it
11545:  &Apache::lonnet::cstore(\%hash);
11546: 
11547:  #changing a value
11548:  $hash{'foo'}='notbar';
11549: 
11550:  #adding a new value
11551:  $hash{'bar'}='foo';
11552:  &Apache::lonnet::cstore(\%hash);
11553: 
11554:  #retrieving the hash
11555:  my %history=&Apache::lonnet::restore();
11556: 
11557:  #print the hash
11558:  foreach my $key (sort(keys(%history))) {
11559:    print("\%history{$key} = $history{$key}");
11560:  }
11561: 
11562: Will print out:
11563: 
11564:  %history{1:foo} = bar
11565:  %history{1:keys} = foo:timestamp
11566:  %history{1:timestamp} = 990455579
11567:  %history{2:bar} = foo
11568:  %history{2:foo} = notbar
11569:  %history{2:keys} = foo:bar:timestamp
11570:  %history{2:timestamp} = 990455580
11571:  %history{bar} = foo
11572:  %history{foo} = notbar
11573:  %history{timestamp} = 990455580
11574:  %history{version} = 2
11575: 
11576: Note that the special hash entries C<keys>, C<version> and
11577: C<timestamp> were added to the hash. C<version> will be equal to the
11578: total number of versions of the data that have been stored. The
11579: C<timestamp> attribute will be the UNIX time the hash was
11580: stored. C<keys> is available in every historical section to list which
11581: keys were added or changed at a specific historical revision of a
11582: hash.
11583: 
11584: B<Warning>: do not store the hash that restore returns directly. This
11585: will cause a mess since it will restore the historical keys as if the
11586: were new keys. I.E. 1:foo will become 1:1:foo etc.
11587: 
11588: Calling convention:
11589: 
11590:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
11591:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
11592: 
11593: For more detailed information, see lonnet specific documentation.
11594: 
11595: =head1 RETURN MESSAGES
11596: 
11597: =over 4
11598: 
11599: =item * B<con_lost>: unable to contact remote host
11600: 
11601: =item * B<con_delayed>: unable to contact remote host, message will be delivered
11602: when the connection is brought back up
11603: 
11604: =item * B<con_failed>: unable to contact remote host and unable to save message
11605: for later delivery
11606: 
11607: =item * B<error:>: an error a occurred, a description of the error follows the :
11608: 
11609: =item * B<no_such_host>: unable to fund a host associated with the user/domain
11610: that was requested
11611: 
11612: =back
11613: 
11614: =head1 PUBLIC SUBROUTINES
11615: 
11616: =head2 Session Environment Functions
11617: 
11618: =over 4
11619: 
11620: =item * 
11621: X<appenv()>
11622: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
11623: the user envirnoment file, and will be restored for each access this
11624: user makes during this session, also modifies the %env for the current
11625: process. Optional rolesarrayref - if defined contains a reference to an array
11626: of roles which are exempt from the restriction on modifying user.role entries 
11627: in the user's environment.db and in %env.    
11628: 
11629: =item *
11630: X<delenv()>
11631: B<delenv($delthis,$regexp)>: removes all items from the session
11632: environment file that begin with $delthis. If the 
11633: optional second arg - $regexp - is true, $delthis is treated as a 
11634: regular expression, otherwise \Q$delthis\E is used. 
11635: The values are also deleted from the current processes %env.
11636: 
11637: =item * get_env_multiple($name) 
11638: 
11639: gets $name from the %env hash, it seemlessly handles the cases where multiple
11640: values may be defined and end up as an array ref.
11641: 
11642: returns an array of values
11643: 
11644: =back
11645: 
11646: =head2 User Information
11647: 
11648: =over 4
11649: 
11650: =item *
11651: X<queryauthenticate()>
11652: B<queryauthenticate($uname,$udom)>: try to determine user's current 
11653: authentication scheme
11654: 
11655: =item *
11656: X<authenticate()>
11657: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
11658: authenticate user from domain's lib servers (first use the current
11659: one). C<$upass> should be the users password.
11660: $checkdefauth is optional (value is 1 if a check should be made to
11661:    authenticate user using default authentication method, and allow
11662:    account creation if username does not have account in the domain).
11663: $clientcancheckhost is optional (value is 1 if checking whether the
11664:    server can host will occur on the client side in lonauth.pm).   
11665: 
11666: =item *
11667: X<homeserver()>
11668: B<homeserver($uname,$udom)>: find the server which has
11669: the user's directory and files (there must be only one), this caches
11670: the answer, and also caches if there is a borken connection.
11671: 
11672: =item *
11673: X<idget()>
11674: B<idget($udom,@ids)>: find the usernames behind a list of IDs
11675: (IDs are a unique resource in a domain, there must be only 1 ID per
11676: username, and only 1 username per ID in a specific domain) (returns
11677: hash: id=>name,id=>name)
11678: 
11679: =item *
11680: X<idrget()>
11681: B<idrget($udom,@unames)>: find the IDs behind a list of
11682: usernames (returns hash: name=>id,name=>id)
11683: 
11684: =item *
11685: X<idput()>
11686: B<idput($udom,%ids)>: store away a list of names and associated IDs
11687: 
11688: =item *
11689: X<rolesinit()>
11690: B<rolesinit($udom,$username,$authhost)>: get user privileges
11691: 
11692: =item *
11693: X<getsection()>
11694: B<getsection($udom,$uname,$cname)>: finds the section of student in the
11695: course $cname, return section name/number or '' for "not in course"
11696: and '-1' for "no section"
11697: 
11698: =item *
11699: X<userenvironment()>
11700: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
11701: passed in @what from the requested user's environment, returns a hash
11702: 
11703: =item * 
11704: X<userlog_query()>
11705: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
11706: activity.log file. %filters defines filters applied when parsing the
11707: log file. These can be start or end timestamps, or the type of action
11708: - log to look for Login or Logout events, check for Checkin or
11709: Checkout, role for role selection. The response is in the form
11710: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
11711: escaped strings of the action recorded in the activity.log file.
11712: 
11713: =back
11714: 
11715: =head2 User Roles
11716: 
11717: =over 4
11718: 
11719: =item *
11720: 
11721: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
11722:  F: full access
11723:  U,I,K: authentication modes (cxx only)
11724:  '': forbidden
11725:  1: user needs to choose course
11726:  2: browse allowed
11727:  A: passphrase authentication needed
11728: 
11729: =item *
11730: 
11731: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
11732: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
11733: and course level
11734: 
11735: =item *
11736: 
11737: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
11738: (rolesplain.tab); plain text explanation of a user role term.
11739: $type is Course (default) or Community.
11740: If $forcedefault evaluates to true, text returned will be default 
11741: text for $type. Otherwise, if this is a course, the text returned 
11742: will be a custom name for the role (if defined in the course's 
11743: environment).  If no custom name is defined the default is returned.
11744:    
11745: =item *
11746: 
11747: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
11748: All arguments are optional. Returns a hash of a roles, either for
11749: co-author/assistant author roles for a user's Construction Space
11750: (default), or if $context is 'userroles', roles for the user himself,
11751: In the hash, keys are set to colon-separated $uname,$udom,$role, and
11752: (optionally) if $withsec is true, a fourth colon-separated item - $section.
11753: For each key, value is set to colon-separated start and end times for
11754: the role.  If no username and domain are specified, will default to
11755: current user/domain. Types, roles, and roledoms are references to arrays
11756: of role statuses (active, future or previous), roles 
11757: (e.g., cc,in, st etc.) and domains of the roles which can be used
11758: to restrict the list of roles reported. If no array ref is 
11759: provided for types, will default to return only active roles.
11760: 
11761: =back
11762: 
11763: =head2 User Modification
11764: 
11765: =over 4
11766: 
11767: =item *
11768: 
11769: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
11770: user for the level given by URL.  Optional start and end dates (leave empty
11771: string or zero for "no date")
11772: 
11773: =item *
11774: 
11775: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
11776: change a users, password, possible return values are: ok,
11777: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
11778: refused
11779: 
11780: =item *
11781: 
11782: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
11783: 
11784: =item *
11785: 
11786: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
11787:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
11788: 
11789: will update user information (firstname,middlename,lastname,generation,
11790: permanentemail), and if forceid is true, student/employee ID also.
11791: A user's institutional affiliation(s) can also be updated.
11792: User information fields will not be overwritten with empty entries 
11793: unless the field is included in the $candelete array reference.
11794: This array is included when a single user is modified via "Manage Users",
11795: or when Autoupdate.pl is run by cron in a domain.
11796: 
11797: =item *
11798: 
11799: modifystudent
11800: 
11801: modify a student's enrollment and identification information.
11802: The course id is resolved based on the current users environment.  
11803: This means the envoking user must be a course coordinator or otherwise
11804: associated with a course.
11805: 
11806: This call is essentially a wrapper for lonnet::modifyuser and
11807: lonnet::modify_student_enrollment
11808: 
11809: Inputs: 
11810: 
11811: =over 4
11812: 
11813: =item B<$udom> Student's loncapa domain
11814: 
11815: =item B<$uname> Student's loncapa login name
11816: 
11817: =item B<$uid> Student/Employee ID
11818: 
11819: =item B<$umode> Student's authentication mode
11820: 
11821: =item B<$upass> Student's password
11822: 
11823: =item B<$first> Student's first name
11824: 
11825: =item B<$middle> Student's middle name
11826: 
11827: =item B<$last> Student's last name
11828: 
11829: =item B<$gene> Student's generation
11830: 
11831: =item B<$usec> Student's section in course
11832: 
11833: =item B<$end> Unix time of the roles expiration
11834: 
11835: =item B<$start> Unix time of the roles start date
11836: 
11837: =item B<$forceid> If defined, allow $uid to be changed
11838: 
11839: =item B<$desiredhome> server to use as home server for student
11840: 
11841: =item B<$email> Student's permanent e-mail address
11842: 
11843: =item B<$type> Type of enrollment (auto or manual)
11844: 
11845: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
11846: 
11847: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
11848: 
11849: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
11850: 
11851: =item B<$context> role change context (shown in User Management Logs display in a course)
11852: 
11853: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
11854: 
11855: =back
11856: 
11857: =item *
11858: 
11859: modify_student_enrollment
11860: 
11861: Change a students enrollment status in a class.  The environment variable
11862: 'role.request.course' must be defined for this function to proceed.
11863: 
11864: Inputs:
11865: 
11866: =over 4
11867: 
11868: =item $udom, students domain
11869: 
11870: =item $uname, students name
11871: 
11872: =item $uid, students user id
11873: 
11874: =item $first, students first name
11875: 
11876: =item $middle
11877: 
11878: =item $last
11879: 
11880: =item $gene
11881: 
11882: =item $usec
11883: 
11884: =item $end
11885: 
11886: =item $start
11887: 
11888: =item $type
11889: 
11890: =item $locktype
11891: 
11892: =item $cid
11893: 
11894: =item $selfenroll
11895: 
11896: =item $context
11897: 
11898: =back
11899: 
11900: 
11901: =item *
11902: 
11903: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
11904: custom role; give a custom role to a user for the level given by URL.  Specify
11905: name and domain of role author, and role name
11906: 
11907: =item *
11908: 
11909: revokerole($udom,$uname,$url,$role) : revoke a role for url
11910: 
11911: =item *
11912: 
11913: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
11914: 
11915: =back
11916: 
11917: =head2 Course Infomation
11918: 
11919: =over 4
11920: 
11921: =item *
11922: 
11923: coursedescription($courseid,$options) : returns a hash of information about the
11924: specified course id, including all environment settings for the
11925: course, the description of the course will be in the hash under the
11926: key 'description'
11927: 
11928: $options is an optional parameter that if supplied is a hash reference that controls
11929: what how this function works.  It has the following key/values:
11930: 
11931: =over 4
11932: 
11933: =item freshen_cache
11934: 
11935: If defined, and the environment cache for the course is valid, it is 
11936: returned in the returned hash.
11937: 
11938: =item one_time
11939: 
11940: If defined, the last cache time is set to _now_
11941: 
11942: =item user
11943: 
11944: If defined, the supplied username is used instead of the current user.
11945: 
11946: 
11947: =back
11948: 
11949: =item *
11950: 
11951: resdata($name,$domain,$type,@which) : request for current parameter
11952: setting for a specific $type, where $type is either 'course' or 'user',
11953: @what should be a list of parameters to ask about. This routine caches
11954: answers for 5 minutes.
11955: 
11956: =item *
11957: 
11958: get_courseresdata($courseid, $domain) : dump the entire course resource
11959: data base, returning a hash that is keyed by the resource name and has
11960: values that are the resource value.  I believe that the timestamps and
11961: versions are also returned.
11962: 
11963: 
11964: =back
11965: 
11966: =head2 Course Modification
11967: 
11968: =over 4
11969: 
11970: =item *
11971: 
11972: writecoursepref($courseid,%prefs) : write preferences (environment
11973: database) for a course
11974: 
11975: =item *
11976: 
11977: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
11978: 
11979: =item *
11980: 
11981: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
11982: 
11983: =back
11984: 
11985: =head2 Resource Subroutines
11986: 
11987: =over 4
11988: 
11989: =item *
11990: 
11991: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
11992: 
11993: =item *
11994: 
11995: repcopy($filename) : subscribes to the requested file, and attempts to
11996: replicate from the owning library server, Might return
11997: 'unavailable', 'not_found', 'forbidden', 'ok', or
11998: 'bad_request', also attempts to grab the metadata for the
11999: resource. Expects the local filesystem pathname
12000: (/home/httpd/html/res/....)
12001: 
12002: =back
12003: 
12004: =head2 Resource Information
12005: 
12006: =over 4
12007: 
12008: =item *
12009: 
12010: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
12011: a vairety of different possible values, $varname should be a request
12012: string, and the other parameters can be used to specify who and what
12013: one is asking about.
12014: 
12015: Possible values for $varname are environment.lastname (or other item
12016: from the envirnment hash), user.name (or someother aspect about the
12017: user), resource.0.maxtries (or some other part and parameter of a
12018: resource)
12019: 
12020: =item *
12021: 
12022: directcondval($number) : get current value of a condition; reads from a state
12023: string
12024: 
12025: =item *
12026: 
12027: condval($condidx) : value of condition index based on state
12028: 
12029: =item *
12030: 
12031: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
12032: resource's metadata, $what should be either a specific key, or either
12033: 'keys' (to get a list of possible keys) or 'packages' to get a list of
12034: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
12035: 
12036: this function automatically caches all requests
12037: 
12038: =item *
12039: 
12040: metadata_query($query,$custom,$customshow) : make a metadata query against the
12041: network of library servers; returns file handle of where SQL and regex results
12042: will be stored for query
12043: 
12044: =item *
12045: 
12046: symbread($filename) : return symbolic list entry (filename argument optional);
12047: returns the data handle
12048: 
12049: =item *
12050: 
12051: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
12052: a possible symb for the URL in $thisfn, and if is an encryypted
12053: resource that the user accessed using /enc/ returns a 1 on success, 0
12054: on failure, user must be in a course, as it assumes the existance of
12055: the course initial hash, and uses $env('request.course.id'}
12056: 
12057: 
12058: =item *
12059: 
12060: symbclean($symb) : removes versions numbers from a symb, returns the
12061: cleaned symb
12062: 
12063: =item *
12064: 
12065: is_on_map($uri) : checks if the $uri is somewhere on the current
12066: course map, user must be in a course for it to work.
12067: 
12068: =item *
12069: 
12070: numval($salt) : return random seed value (addend for rndseed)
12071: 
12072: =item *
12073: 
12074: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
12075: a random seed, all arguments are optional, if they aren't sent it uses the
12076: environment to derive them. Note: if symb isn't sent and it can't get one
12077: from &symbread it will use the current time as its return value
12078: 
12079: =item *
12080: 
12081: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
12082: unfakeable, receipt
12083: 
12084: =item *
12085: 
12086: receipt() : API to ireceipt working off of env values; given out to users
12087: 
12088: =item *
12089: 
12090: countacc($url) : count the number of accesses to a given URL
12091: 
12092: =item *
12093: 
12094: 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
12095: 
12096: =item *
12097: 
12098: 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)
12099: 
12100: =item *
12101: 
12102: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
12103: 
12104: =item *
12105: 
12106: devalidate($symb) : devalidate temporary spreadsheet calculations,
12107: forcing spreadsheet to reevaluate the resource scores next time.
12108: 
12109: =back
12110: 
12111: =head2 Storing/Retreiving Data
12112: 
12113: =over 4
12114: 
12115: =item *
12116: 
12117: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
12118: for this url; hashref needs to be given and should be a \%hashname; the
12119: remaining args aren't required and if they aren't passed or are '' they will
12120: be derived from the env
12121: 
12122: =item *
12123: 
12124: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
12125: uses critical subroutine
12126: 
12127: =item *
12128: 
12129: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
12130: all args are optional
12131: 
12132: =item *
12133: 
12134: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
12135: dumps the complete (or key matching regexp) namespace into a hash
12136: ($udom, $uname, $regexp, $range are optional) for a namespace that is
12137: normally &store()ed into
12138: 
12139: $range should be either an integer '100' (give me the first 100
12140:                                            matching records)
12141:               or be  two integers sperated by a - with no spaces
12142:                  '30-50' (give me the 30th through the 50th matching
12143:                           records)
12144: 
12145: 
12146: =item *
12147: 
12148: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
12149: replaces a &store() version of data with a replacement set of data
12150: for a particular resource in a namespace passed in the $storehash hash 
12151: reference
12152: 
12153: =item *
12154: 
12155: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
12156: works very similar to store/cstore, but all data is stored in a
12157: temporary location and can be reset using tmpreset, $storehash should
12158: be a hash reference, returns nothing on success
12159: 
12160: =item *
12161: 
12162: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
12163: similar to restore, but all data is stored in a temporary location and
12164: can be reset using tmpreset. Returns a hash of values on success,
12165: error string otherwise.
12166: 
12167: =item *
12168: 
12169: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
12170: deltes all keys for $symb form the temporary storage hash.
12171: 
12172: =item *
12173: 
12174: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
12175: reference filled in from namesp ($udom and $uname are optional)
12176: 
12177: =item *
12178: 
12179: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
12180: namesp ($udom and $uname are optional)
12181: 
12182: =item *
12183: 
12184: dump($namespace,$udom,$uname,$regexp,$range) : 
12185: dumps the complete (or key matching regexp) namespace into a hash
12186: ($udom, $uname, $regexp, $range are optional)
12187: 
12188: $range should be either an integer '100' (give me the first 100
12189:                                            matching records)
12190:               or be  two integers sperated by a - with no spaces
12191:                  '30-50' (give me the 30th through the 50th matching
12192:                           records)
12193: =item *
12194: 
12195: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
12196: $store can be a scalar, an array reference, or if the amount to be 
12197: incremented is > 1, a hash reference.
12198: 
12199: ($udom and $uname are optional)
12200: 
12201: =item *
12202: 
12203: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
12204: ($udom and $uname are optional)
12205: 
12206: =item *
12207: 
12208: cput($namespace,$storehash,$udom,$uname) : critical put
12209: ($udom and $uname are optional)
12210: 
12211: =item *
12212: 
12213: newput($namespace,$storehash,$udom,$uname) :
12214: 
12215: Attempts to store the items in the $storehash, but only if they don't
12216: currently exist, if this succeeds you can be certain that you have 
12217: successfully created a new key value pair in the $namespace db.
12218: 
12219: 
12220: Args:
12221:  $namespace: name of database to store values to
12222:  $storehash: hashref to store to the db
12223:  $udom: (optional) domain of user containing the db
12224:  $uname: (optional) name of user caontaining the db
12225: 
12226: Returns:
12227:  'ok' -> succeeded in storing all keys of $storehash
12228:  'key_exists: <key>' -> failed to anything out of $storehash, as at
12229:                         least <key> already existed in the db (other
12230:                         requested keys may also already exist)
12231:  'error: <msg>' -> unable to tie the DB or other error occurred
12232:  'con_lost' -> unable to contact request server
12233:  'refused' -> action was not allowed by remote machine
12234: 
12235: 
12236: =item *
12237: 
12238: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
12239: reference filled in from namesp (encrypts the return communication)
12240: ($udom and $uname are optional)
12241: 
12242: =item *
12243: 
12244: log($udom,$name,$home,$message) : write to permanent log for user; use
12245: critical subroutine
12246: 
12247: =item *
12248: 
12249: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
12250: array reference filled in from namespace found in domain level on either
12251: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
12252: 
12253: =item *
12254: 
12255: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
12256: domain level either on specified domain server ($uhome) or primary domain 
12257: server ($udom and $uhome are optional)
12258: 
12259: =item * 
12260: 
12261: get_domain_defaults($target_domain) : returns hash with defaults for
12262: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
12263: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
12264: or localauth), initial password or a kerberos realm, language (e.g., en-us).
12265: Values are retrieved from cache (if current), or from domain's configuration.db
12266: (if available), or lastly from values in lonTabs/dns_domain,tab, 
12267: or lonTabs/domain.tab. 
12268: 
12269: %domdefaults = &get_auth_defaults($target_domain);
12270: 
12271: =back
12272: 
12273: =head2 Network Status Functions
12274: 
12275: =over 4
12276: 
12277: =item *
12278: 
12279: dirlist() : return directory list based on URI (first arg).
12280: 
12281: Inputs: 1 required, 5 optional.
12282: 
12283: =over
12284: 
12285: =item 
12286: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
12287: 
12288: =item
12289: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
12290: 
12291: =item
12292: $username -  username of user/course to be listed. Extracted from $uri if absent. 
12293: 
12294: =item
12295: $getpropath - boolean: 1 if prepend path using &propath(). 
12296: 
12297: =item
12298: $getuserdir - boolean: 1 if prepend path for "userfiles".
12299: 
12300: =item 
12301: $alternateRoot - path to prepend in place of path from $uri.
12302: 
12303: =back
12304: 
12305: Returns: Array of up to two items.
12306: 
12307: =over
12308: 
12309: a reference to an array of files/subdirectories
12310: 
12311: =over
12312: 
12313: Each element in the array of files/subdirectories is a & separated list of
12314: item name and the result of running stat on the item.  If dirlist was requested
12315: for a file instead of a directory, the item name will be ''. For a directory 
12316: listing, if the item is a metadata file, the element will end &N&M 
12317: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
12318: default copyright set (1).  
12319: 
12320: =back
12321: 
12322: a scalar containing error condition (if encountered).
12323: 
12324: =over
12325: 
12326: =item 
12327: no_host (no homeserver identified for $username:$domain).
12328: 
12329: =item 
12330: no_such_host (server contacted for listing not identified as valid host).
12331: 
12332: =item 
12333: con_lost (connection to remote server failed).
12334: 
12335: =item 
12336: refused (invalid $username:$domain received on lond side).
12337: 
12338: =item 
12339: no_such_dir (directory at specified path on lond side does not exist). 
12340: 
12341: =item 
12342: empty (directory at specified path on lond side is empty).
12343: 
12344: =over
12345: 
12346: This is currently not encountered because the &ls3, &ls2, 
12347: &ls (_handler) routines on the lond side do not filter out
12348: . and .. from a directory listing. 
12349: 
12350: =back
12351: 
12352: =back
12353: 
12354: =back
12355: 
12356: =item *
12357: 
12358: spareserver() : find server with least workload from spare.tab
12359: 
12360: 
12361: =item *
12362: 
12363: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
12364: if there is no corresponding loncapa host.
12365: 
12366: =back
12367: 
12368: 
12369: =head2 Apache Request
12370: 
12371: =over 4
12372: 
12373: =item *
12374: 
12375: ssi($url,%hash) : server side include, does a complete request cycle on url to
12376: localhost, posts hash
12377: 
12378: =back
12379: 
12380: =head2 Data to String to Data
12381: 
12382: =over 4
12383: 
12384: =item *
12385: 
12386: hash2str(%hash) : convert a hash into a string complete with escaping and '='
12387: and '&' separators, supports elements that are arrayrefs and hashrefs
12388: 
12389: =item *
12390: 
12391: hashref2str($hashref) : convert a hashref into a string complete with
12392: escaping and '=' and '&' separators, supports elements that are
12393: arrayrefs and hashrefs
12394: 
12395: =item *
12396: 
12397: arrayref2str($arrayref) : convert an arrayref into a string complete
12398: with escaping and '&' separators, supports elements that are arrayrefs
12399: and hashrefs
12400: 
12401: =item *
12402: 
12403: str2hash($string) : convert string to hash using unescaping and
12404: splitting on '=' and '&', supports elements that are arrayrefs and
12405: hashrefs
12406: 
12407: =item *
12408: 
12409: str2array($string) : convert string to hash using unescaping and
12410: splitting on '&', supports elements that are arrayrefs and hashrefs
12411: 
12412: =back
12413: 
12414: =head2 Logging Routines
12415: 
12416: 
12417: These routines allow one to make log messages in the lonnet.log and
12418: lonnet.perm logfiles.
12419: 
12420: =over 4
12421: 
12422: =item *
12423: 
12424: logtouch() : make sure the logfile, lonnet.log, exists
12425: 
12426: =item *
12427: 
12428: logthis() : append message to the normal lonnet.log file, it gets
12429: preiodically rolled over and deleted.
12430: 
12431: =item *
12432: 
12433: logperm() : append a permanent message to lonnet.perm.log, this log
12434: file never gets deleted by any automated portion of the system, only
12435: messages of critical importance should go in here.
12436: 
12437: 
12438: =back
12439: 
12440: =head2 General File Helper Routines
12441: 
12442: =over 4
12443: 
12444: =item *
12445: 
12446: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
12447: (a) files in /uploaded
12448:   (i) If a local copy of the file exists - 
12449:       compares modification date of local copy with last-modified date for 
12450:       definitive version stored on home server for course. If local copy is 
12451:       stale, requests a new version from the home server and stores it. 
12452:       If the original has been removed from the home server, then local copy 
12453:       is unlinked.
12454:   (ii) If local copy does not exist -
12455:       requests the file from the home server and stores it. 
12456:   
12457:   If $caller is 'uploadrep':  
12458:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
12459:     for request for files originally uploaded via DOCS. 
12460:      - returns 'ok' if fresh local copy now available, -1 otherwise.
12461:   
12462:   Otherwise:
12463:      This indicates a call from the content generation phase of the request.
12464:      -  returns the entire contents of the file or -1.
12465:      
12466: (b) files in /res
12467:    - returns the entire contents of a file or -1; 
12468:    it properly subscribes to and replicates the file if neccessary.
12469: 
12470: 
12471: =item *
12472: 
12473: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
12474:                   reference
12475: 
12476: returns either a stat() list of data about the file or an empty list
12477: if the file doesn't exist or couldn't find out about it (connection
12478: problems or user unknown)
12479: 
12480: =item *
12481: 
12482: filelocation($dir,$file) : returns file system location of a file
12483: based on URI; meant to be "fairly clean" absolute reference, $dir is a
12484: directory that relative $file lookups are to looked in ($dir of /a/dir
12485: and a file of ../bob will become /a/bob)
12486: 
12487: =item *
12488: 
12489: hreflocation($dir,$file) : returns file system location or a URL; same as
12490: filelocation except for hrefs
12491: 
12492: =item *
12493: 
12494: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
12495: 
12496: =back
12497: 
12498: =head2 Usererfile file routines (/uploaded*)
12499: 
12500: =over 4
12501: 
12502: =item *
12503: 
12504: userfileupload(): main rotine for putting a file in a user or course's
12505:                   filespace, arguments are,
12506: 
12507:  formname - required - this is the name of the element in $env where the
12508:            filename, and the contents of the file to create/modifed exist
12509:            the filename is in $env{'form.'.$formname.'.filename'} and the
12510:            contents of the file is located in $env{'form.'.$formname}
12511:  context - if coursedoc, store the file in the course of the active role
12512:              of the current user; 
12513:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
12514:            if 'canceloverwrite': delete file in tmp/overwrites directory
12515:  subdir - required - subdirectory to put the file in under ../userfiles/
12516:          if undefined, it will be placed in "unknown"
12517: 
12518:  (This routine calls clean_filename() to remove any dangerous
12519:  characters from the filename, and then calls finuserfileupload() to
12520:  complete the transaction)
12521: 
12522:  returns either the url of the uploaded file (/uploaded/....) if successful
12523:  and /adm/notfound.html if unsuccessful
12524: 
12525: =item *
12526: 
12527: clean_filename(): routine for cleaing a filename up for storage in
12528:                  userfile space, argument is:
12529: 
12530:  filename - proposed filename
12531: 
12532: returns: the new clean filename
12533: 
12534: =item *
12535: 
12536: finishuserfileupload(): routine that creates and sends the file to
12537: userspace, probably shouldn't be called directly
12538: 
12539:   docuname: username or courseid of destination for the file
12540:   docudom: domain of user/course of destination for the file
12541:   formname: same as for userfileupload()
12542:   fname: filename (including subdirectories) for the file
12543:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
12544:   allfiles: reference to hash used to store objects found by parser
12545:   codebase: reference to hash used for codebases of java objects found by parser
12546:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
12547:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
12548:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
12549:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
12550:   context: if 'overwrite', will move the uploaded file from its temporary location to
12551:             userfiles to facilitate overwriting a previously uploaded file with same name.
12552:   mimetype: reference to scalar to accommodate mime type determined
12553:             from File::MMagic if $parser = parse.
12554: 
12555:  returns either the url of the uploaded file (/uploaded/....) if successful
12556:  and /adm/notfound.html if unsuccessful (or an error message if context 
12557:  was 'overwrite').
12558:  
12559: 
12560: =item *
12561: 
12562: renameuserfile(): renames an existing userfile to a new name
12563: 
12564:   Args:
12565:    docuname: username or courseid of destination for the file
12566:    docudom: domain of user/course of destination for the file
12567:    old: current file name (including any subdirs under userfiles)
12568:    new: desired file name (including any subdirs under userfiles)
12569: 
12570: =item *
12571: 
12572: mkdiruserfile(): creates a directory is a userfiles dir
12573: 
12574:   Args:
12575:    docuname: username or courseid of destination for the file
12576:    docudom: domain of user/course of destination for the file
12577:    dir: dir to create (including any subdirs under userfiles)
12578: 
12579: =item *
12580: 
12581: removeuserfile(): removes a file that exists in userfiles
12582: 
12583:   Args:
12584:    docuname: username or courseid of destination for the file
12585:    docudom: domain of user/course of destination for the file
12586:    fname: filname to delete (including any subdirs under userfiles)
12587: 
12588: =item *
12589: 
12590: removeuploadedurl(): convience function for removeuserfile()
12591: 
12592:   Args:
12593:    url:  a full /uploaded/... url to delete
12594: 
12595: =item * 
12596: 
12597: get_portfile_permissions():
12598:   Args:
12599:     domain: domain of user or course contain the portfolio files
12600:     user: name of user or num of course contain the portfolio files
12601:   Returns:
12602:     hashref of a dump of the proper file_permissions.db
12603:    
12604: 
12605: =item * 
12606: 
12607: get_access_controls():
12608: 
12609: Args:
12610:   current_permissions: the hash ref returned from get_portfile_permissions()
12611:   group: (optional) the group you want the files associated with
12612:   file: (optional) the file you want access info on
12613: 
12614: Returns:
12615:     a hash (keys are file names) of hashes containing
12616:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
12617:         values are XML containing access control settings (see below) 
12618: 
12619: Internal notes:
12620: 
12621:  access controls are stored in file_permissions.db as key=value pairs.
12622:     key -> path to file/file_name\0uniqueID:scope_end_start
12623:         where scope -> public,guest,course,group,domains or users.
12624:               end -> UNIX time for end of access (0 -> no end date)
12625:               start -> UNIX time for start of access
12626: 
12627:     value -> XML description of access control
12628:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
12629:             <start></start>
12630:             <end></end>
12631: 
12632:             <password></password>  for scope type = guest
12633: 
12634:             <domain></domain>     for scope type = course or group
12635:             <number></number>
12636:             <roles id="">
12637:              <role></role>
12638:              <access></access>
12639:              <section></section>
12640:              <group></group>
12641:             </roles>
12642: 
12643:             <dom></dom>         for scope type = domains
12644: 
12645:             <users>             for scope type = users
12646:              <user>
12647:               <uname></uname>
12648:               <udom></udom>
12649:              </user>
12650:             </users>
12651:            </scope> 
12652:               
12653:  Access data is also aggregated for each file in an additional key=value pair:
12654:  key -> path to file/file_name\0accesscontrol 
12655:  value -> reference to hash
12656:           hash contains key = value pairs
12657:           where key = uniqueID:scope_end_start
12658:                 value = UNIX time record was last updated
12659: 
12660:           Used to improve speed of look-ups of access controls for each file.  
12661:  
12662:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
12663: 
12664: modify_access_controls():
12665: 
12666: Modifies access controls for a portfolio file
12667: Args
12668: 1. file name
12669: 2. reference to hash of required changes,
12670: 3. domain
12671: 4. username
12672:   where domain,username are the domain of the portfolio owner 
12673:   (either a user or a course) 
12674: 
12675: Returns:
12676: 1. result of additions or updates ('ok' or 'error', with error message). 
12677: 2. result of deletions ('ok' or 'error', with error message).
12678: 3. reference to hash of any new or updated access controls.
12679: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
12680:    key = integer (inbound ID)
12681:    value = uniqueID  
12682: 
12683: =back
12684: 
12685: =head2 HTTP Helper Routines
12686: 
12687: =over 4
12688: 
12689: =item *
12690: 
12691: escape() : unpack non-word characters into CGI-compatible hex codes
12692: 
12693: =item *
12694: 
12695: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
12696: 
12697: =back
12698: 
12699: =head1 PRIVATE SUBROUTINES
12700: 
12701: =head2 Underlying communication routines (Shouldn't call)
12702: 
12703: =over 4
12704: 
12705: =item *
12706: 
12707: subreply() : tries to pass a message to lonc, returns con_lost if incapable
12708: 
12709: =item *
12710: 
12711: reply() : uses subreply to send a message to remote machine, logs all failures
12712: 
12713: =item *
12714: 
12715: critical() : passes a critical message to another server; if cannot
12716: get through then place message in connection buffer directory and
12717: returns con_delayed, if incapable of saving message, returns
12718: con_failed
12719: 
12720: =item *
12721: 
12722: reconlonc() : tries to reconnect lonc client processes.
12723: 
12724: =back
12725: 
12726: =head2 Resource Access Logging
12727: 
12728: =over 4
12729: 
12730: =item *
12731: 
12732: flushcourselogs() : flush (save) buffer logs and access logs
12733: 
12734: =item *
12735: 
12736: courselog($what) : save message for course in hash
12737: 
12738: =item *
12739: 
12740: courseacclog($what) : save message for course using &courselog().  Perform
12741: special processing for specific resource types (problems, exams, quizzes, etc).
12742: 
12743: =item *
12744: 
12745: goodbye() : flush course logs and log shutting down; it is called in srm.conf
12746: as a PerlChildExitHandler
12747: 
12748: =back
12749: 
12750: =head2 Other
12751: 
12752: =over 4
12753: 
12754: =item *
12755: 
12756: symblist($mapname,%newhash) : update symbolic storage links
12757: 
12758: =back
12759: 
12760: =cut
12761: 

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