File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1172: download - view: text, annotated - select for diffs
Mon May 21 18:35:30 2012 UTC (12 years, 2 months ago) by bisitz
Branches: MAIN
CVS tags: version_2_11_X, HEAD
Removal of "priv" more global: now done in lonnet::declutter
(related to BZ 1320, 6591)

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1172 2012/05/21 18:35:30 bisitz 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: use LONCAPA::Lond;
  101: 
  102: use File::Copy;
  103: 
  104: my $readit;
  105: my $max_connection_retries = 10;     # Or some such value.
  106: 
  107: require Exporter;
  108: 
  109: our @ISA = qw (Exporter);
  110: our @EXPORT = qw(%env);
  111: 
  112: 
  113: # --------------------------------------------------------------------- Logging
  114: {
  115:     my $logid;
  116:     sub instructor_log {
  117: 	my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
  118:         if (($cnum eq '') || ($cdom eq '')) {
  119:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  120:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  121:         }
  122: 	$logid++;
  123:         my $now = time();
  124: 	my $id=$now.'00000'.$$.'00000'.$logid;
  125: 	return &Apache::lonnet::put('nohist_'.$hash_name,
  126: 				    { $id => {
  127: 					'exe_uname' => $env{'user.name'},
  128: 					'exe_udom'  => $env{'user.domain'},
  129: 					'exe_time'  => $now,
  130: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
  131: 					'delflag'   => $delflag,
  132: 					'logentry'  => $storehash,
  133: 					'uname'     => $uname,
  134: 					'udom'      => $udom,
  135: 				    }
  136: 				  },$cdom,$cnum);
  137:     }
  138: }
  139: 
  140: sub logtouch {
  141:     my $execdir=$perlvar{'lonDaemons'};
  142:     unless (-e "$execdir/logs/lonnet.log") {	
  143: 	open(my $fh,">>$execdir/logs/lonnet.log");
  144: 	close $fh;
  145:     }
  146:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  147:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  148: }
  149: 
  150: sub logthis {
  151:     my $message=shift;
  152:     my $execdir=$perlvar{'lonDaemons'};
  153:     my $now=time;
  154:     my $local=localtime($now);
  155:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
  156: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
  157: 	print $fh $logstring;
  158: 	close($fh);
  159:     }
  160:     return 1;
  161: }
  162: 
  163: sub logperm {
  164:     my $message=shift;
  165:     my $execdir=$perlvar{'lonDaemons'};
  166:     my $now=time;
  167:     my $local=localtime($now);
  168:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
  169: 	print $fh "$now:$message:$local\n";
  170: 	close($fh);
  171:     }
  172:     return 1;
  173: }
  174: 
  175: sub create_connection {
  176:     my ($hostname,$lonid) = @_;
  177:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  178: 				     Type    => SOCK_STREAM,
  179: 				     Timeout => 10);
  180:     return 0 if (!$client);
  181:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
  182:     my $result = <$client>;
  183:     chomp($result);
  184:     return 1 if ($result eq 'done');
  185:     return 0;
  186: }
  187: 
  188: sub get_server_timezone {
  189:     my ($cnum,$cdom) = @_;
  190:     my $home=&homeserver($cnum,$cdom);
  191:     if ($home ne 'no_host') {
  192:         my $cachetime = 24*3600;
  193:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
  194:         if (defined($cached)) {
  195:             return $timezone;
  196:         } else {
  197:             my $timezone = &reply('servertimezone',$home);
  198:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
  199:         }
  200:     }
  201: }
  202: 
  203: sub get_server_distarch {
  204:     my ($lonhost,$ignore_cache) = @_;
  205:     if (defined($lonhost)) {
  206:         if (!defined(&hostname($lonhost))) {
  207:             return;
  208:         }
  209:         my $cachetime = 12*3600;
  210:         if (!$ignore_cache) {
  211:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
  212:             if (defined($cached)) {
  213:                 return $distarch;
  214:             }
  215:         }
  216:         my $rep = &reply('serverdistarch',$lonhost);
  217:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
  218:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
  219:                 $rep eq '') {
  220:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
  221:         }
  222:     }
  223:     return;
  224: }
  225: 
  226: sub get_server_loncaparev {
  227:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
  228:     if (defined($lonhost)) {
  229:         if (!defined(&hostname($lonhost))) {
  230:             undef($lonhost);
  231:         }
  232:     }
  233:     if (!defined($lonhost)) {
  234:         if (defined(&domain($dom,'primary'))) {
  235:             $lonhost=&domain($dom,'primary');
  236:             if ($lonhost eq 'no_host') {
  237:                 undef($lonhost);
  238:             }
  239:         }
  240:     }
  241:     if (defined($lonhost)) {
  242:         my $cachetime = 12*3600;
  243:         if (!$ignore_cache) {
  244:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
  245:             if (defined($cached)) {
  246:                 return $loncaparev;
  247:             }
  248:         }
  249:         my ($answer,$loncaparev);
  250:         my @ids=&current_machine_ids();
  251:         if (grep(/^\Q$lonhost\E$/,@ids)) {
  252:             $answer = $perlvar{'lonVersion'};
  253:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  254:                 $loncaparev = $1;
  255:             }
  256:         } else {
  257:             $answer = &reply('serverloncaparev',$lonhost);
  258:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
  259:                 if ($caller eq 'loncron') {
  260:                     my $ua=new LWP::UserAgent;
  261:                     $ua->timeout(4);
  262:                     my $protocol = $protocol{$lonhost};
  263:                     $protocol = 'http' if ($protocol ne 'https');
  264:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
  265:                     my $request=new HTTP::Request('GET',$url);
  266:                     my $response=$ua->request($request);
  267:                     unless ($response->is_error()) {
  268:                         my $content = $response->content;
  269:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
  270:                             $loncaparev = $1;
  271:                         }
  272:                     }
  273:                 } else {
  274:                     $loncaparev = $loncaparevs{$lonhost};
  275:                 }
  276:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  277:                 $loncaparev = $1;
  278:             }
  279:         }
  280:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
  281:     }
  282: }
  283: 
  284: sub get_server_homeID {
  285:     my ($hostname,$ignore_cache,$caller) = @_;
  286:     unless ($ignore_cache) {
  287:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
  288:         if (defined($cached)) {
  289:             return $serverhomeID;
  290:         }
  291:     }
  292:     my $cachetime = 12*3600;
  293:     my $serverhomeID;
  294:     if ($caller eq 'loncron') { 
  295:         my @machine_ids = &machine_ids($hostname);
  296:         foreach my $id (@machine_ids) {
  297:             my $response = &reply('serverhomeID',$id);
  298:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
  299:                 $serverhomeID = $response;
  300:                 last;
  301:             }
  302:         }
  303:         if ($serverhomeID eq '') {
  304:             $serverhomeID = $machine_ids[-1];
  305:         }
  306:     } else {
  307:         $serverhomeID = $serverhomeIDs{$hostname};
  308:     }
  309:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
  310: }
  311: 
  312: sub get_remote_globals {
  313:     my ($lonhost,$whathash,$ignore_cache) = @_;
  314:     my ($result,%returnhash,%whatneeded);
  315:     if (ref($whathash) eq 'HASH') {
  316:         foreach my $what (sort(keys(%{$whathash}))) {
  317:             my $hashid = $lonhost.'-'.$what;
  318:             my ($response,$cached);
  319:             unless ($ignore_cache) {
  320:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
  321:             }
  322:             if (defined($cached)) {
  323:                 $returnhash{$what} = $response;
  324:             } else {
  325:                 $whatneeded{$what} = 1;
  326:             }
  327:         }
  328:         if (keys(%whatneeded) == 0) {
  329:             $result = 'ok';
  330:         } else {
  331:             my $requested = &freeze_escape(\%whatneeded);
  332:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
  333:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  334:                 ($rep eq 'unknown_cmd')) {
  335:                 $result = $rep;
  336:             } else {
  337:                 $result = 'ok';
  338:                 my @pairs=split(/\&/,$rep);
  339:                 foreach my $item (@pairs) {
  340:                     my ($key,$value)=split(/=/,$item,2);
  341:                     my $what = &unescape($key);
  342:                     my $hashid = $lonhost.'-'.$what;
  343:                     $returnhash{$what}=&thaw_unescape($value);
  344:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
  345:                 }
  346:             }
  347:         }
  348:     }
  349:     return ($result,\%returnhash);
  350: }
  351: 
  352: sub remote_devalidate_cache {
  353:     my ($lonhost,$name,$id) = @_;
  354:     my $response = &reply('devalidatecache:'.&escape($name).':'.&escape($id),$lonhost);
  355:     return $response;
  356: }
  357: 
  358: # -------------------------------------------------- Non-critical communication
  359: sub subreply {
  360:     my ($cmd,$server)=@_;
  361:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  362:     #
  363:     #  With loncnew process trimming, there's a timing hole between lonc server
  364:     #  process exit and the master server picking up the listen on the AF_UNIX
  365:     #  socket.  In that time interval, a lock file will exist:
  366: 
  367:     my $lockfile=$peerfile.".lock";
  368:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  369: 	sleep(1);
  370:     }
  371:     # At this point, either a loncnew parent is listening or an old lonc
  372:     # or loncnew child is listening so we can connect or everything's dead.
  373:     #
  374:     #   We'll give the connection a few tries before abandoning it.  If
  375:     #   connection is not possible, we'll con_lost back to the client.
  376:     #   
  377:     my $client;
  378:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  379: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  380: 				      Type    => SOCK_STREAM,
  381: 				      Timeout => 10);
  382: 	if ($client) {
  383: 	    last;		# Connected!
  384: 	} else {
  385: 	    &create_connection(&hostname($server),$server);
  386: 	}
  387:         sleep(1);		# Try again later if failed connection.
  388:     }
  389:     my $answer;
  390:     if ($client) {
  391: 	print $client "sethost:$server:$cmd\n";
  392: 	$answer=<$client>;
  393: 	if (!$answer) { $answer="con_lost"; }
  394: 	chomp($answer);
  395:     } else {
  396: 	$answer = 'con_lost';	# Failed connection.
  397:     }
  398:     return $answer;
  399: }
  400: 
  401: sub reply {
  402:     my ($cmd,$server)=@_;
  403:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  404:     my $answer=subreply($cmd,$server);
  405:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  406:        &logthis("<font color=\"blue\">WARNING:".
  407:                 " $cmd to $server returned $answer</font>");
  408:     }
  409:     return $answer;
  410: }
  411: 
  412: # ----------------------------------------------------------- Send USR1 to lonc
  413: 
  414: sub reconlonc {
  415:     my ($lonid) = @_;
  416:     my $hostname = &hostname($lonid);
  417:     if ($lonid) {
  418: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  419: 	if ($hostname && -e $peerfile) {
  420: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  421: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  422: 					     Type    => SOCK_STREAM,
  423: 					     Timeout => 10);
  424: 	    if ($client) {
  425: 		print $client ("reset_retries\n");
  426: 		my $answer=<$client>;
  427: 		#reset just this one.
  428: 	    }
  429: 	}
  430: 	return;
  431:     }
  432: 
  433:     &logthis("Trying to reconnect lonc");
  434:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  435:     if (open(my $fh,"<$loncfile")) {
  436: 	my $loncpid=<$fh>;
  437:         chomp($loncpid);
  438:         if (kill 0 => $loncpid) {
  439: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  440:             kill USR1 => $loncpid;
  441:             sleep 1;
  442:          } else {
  443: 	    &logthis(
  444:                "<font color=\"blue\">WARNING:".
  445:                " lonc at pid $loncpid not responding, giving up</font>");
  446:         }
  447:     } else {
  448: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  449:     }
  450: }
  451: 
  452: # ------------------------------------------------------ Critical communication
  453: 
  454: sub critical {
  455:     my ($cmd,$server)=@_;
  456:     unless (&hostname($server)) {
  457:         &logthis("<font color=\"blue\">WARNING:".
  458:                " Critical message to unknown server ($server)</font>");
  459:         return 'no_such_host';
  460:     }
  461:     my $answer=reply($cmd,$server);
  462:     if ($answer eq 'con_lost') {
  463: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
  464: 	my $answer=reply($cmd,$server);
  465:         if ($answer eq 'con_lost') {
  466:             my $now=time;
  467:             my $middlename=$cmd;
  468:             $middlename=substr($middlename,0,16);
  469:             $middlename=~s/\W//g;
  470:             my $dfilename=
  471:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  472:             $dumpcount++;
  473:             {
  474: 		my $dfh;
  475: 		if (open($dfh,">$dfilename")) {
  476: 		    print $dfh "$cmd\n"; 
  477: 		    close($dfh);
  478: 		}
  479:             }
  480:             sleep 2;
  481:             my $wcmd='';
  482:             {
  483: 		my $dfh;
  484: 		if (open($dfh,"<$dfilename")) {
  485: 		    $wcmd=<$dfh>; 
  486: 		    close($dfh);
  487: 		}
  488:             }
  489:             chomp($wcmd);
  490:             if ($wcmd eq $cmd) {
  491: 		&logthis("<font color=\"blue\">WARNING: ".
  492:                          "Connection buffer $dfilename: $cmd</font>");
  493:                 &logperm("D:$server:$cmd");
  494: 	        return 'con_delayed';
  495:             } else {
  496:                 &logthis("<font color=\"red\">CRITICAL:"
  497:                         ." Critical connection failed: $server $cmd</font>");
  498:                 &logperm("F:$server:$cmd");
  499:                 return 'con_failed';
  500:             }
  501:         }
  502:     }
  503:     return $answer;
  504: }
  505: 
  506: # ------------------------------------------- check if return value is an error
  507: 
  508: sub error {
  509:     my ($result) = @_;
  510:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  511: 	if ($2 == 2) { return undef; }
  512: 	return $1;
  513:     }
  514:     return undef;
  515: }
  516: 
  517: sub convert_and_load_session_env {
  518:     my ($lonidsdir,$handle)=@_;
  519:     my @profile;
  520:     {
  521: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  522: 	if (!$opened) {
  523: 	    return 0;
  524: 	}
  525: 	flock($idf,LOCK_SH);
  526: 	@profile=<$idf>;
  527: 	close($idf);
  528:     }
  529:     my %temp_env;
  530:     foreach my $line (@profile) {
  531: 	if ($line !~ m/=/) {
  532: 	    return 0;
  533: 	}
  534: 	chomp($line);
  535: 	my ($envname,$envvalue)=split(/=/,$line,2);
  536: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  537:     }
  538:     unlink("$lonidsdir/$handle.id");
  539:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  540: 	    0640)) {
  541: 	%disk_env = %temp_env;
  542: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  543: 	untie(%disk_env);
  544:     }
  545:     return 1;
  546: }
  547: 
  548: # ------------------------------------------- Transfer profile into environment
  549: my $env_loaded;
  550: sub transfer_profile_to_env {
  551:     my ($lonidsdir,$handle,$force_transfer) = @_;
  552:     if (!$force_transfer && $env_loaded) { return; } 
  553: 
  554:     if (!defined($lonidsdir)) {
  555: 	$lonidsdir = $perlvar{'lonIDsDir'};
  556:     }
  557:     if (!defined($handle)) {
  558:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  559:     }
  560: 
  561:     my $convert;
  562:     {
  563:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  564: 	if (!$opened) {
  565: 	    return;
  566: 	}
  567: 	flock($idf,LOCK_SH);
  568: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  569: 		&GDBM_READER(),0640)) {
  570: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  571: 	    untie(%disk_env);
  572: 	} else {
  573: 	    $convert = 1;
  574: 	}
  575:     }
  576:     if ($convert) {
  577: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  578: 	    &logthis("Failed to load session, or convert session.");
  579: 	}
  580:     }
  581: 
  582:     my %remove;
  583:     while ( my $envname = each(%env) ) {
  584:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  585:             if ($time < time-300) {
  586:                 $remove{$key}++;
  587:             }
  588:         }
  589:     }
  590: 
  591:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  592:     $env_loaded=1;
  593:     foreach my $expired_key (keys(%remove)) {
  594:         &delenv($expired_key);
  595:     }
  596: }
  597: 
  598: # ---------------------------------------------------- Check for valid session 
  599: sub check_for_valid_session {
  600:     my ($r,$name) = @_;
  601:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  602:     if ($name eq '') {
  603:         $name = 'lonID';
  604:     }
  605:     my $lonid=$cookies{$name};
  606:     return undef if (!$lonid);
  607: 
  608:     my $handle=&LONCAPA::clean_handle($lonid->value);
  609:     my $lonidsdir;
  610:     if ($name eq 'lonDAV') {
  611:         $lonidsdir=$r->dir_config('lonDAVsessDir');
  612:     } else {
  613:         $lonidsdir=$r->dir_config('lonIDsDir');
  614:     }
  615:     return undef if (!-e "$lonidsdir/$handle.id");
  616: 
  617:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  618:     return undef if (!$opened);
  619: 
  620:     flock($idf,LOCK_SH);
  621:     my %disk_env;
  622:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  623: 	    &GDBM_READER(),0640)) {
  624: 	return undef;	
  625:     }
  626: 
  627:     if (!defined($disk_env{'user.name'})
  628: 	|| !defined($disk_env{'user.domain'})) {
  629: 	return undef;
  630:     }
  631:     return $handle;
  632: }
  633: 
  634: sub timed_flock {
  635:     my ($file,$lock_type) = @_;
  636:     my $failed=0;
  637:     eval {
  638: 	local $SIG{__DIE__}='DEFAULT';
  639: 	local $SIG{ALRM}=sub {
  640: 	    $failed=1;
  641: 	    die("failed lock");
  642: 	};
  643: 	alarm(13);
  644: 	flock($file,$lock_type);
  645: 	alarm(0);
  646:     };
  647:     if ($failed) {
  648: 	return undef;
  649:     } else {
  650: 	return 1;
  651:     }
  652: }
  653: 
  654: # ---------------------------------------------------------- Append Environment
  655: 
  656: sub appenv {
  657:     my ($newenv,$roles) = @_;
  658:     if (ref($newenv) eq 'HASH') {
  659:         foreach my $key (keys(%{$newenv})) {
  660:             my $refused = 0;
  661: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  662:                 $refused = 1;
  663:                 if (ref($roles) eq 'ARRAY') {
  664:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
  665:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  666:                         $refused = 0;
  667:                     }
  668:                 }
  669:             }
  670:             if ($refused) {
  671:                 &logthis("<font color=\"blue\">WARNING: ".
  672:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  673:                          .'</font>');
  674: 	        delete($newenv->{$key});
  675:             } else {
  676:                 $env{$key}=$newenv->{$key};
  677:             }
  678:         }
  679:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
  680:         if ($opened
  681: 	    && &timed_flock($env_file,LOCK_EX)
  682: 	    &&
  683: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  684: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  685: 	    while (my ($key,$value) = each(%{$newenv})) {
  686: 	        $disk_env{$key} = $value;
  687: 	    }
  688: 	    untie(%disk_env);
  689:         }
  690:     }
  691:     return 'ok';
  692: }
  693: # ----------------------------------------------------- Delete from Environment
  694: 
  695: sub delenv {
  696:     my ($delthis,$regexp,$roles) = @_;
  697:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
  698:         my $refused = 1;
  699:         if (ref($roles) eq 'ARRAY') {
  700:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
  701:             if (grep(/^\Q$role\E$/,@{$roles})) {
  702:                 $refused = 0;
  703:             }
  704:         }
  705:         if ($refused) {
  706:             &logthis("<font color=\"blue\">WARNING: ".
  707:                      "Attempt to delete from environment ".$delthis);
  708:             return 'error';
  709:         }
  710:     }
  711:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  712:     if ($opened
  713: 	&& &timed_flock($env_file,LOCK_EX)
  714: 	&&
  715: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  716: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  717: 	foreach my $key (keys(%disk_env)) {
  718: 	    if ($regexp) {
  719:                 if ($key=~/^$delthis/) {
  720:                     delete($env{$key});
  721:                     delete($disk_env{$key});
  722:                 } 
  723:             } else {
  724:                 if ($key=~/^\Q$delthis\E/) {
  725: 		    delete($env{$key});
  726: 		    delete($disk_env{$key});
  727: 	        }
  728:             }
  729: 	}
  730: 	untie(%disk_env);
  731:     }
  732:     return 'ok';
  733: }
  734: 
  735: sub get_env_multiple {
  736:     my ($name) = @_;
  737:     my @values;
  738:     if (defined($env{$name})) {
  739:         # exists is it an array
  740:         if (ref($env{$name})) {
  741:             @values=@{ $env{$name} };
  742:         } else {
  743:             $values[0]=$env{$name};
  744:         }
  745:     }
  746:     return(@values);
  747: }
  748: 
  749: # ------------------------------------------------------------------- Locking
  750: 
  751: sub set_lock {
  752:     my ($text)=@_;
  753:     $locknum++;
  754:     my $id=$$.'-'.$locknum;
  755:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  756:              'session.lock.'.$id => $text});
  757:     return $id;
  758: }
  759: 
  760: sub get_locks {
  761:     my $num=0;
  762:     my %texts=();
  763:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  764:        if ($lock=~/\w/) {
  765:           $num++;
  766:           $texts{$lock}=$env{'session.lock.'.$lock};
  767:        }
  768:    }
  769:    return ($num,%texts);
  770: }
  771: 
  772: sub remove_lock {
  773:     my ($id)=@_;
  774:     my $newlocks='';
  775:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  776:        if (($lock=~/\w/) && ($lock ne $id)) {
  777:           $newlocks.=','.$lock;
  778:        }
  779:     }
  780:     &appenv({'session.locks' => $newlocks});
  781:     &delenv('session.lock.'.$id);
  782: }
  783: 
  784: sub remove_all_locks {
  785:     my $activelocks=$env{'session.locks'};
  786:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  787:        if ($lock=~/\w/) {
  788:           &remove_lock($lock);
  789:        }
  790:     }
  791: }
  792: 
  793: 
  794: # ------------------------------------------ Find out current server userload
  795: sub userload {
  796:     my $numusers=0;
  797:     {
  798: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  799: 	my $filename;
  800: 	my $curtime=time;
  801: 	while ($filename=readdir(LONIDS)) {
  802: 	    next if ($filename eq '.' || $filename eq '..');
  803: 	    next if ($filename =~ /publicuser_\d+\.id/);
  804: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  805: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  806: 	}
  807: 	closedir(LONIDS);
  808:     }
  809:     my $userloadpercent=0;
  810:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  811:     if ($maxuserload) {
  812: 	$userloadpercent=100*$numusers/$maxuserload;
  813:     }
  814:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  815:     return $userloadpercent;
  816: }
  817: 
  818: # ------------------------------ Find server with least workload from spare.tab
  819: 
  820: sub spareserver {
  821:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
  822:     my $spare_server;
  823:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  824:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  825:                                                      :  $userloadpercent;
  826:     my ($uint_dom,$remotesessions);
  827:     if (($udom ne '') && (&domain($udom) ne '')) {
  828:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
  829:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
  830:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
  831:         $remotesessions = $udomdefaults{'remotesessions'};
  832:     }
  833:     my $spareshash = &this_host_spares($udom);
  834:     if (ref($spareshash) eq 'HASH') {
  835:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  836:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  837:                 if ($uint_dom) {
  838:                     next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
  839:                                                  $try_server));
  840:                 }
  841: 	        ($spare_server, $lowest_load) =
  842: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
  843:             }
  844:         }
  845: 
  846:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
  847: 
  848:         if (!$found_server) {
  849:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
  850: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
  851:                     if ($uint_dom) {
  852:                         next unless (&spare_can_host($udom,$uint_dom,
  853:                                                      $remotesessions,$try_server));
  854:                     }
  855: 	            ($spare_server, $lowest_load) =
  856: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
  857:                 }
  858: 	    }
  859:         }
  860:     }
  861: 
  862:     if (!$want_server_name) {
  863:         my $protocol = 'http';
  864:         if ($protocol{$spare_server} eq 'https') {
  865:             $protocol = $protocol{$spare_server};
  866:         }
  867:         if (defined($spare_server)) {
  868:             my $hostname = &hostname($spare_server);
  869:             if (defined($hostname)) {
  870: 	        $spare_server = $protocol.'://'.$hostname;
  871:             }
  872:         }
  873:     }
  874:     return $spare_server;
  875: }
  876: 
  877: sub compare_server_load {
  878:     my ($try_server, $spare_server, $lowest_load) = @_;
  879: 
  880:     my $loadans     = &reply('load',    $try_server);
  881:     my $userloadans = &reply('userload',$try_server);
  882: 
  883:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  884: 	return ($spare_server, $lowest_load); #didn't get a number from the server
  885:     }
  886: 
  887:     my $load;
  888:     if ($loadans =~ /\d/) {
  889: 	if ($userloadans =~ /\d/) {
  890: 	    #both are numbers, pick the bigger one
  891: 	    $load = ($loadans > $userloadans) ? $loadans 
  892: 		                              : $userloadans;
  893: 	} else {
  894: 	    $load = $loadans;
  895: 	}
  896:     } else {
  897: 	$load = $userloadans;
  898:     }
  899: 
  900:     if (($load =~ /\d/) && ($load < $lowest_load)) {
  901: 	$spare_server = $try_server;
  902: 	$lowest_load  = $load;
  903:     }
  904:     return ($spare_server,$lowest_load);
  905: }
  906: 
  907: # --------------------------- ask offload servers if user already has a session
  908: sub find_existing_session {
  909:     my ($udom,$uname) = @_;
  910:     my $spareshash = &this_host_spares($udom);
  911:     if (ref($spareshash) eq 'HASH') {
  912:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  913:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  914:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
  915:             }
  916:         }
  917:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
  918:             foreach my $try_server (@{ $spareshash->{'default'} }) {
  919:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
  920:             }
  921:         }
  922:     }
  923:     return;
  924: }
  925: 
  926: # -------------------------------- ask if server already has a session for user
  927: sub has_user_session {
  928:     my ($lonid,$udom,$uname) = @_;
  929:     my $result = &reply(join(':','userhassession',
  930: 			     map {&escape($_)} ($udom,$uname)),$lonid);
  931:     return 1 if ($result eq 'ok');
  932: 
  933:     return 0;
  934: }
  935: 
  936: # --------- determine least loaded server in a user's domain which allows login
  937: 
  938: sub choose_server {
  939:     my ($udom,$checkloginvia) = @_;
  940:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
  941:     my %servers = &get_servers($udom);
  942:     my $lowest_load = 30000;
  943:     my ($login_host,$hostname,$portal_path,$isredirect);
  944:     foreach my $lonhost (keys(%servers)) {
  945:         my $loginvia;
  946:         if ($checkloginvia) {
  947:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
  948:             if ($loginvia) {
  949:                 my ($server,$path) = split(/:/,$loginvia);
  950:                 ($login_host, $lowest_load) =
  951:                     &compare_server_load($server, $login_host, $lowest_load);
  952:                 if ($login_host eq $server) {
  953:                     $portal_path = $path;
  954:                     $isredirect = 1;
  955:                 }
  956:             } else {
  957:                 ($login_host, $lowest_load) =
  958:                     &compare_server_load($lonhost, $login_host, $lowest_load);
  959:                 if ($login_host eq $lonhost) {
  960:                     $portal_path = '';
  961:                     $isredirect = ''; 
  962:                 }
  963:             }
  964:         } else {
  965:             ($login_host, $lowest_load) =
  966:                 &compare_server_load($lonhost, $login_host, $lowest_load);
  967:         }
  968:     }
  969:     if ($login_host ne '') {
  970:         $hostname = &hostname($login_host);
  971:     }
  972:     return ($login_host,$hostname,$portal_path,$isredirect);
  973: }
  974: 
  975: # --------------------------------------------- Try to change a user's password
  976: 
  977: sub changepass {
  978:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
  979:     $currentpass = &escape($currentpass);
  980:     $newpass     = &escape($newpass);
  981:     my $lonhost = $perlvar{'lonHostID'};
  982:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
  983: 		       $server);
  984:     if (! $answer) {
  985: 	&logthis("No reply on password change request to $server ".
  986: 		 "by $uname in domain $udom.");
  987:     } elsif ($answer =~ "^ok") {
  988:         &logthis("$uname in $udom successfully changed their password ".
  989: 		 "on $server.");
  990:     } elsif ($answer =~ "^pwchange_failure") {
  991: 	&logthis("$uname in $udom was unable to change their password ".
  992: 		 "on $server.  The action was blocked by either lcpasswd ".
  993: 		 "or pwchange");
  994:     } elsif ($answer =~ "^non_authorized") {
  995:         &logthis("$uname in $udom did not get their password correct when ".
  996: 		 "attempting to change it on $server.");
  997:     } elsif ($answer =~ "^auth_mode_error") {
  998:         &logthis("$uname in $udom attempted to change their password despite ".
  999: 		 "not being locally or internally authenticated on $server.");
 1000:     } elsif ($answer =~ "^unknown_user") {
 1001:         &logthis("$uname in $udom attempted to change their password ".
 1002: 		 "on $server but were unable to because $server is not ".
 1003: 		 "their home server.");
 1004:     } elsif ($answer =~ "^refused") {
 1005: 	&logthis("$server refused to change $uname in $udom password because ".
 1006: 		 "it was sent an unencrypted request to change the password.");
 1007:     } elsif ($answer =~ "invalid_client") {
 1008:         &logthis("$server refused to change $uname in $udom password because ".
 1009:                  "it was a reset by e-mail originating from an invalid server.");
 1010:     }
 1011:     return $answer;
 1012: }
 1013: 
 1014: # ----------------------- Try to determine user's current authentication scheme
 1015: 
 1016: sub queryauthenticate {
 1017:     my ($uname,$udom)=@_;
 1018:     my $uhome=&homeserver($uname,$udom);
 1019:     if (!$uhome) {
 1020: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
 1021: 	return 'no_host';
 1022:     }
 1023:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
 1024:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
 1025: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1026:     }
 1027:     return $answer;
 1028: }
 1029: 
 1030: # --------- Try to authenticate user from domain's lib servers (first this one)
 1031: 
 1032: sub authenticate {
 1033:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
 1034:     $upass=&escape($upass);
 1035:     $uname= &LONCAPA::clean_username($uname);
 1036:     my $uhome=&homeserver($uname,$udom,1);
 1037:     my $newhome;
 1038:     if ((!$uhome) || ($uhome eq 'no_host')) {
 1039: # Maybe the machine was offline and only re-appeared again recently?
 1040:         &reconlonc();
 1041: # One more
 1042: 	$uhome=&homeserver($uname,$udom,1);
 1043:         if (($uhome eq 'no_host') && $checkdefauth) {
 1044:             if (defined(&domain($udom,'primary'))) {
 1045:                 $newhome=&domain($udom,'primary');
 1046:             }
 1047:             if ($newhome ne '') {
 1048:                 $uhome = $newhome;
 1049:             }
 1050:         }
 1051: 	if ((!$uhome) || ($uhome eq 'no_host')) {
 1052: 	    &logthis("User $uname at $udom is unknown in authenticate");
 1053: 	    return 'no_host';
 1054:         }
 1055:     }
 1056:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
 1057:     if ($answer eq 'authorized') {
 1058:         if ($newhome) {
 1059:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
 1060:             return 'no_account_on_host'; 
 1061:         } else {
 1062:             &logthis("User $uname at $udom authorized by $uhome");
 1063:             return $uhome;
 1064:         }
 1065:     }
 1066:     if ($answer eq 'non_authorized') {
 1067: 	&logthis("User $uname at $udom rejected by $uhome");
 1068: 	return 'no_host'; 
 1069:     }
 1070:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1071:     return 'no_host';
 1072: }
 1073: 
 1074: sub can_host_session {
 1075:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
 1076:     my $canhost = 1;
 1077:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
 1078:     if (ref($remotesessions) eq 'HASH') {
 1079:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
 1080:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
 1081:                 $canhost = 0;
 1082:             } else {
 1083:                 $canhost = 1;
 1084:             }
 1085:         }
 1086:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
 1087:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
 1088:                 $canhost = 1;
 1089:             } else {
 1090:                 $canhost = 0;
 1091:             }
 1092:         }
 1093:         if ($canhost) {
 1094:             if ($remotesessions->{'version'} ne '') {
 1095:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
 1096:                 if ($reqmajor ne '' && $reqminor ne '') {
 1097:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
 1098:                         my $major = $1;
 1099:                         my $minor = $2;
 1100:                         if (($major < $reqmajor ) ||
 1101:                             (($major == $reqmajor) && ($minor < $reqminor))) {
 1102:                             $canhost = 0;
 1103:                         }
 1104:                     } else {
 1105:                         $canhost = 0;
 1106:                     }
 1107:                 }
 1108:             }
 1109:         }
 1110:     }
 1111:     if ($canhost) {
 1112:         if (ref($hostedsessions) eq 'HASH') {
 1113:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1114:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 1115:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
 1116:                 if (($uint_dom ne '') && 
 1117:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
 1118:                     $canhost = 0;
 1119:                 } else {
 1120:                     $canhost = 1;
 1121:                 }
 1122:             }
 1123:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
 1124:                 if (($uint_dom ne '') && 
 1125:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
 1126:                     $canhost = 1;
 1127:                 } else {
 1128:                     $canhost = 0;
 1129:                 }
 1130:             }
 1131:         }
 1132:     }
 1133:     return $canhost;
 1134: }
 1135: 
 1136: sub spare_can_host {
 1137:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
 1138:     my $canhost=1;
 1139:     my @intdoms;
 1140:     my $internet_names = &Apache::lonnet::get_internet_names($try_server);
 1141:     if (ref($internet_names) eq 'ARRAY') {
 1142:         @intdoms = @{$internet_names};
 1143:     }
 1144:     unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1145:         my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
 1146:         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
 1147:         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
 1148:         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
 1149:         $canhost = &can_host_session($udom,$try_server,$remoterev,
 1150:                                      $remotesessions,
 1151:                                      $defdomdefaults{'hostedsessions'});
 1152:     }
 1153:     return $canhost;
 1154: }
 1155: 
 1156: sub this_host_spares {
 1157:     my ($dom) = @_;
 1158:     my ($dom_in_use,$lonhost_in_use,$result);
 1159:     my @hosts = &current_machine_ids();
 1160:     foreach my $lonhost (@hosts) {
 1161:         if (&host_domain($lonhost) eq $dom) {
 1162:             $dom_in_use = $dom;
 1163:             $lonhost_in_use = $lonhost;
 1164:             last;
 1165:         }
 1166:     }
 1167:     if ($dom_in_use ne '') {
 1168:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1169:     }
 1170:     if (ref($result) ne 'HASH') {
 1171:         $lonhost_in_use = $perlvar{'lonHostID'};
 1172:         $dom_in_use = &host_domain($lonhost_in_use);
 1173:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1174:         if (ref($result) ne 'HASH') {
 1175:             $result = \%spareid;
 1176:         }
 1177:     }
 1178:     return $result;
 1179: }
 1180: 
 1181: sub spares_for_offload  {
 1182:     my ($dom_in_use,$lonhost_in_use) = @_;
 1183:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
 1184:     if (defined($cached)) {
 1185:         return $result;
 1186:     } else {
 1187:         my $cachetime = 60*60*24;
 1188:         my %domconfig =
 1189:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
 1190:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1191:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
 1192:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
 1193:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
 1194:                 }
 1195:             }
 1196:         }
 1197:     }
 1198:     return;
 1199: }
 1200: 
 1201: sub get_lonbalancer_config {
 1202:     my ($servers) = @_;
 1203:     my ($currbalancer,$currtargets);
 1204:     if (ref($servers) eq 'HASH') {
 1205:         foreach my $server (keys(%{$servers})) {
 1206:             my %what = (
 1207:                          spareid => 1,
 1208:                          perlvar => 1,
 1209:                        );
 1210:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
 1211:             if ($result eq 'ok') {
 1212:                 if (ref($returnhash) eq 'HASH') {
 1213:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
 1214:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
 1215:                             $currbalancer = $server;
 1216:                             $currtargets = {};
 1217:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
 1218:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
 1219:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
 1220:                                 }
 1221:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
 1222:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
 1223:                                 }
 1224:                             }
 1225:                             last;
 1226:                         }
 1227:                     }
 1228:                 }
 1229:             }
 1230:         }
 1231:     }
 1232:     return ($currbalancer,$currtargets);
 1233: }
 1234: 
 1235: sub check_loadbalancing {
 1236:     my ($uname,$udom) = @_;
 1237:     my ($is_balancer,$dom_in_use,$homeintdom,$rule_in_effect,
 1238:         $offloadto,$otherserver);
 1239:     my $lonhost = $perlvar{'lonHostID'};
 1240:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1241:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
 1242:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
 1243:     my $serverhomedom = &host_domain($lonhost);
 1244: 
 1245:     my $cachetime = 60*60*24;
 1246: 
 1247:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1248:         $dom_in_use = $udom;
 1249:         $homeintdom = 1;
 1250:     } else {
 1251:         $dom_in_use = $serverhomedom;
 1252:     }
 1253:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
 1254:     unless (defined($cached)) {
 1255:         my %domconfig =
 1256:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
 1257:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1258:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1259:         }
 1260:     }
 1261:     if (ref($result) eq 'HASH') {
 1262:         my $currbalancer = $result->{'lonhost'};
 1263:         my $currtargets = $result->{'targets'};
 1264:         my $currrules = $result->{'rules'};
 1265:         if ($currbalancer ne '') {
 1266:             my @hosts = &current_machine_ids();
 1267:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
 1268:                 $is_balancer = 1;
 1269:             }
 1270:         }
 1271:         if ($is_balancer) {
 1272:             if (ref($currrules) eq 'HASH') {
 1273:                 if ($homeintdom) {
 1274:                     if ($uname ne '') {
 1275:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
 1276:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
 1277:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
 1278:                                 $rule_in_effect = $currrules->{'_LC_author'};
 1279:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
 1280:                                 $rule_in_effect = $currrules->{'_LC_adv'}
 1281:                             }
 1282:                         }
 1283:                         if ($rule_in_effect eq '') {
 1284:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
 1285:                             if ($userenv{'inststatus'} ne '') {
 1286:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
 1287:                                 my ($othertitle,$usertypes,$types) =
 1288:                                     &Apache::loncommon::sorted_inst_types($udom);
 1289:                                 if (ref($types) eq 'ARRAY') {
 1290:                                     foreach my $type (@{$types}) {
 1291:                                         if (grep(/^\Q$type\E$/,@statuses)) {
 1292:                                             if (exists($currrules->{$type})) {
 1293:                                                 $rule_in_effect = $currrules->{$type};
 1294:                                             }
 1295:                                         }
 1296:                                     }
 1297:                                 }
 1298:                             } else {
 1299:                                 if (exists($currrules->{'default'})) {
 1300:                                     $rule_in_effect = $currrules->{'default'};
 1301:                                 }
 1302:                             }
 1303:                         }
 1304:                     } else {
 1305:                         if (exists($currrules->{'default'})) {
 1306:                             $rule_in_effect = $currrules->{'default'};
 1307:                         }
 1308:                     }
 1309:                 } else {
 1310:                     if ($currrules->{'_LC_external'} ne '') {
 1311:                         $rule_in_effect = $currrules->{'_LC_external'};
 1312:                     }
 1313:                 }
 1314:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1315:                                                        $uname,$udom);
 1316:             }
 1317:         }
 1318:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
 1319:         my ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
 1320:         unless (defined($cached)) {
 1321:             my %domconfig =
 1322:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
 1323:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1324:                 $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1325:             }
 1326:         }
 1327:         if (ref($result) eq 'HASH') {
 1328:             my $currbalancer = $result->{'lonhost'};
 1329:             my $currtargets = $result->{'targets'};
 1330:             my $currrules = $result->{'rules'};
 1331: 
 1332:             if ($currbalancer eq $lonhost) {
 1333:                 $is_balancer = 1;
 1334:                 if (ref($currrules) eq 'HASH') {
 1335:                     if ($currrules->{'_LC_internetdom'} ne '') {
 1336:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
 1337:                     }
 1338:                 }
 1339:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1340:                                                        $uname,$udom);
 1341:             }
 1342:         } else {
 1343:             if ($perlvar{'lonBalancer'} eq 'yes') {
 1344:                 $is_balancer = 1;
 1345:                 $offloadto = &this_host_spares($dom_in_use);
 1346:             }
 1347:         }
 1348:     } else {
 1349:         if ($perlvar{'lonBalancer'} eq 'yes') {
 1350:             $is_balancer = 1;
 1351:             $offloadto = &this_host_spares($dom_in_use);
 1352:         }
 1353:     }
 1354:     my $lowest_load = 30000;
 1355:     if (ref($offloadto) eq 'HASH') {
 1356:         if (ref($offloadto->{'primary'}) eq 'ARRAY') {
 1357:             foreach my $try_server (@{$offloadto->{'primary'}}) {
 1358:                 ($otherserver,$lowest_load) =
 1359:                     &compare_server_load($try_server,$otherserver,$lowest_load);
 1360:             }
 1361:         }
 1362:         my $found_server = ($otherserver ne '' && $lowest_load < 100);
 1363: 
 1364:         if (!$found_server) {
 1365:             if (ref($offloadto->{'default'}) eq 'ARRAY') {
 1366:                 foreach my $try_server (@{$offloadto->{'default'}}) {
 1367:                     ($otherserver,$lowest_load) =
 1368:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1369:                 }
 1370:             }
 1371:         }
 1372:     } elsif (ref($offloadto) eq 'ARRAY') {
 1373:         if (@{$offloadto} == 1) {
 1374:             $otherserver = $offloadto->[0];
 1375:         } elsif (@{$offloadto} > 1) {
 1376:             foreach my $try_server (@{$offloadto}) {
 1377:                 ($otherserver,$lowest_load) =
 1378:                     &compare_server_load($try_server,$otherserver,$lowest_load);
 1379:             }
 1380:         }
 1381:     }
 1382:     return ($is_balancer,$otherserver);
 1383: }
 1384: 
 1385: sub get_loadbalancer_targets {
 1386:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
 1387:     my $offloadto;
 1388:     if ($rule_in_effect eq '') {
 1389:         $offloadto = $currtargets;
 1390:     } else {
 1391:         if ($rule_in_effect eq 'homeserver') {
 1392:             my $homeserver = &homeserver($uname,$udom);
 1393:             if ($homeserver ne 'no_host') {
 1394:                 $offloadto = [$homeserver];
 1395:             }
 1396:         } elsif ($rule_in_effect eq 'externalbalancer') {
 1397:             my %domconfig =
 1398:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1399:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1400:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
 1401:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
 1402:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
 1403:                     }
 1404:                 }
 1405:             } else {
 1406:                 my %servers = &dom_servers($udom);
 1407:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
 1408:                 if (&hostname($remotebalancer) ne '') {
 1409:                     $offloadto = [$remotebalancer];
 1410:                 }
 1411:             }
 1412:         } elsif (&hostname($rule_in_effect) ne '') {
 1413:             $offloadto = [$rule_in_effect];
 1414:         }
 1415:     }
 1416:     return $offloadto;
 1417: }
 1418: 
 1419: sub internet_dom_servers {
 1420:     my ($dom) = @_;
 1421:     my (%uniqservers,%servers);
 1422:     my $primaryserver = &hostname(&domain($dom,'primary'));
 1423:     my @machinedoms = &machine_domains($primaryserver);
 1424:     foreach my $mdom (@machinedoms) {
 1425:         my %currservers = %servers;
 1426:         my %server = &get_servers($mdom);
 1427:         %servers = (%currservers,%server);
 1428:     }
 1429:     my %by_hostname;
 1430:     foreach my $id (keys(%servers)) {
 1431:         push(@{$by_hostname{$servers{$id}}},$id);
 1432:     }
 1433:     foreach my $hostname (sort(keys(%by_hostname))) {
 1434:         if (@{$by_hostname{$hostname}} > 1) {
 1435:             my $match = 0;
 1436:             foreach my $id (@{$by_hostname{$hostname}}) {
 1437:                 if (&host_domain($id) eq $dom) {
 1438:                     $uniqservers{$id} = $hostname;
 1439:                     $match = 1;
 1440:                 }
 1441:             }
 1442:             unless ($match) {
 1443:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1444:             }
 1445:         } else {
 1446:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1447:         }
 1448:     }
 1449:     return %uniqservers;
 1450: }
 1451: 
 1452: # ---------------------- Find the homebase for a user from domain's lib servers
 1453: 
 1454: my %homecache;
 1455: sub homeserver {
 1456:     my ($uname,$udom,$ignoreBadCache)=@_;
 1457:     my $index="$uname:$udom";
 1458: 
 1459:     if (exists($homecache{$index})) { return $homecache{$index}; }
 1460: 
 1461:     my %servers = &get_servers($udom,'library');
 1462:     foreach my $tryserver (keys(%servers)) {
 1463:         next if ($ignoreBadCache ne 'true' && 
 1464: 		 exists($badServerCache{$tryserver}));
 1465: 
 1466: 	my $answer=reply("home:$udom:$uname",$tryserver);
 1467: 	if ($answer eq 'found') {
 1468: 	    delete($badServerCache{$tryserver}); 
 1469: 	    return $homecache{$index}=$tryserver;
 1470: 	} elsif ($answer eq 'no_host') {
 1471: 	    $badServerCache{$tryserver}=1;
 1472: 	}
 1473:     }    
 1474:     return 'no_host';
 1475: }
 1476: 
 1477: # ------------------------------------- Find the usernames behind a list of IDs
 1478: 
 1479: sub idget {
 1480:     my ($udom,@ids)=@_;
 1481:     my %returnhash=();
 1482:     
 1483:     my %servers = &get_servers($udom,'library');
 1484:     foreach my $tryserver (keys(%servers)) {
 1485: 	my $idlist=join('&',@ids);
 1486: 	$idlist=~tr/A-Z/a-z/; 
 1487: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
 1488: 	my @answer=();
 1489: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
 1490: 	    @answer=split(/\&/,$reply);
 1491: 	}                    ;
 1492: 	my $i;
 1493: 	for ($i=0;$i<=$#ids;$i++) {
 1494: 	    if ($answer[$i]) {
 1495: 		$returnhash{$ids[$i]}=$answer[$i];
 1496: 	    } 
 1497: 	}
 1498:     } 
 1499:     return %returnhash;
 1500: }
 1501: 
 1502: # ------------------------------------- Find the IDs behind a list of usernames
 1503: 
 1504: sub idrget {
 1505:     my ($udom,@unames)=@_;
 1506:     my %returnhash=();
 1507:     foreach my $uname (@unames) {
 1508:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
 1509:     }
 1510:     return %returnhash;
 1511: }
 1512: 
 1513: # ------------------------------- Store away a list of names and associated IDs
 1514: 
 1515: sub idput {
 1516:     my ($udom,%ids)=@_;
 1517:     my %servers=();
 1518:     foreach my $uname (keys(%ids)) {
 1519: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
 1520:         my $uhom=&homeserver($uname,$udom);
 1521:         if ($uhom ne 'no_host') {
 1522:             my $id=&escape($ids{$uname});
 1523:             $id=~tr/A-Z/a-z/;
 1524:             my $esc_unam=&escape($uname);
 1525: 	    if ($servers{$uhom}) {
 1526: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
 1527:             } else {
 1528:                 $servers{$uhom}=$id.'='.$esc_unam;
 1529:             }
 1530:         }
 1531:     }
 1532:     foreach my $server (keys(%servers)) {
 1533:         &critical('idput:'.$udom.':'.$servers{$server},$server);
 1534:     }
 1535: }
 1536: 
 1537: # ------------------------------dump from db file owned by domainconfig user
 1538: sub dump_dom {
 1539:     my ($namespace, $udom, $regexp) = @_;
 1540: 
 1541:     $udom ||= $env{'user.domain'};
 1542: 
 1543:     return () unless $udom;
 1544: 
 1545:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
 1546: }
 1547: 
 1548: # ------------------------------------------ get items from domain db files   
 1549: 
 1550: sub get_dom {
 1551:     my ($namespace,$storearr,$udom,$uhome)=@_;
 1552:     my $items='';
 1553:     foreach my $item (@$storearr) {
 1554:         $items.=&escape($item).'&';
 1555:     }
 1556:     $items=~s/\&$//;
 1557:     if (!$udom) {
 1558:         $udom=$env{'user.domain'};
 1559:         if (defined(&domain($udom,'primary'))) {
 1560:             $uhome=&domain($udom,'primary');
 1561:         } else {
 1562:             undef($uhome);
 1563:         }
 1564:     } else {
 1565:         if (!$uhome) {
 1566:             if (defined(&domain($udom,'primary'))) {
 1567:                 $uhome=&domain($udom,'primary');
 1568:             }
 1569:         }
 1570:     }
 1571:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1572:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 1573:         my %returnhash;
 1574:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 1575:             return %returnhash;
 1576:         }
 1577:         my @pairs=split(/\&/,$rep);
 1578:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 1579:             return @pairs;
 1580:         }
 1581:         my $i=0;
 1582:         foreach my $item (@$storearr) {
 1583:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 1584:             $i++;
 1585:         }
 1586:         return %returnhash;
 1587:     } else {
 1588:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 1589:     }
 1590: }
 1591: 
 1592: # -------------------------------------------- put items in domain db files 
 1593: 
 1594: sub put_dom {
 1595:     my ($namespace,$storehash,$udom,$uhome)=@_;
 1596:     if (!$udom) {
 1597:         $udom=$env{'user.domain'};
 1598:         if (defined(&domain($udom,'primary'))) {
 1599:             $uhome=&domain($udom,'primary');
 1600:         } else {
 1601:             undef($uhome);
 1602:         }
 1603:     } else {
 1604:         if (!$uhome) {
 1605:             if (defined(&domain($udom,'primary'))) {
 1606:                 $uhome=&domain($udom,'primary');
 1607:             }
 1608:         }
 1609:     } 
 1610:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1611:         my $items='';
 1612:         foreach my $item (keys(%$storehash)) {
 1613:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 1614:         }
 1615:         $items=~s/\&$//;
 1616:         return &reply("putdom:$udom:$namespace:$items",$uhome);
 1617:     } else {
 1618:         &logthis("put_dom failed - no homeserver and/or domain");
 1619:     }
 1620: }
 1621: 
 1622: # --------------------- newput for items in db file owned by domainconfig user
 1623: sub newput_dom {
 1624:     my ($namespace,$storehash,$udom) = @_;
 1625:     my $result;
 1626:     if (!$udom) {
 1627:         $udom=$env{'user.domain'};
 1628:     }
 1629:     if ($udom) {
 1630:         my $uname = &get_domainconfiguser($udom);
 1631:         $result = &newput($namespace,$storehash,$udom,$uname);
 1632:     }
 1633:     return $result;
 1634: }
 1635: 
 1636: # --------------------- delete for items in db file owned by domainconfig user
 1637: sub del_dom {
 1638:     my ($namespace,$storearr,$udom)=@_;
 1639:     if (ref($storearr) eq 'ARRAY') {
 1640:         if (!$udom) {
 1641:             $udom=$env{'user.domain'};
 1642:         }
 1643:         if ($udom) {
 1644:             my $uname = &get_domainconfiguser($udom); 
 1645:             return &del($namespace,$storearr,$udom,$uname);
 1646:         }
 1647:     }
 1648: }
 1649: 
 1650: # ----------------------------------construct domainconfig user for a domain 
 1651: sub get_domainconfiguser {
 1652:     my ($udom) = @_;
 1653:     return $udom.'-domainconfig';
 1654: }
 1655: 
 1656: sub retrieve_inst_usertypes {
 1657:     my ($udom) = @_;
 1658:     my (%returnhash,@order);
 1659:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 1660:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 1661:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 1662:         %returnhash = %{$domdefs{'inststatustypes'}};
 1663:         @order = @{$domdefs{'inststatusorder'}};
 1664:     } else {
 1665:         if (defined(&domain($udom,'primary'))) {
 1666:             my $uhome=&domain($udom,'primary');
 1667:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 1668:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 1669:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
 1670:                 return (\%returnhash,\@order);
 1671:             }
 1672:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 1673:             my @pairs=split(/\&/,$hashitems);
 1674:             foreach my $item (@pairs) {
 1675:                 my ($key,$value)=split(/=/,$item,2);
 1676:                 $key = &unescape($key);
 1677:                 next if ($key =~ /^error: 2 /);
 1678:                 $returnhash{$key}=&thaw_unescape($value);
 1679:             }
 1680:             my @esc_order = split(/\&/,$orderitems);
 1681:             foreach my $item (@esc_order) {
 1682:                 push(@order,&unescape($item));
 1683:             }
 1684:         } else {
 1685:             &logthis("get_dom failed - no primary domain server for $udom");
 1686:         }
 1687:     }
 1688:     return (\%returnhash,\@order);
 1689: }
 1690: 
 1691: sub is_domainimage {
 1692:     my ($url) = @_;
 1693:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
 1694:         if (&domain($1) ne '') {
 1695:             return '1';
 1696:         }
 1697:     }
 1698:     return;
 1699: }
 1700: 
 1701: sub inst_directory_query {
 1702:     my ($srch) = @_;
 1703:     my $udom = $srch->{'srchdomain'};
 1704:     my %results;
 1705:     my $homeserver = &domain($udom,'primary');
 1706:     my $outcome;
 1707:     if ($homeserver ne '') {
 1708: 	my $queryid=&reply("querysend:instdirsearch:".
 1709: 			   &escape($srch->{'srchby'}).':'.
 1710: 			   &escape($srch->{'srchterm'}).':'.
 1711: 			   &escape($srch->{'srchtype'}),$homeserver);
 1712: 	my $host=&hostname($homeserver);
 1713: 	if ($queryid !~/^\Q$host\E\_/) {
 1714: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1715: 	    return;
 1716: 	}
 1717: 	my $response = &get_query_reply($queryid);
 1718: 	my $maxtries = 5;
 1719: 	my $tries = 1;
 1720: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1721: 	    $response = &get_query_reply($queryid);
 1722: 	    $tries ++;
 1723: 	}
 1724: 
 1725:         if (!&error($response) && $response ne 'refused') {
 1726:             if ($response eq 'unavailable') {
 1727:                 $outcome = $response;
 1728:             } else {
 1729:                 $outcome = 'ok';
 1730:                 my @matches = split(/\n/,$response);
 1731:                 foreach my $match (@matches) {
 1732:                     my ($key,$value) = split(/=/,$match);
 1733:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 1734:                 }
 1735:             }
 1736:         }
 1737:     }
 1738:     return ($outcome,%results);
 1739: }
 1740: 
 1741: sub usersearch {
 1742:     my ($srch) = @_;
 1743:     my $dom = $srch->{'srchdomain'};
 1744:     my %results;
 1745:     my %libserv = &all_library();
 1746:     my $query = 'usersearch';
 1747:     foreach my $tryserver (keys(%libserv)) {
 1748:         if (&host_domain($tryserver) eq $dom) {
 1749:             my $host=&hostname($tryserver);
 1750:             my $queryid=
 1751:                 &reply("querysend:".&escape($query).':'.
 1752:                        &escape($srch->{'srchby'}).':'.
 1753:                        &escape($srch->{'srchtype'}).':'.
 1754:                        &escape($srch->{'srchterm'}),$tryserver);
 1755:             if ($queryid !~/^\Q$host\E\_/) {
 1756:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 1757:                 next;
 1758:             }
 1759:             my $reply = &get_query_reply($queryid);
 1760:             my $maxtries = 1;
 1761:             my $tries = 1;
 1762:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 1763:                 $reply = &get_query_reply($queryid);
 1764:                 $tries ++;
 1765:             }
 1766:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 1767:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 1768:             } else {
 1769:                 my @matches;
 1770:                 if ($reply =~ /\n/) {
 1771:                     @matches = split(/\n/,$reply);
 1772:                 } else {
 1773:                     @matches = split(/\&/,$reply);
 1774:                 }
 1775:                 foreach my $match (@matches) {
 1776:                     my ($uname,$udom,%userhash);
 1777:                     foreach my $entry (split(/:/,$match)) {
 1778:                         my ($key,$value) =
 1779:                             map {&unescape($_);} split(/=/,$entry);
 1780:                         $userhash{$key} = $value;
 1781:                         if ($key eq 'username') {
 1782:                             $uname = $value;
 1783:                         } elsif ($key eq 'domain') {
 1784:                             $udom = $value;
 1785:                         }
 1786:                     }
 1787:                     $results{$uname.':'.$udom} = \%userhash;
 1788:                 }
 1789:             }
 1790:         }
 1791:     }
 1792:     return %results;
 1793: }
 1794: 
 1795: sub get_instuser {
 1796:     my ($udom,$uname,$id) = @_;
 1797:     my $homeserver = &domain($udom,'primary');
 1798:     my ($outcome,%results);
 1799:     if ($homeserver ne '') {
 1800:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 1801:                            &escape($id).':'.&escape($udom),$homeserver);
 1802:         my $host=&hostname($homeserver);
 1803:         if ($queryid !~/^\Q$host\E\_/) {
 1804:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1805:             return;
 1806:         }
 1807:         my $response = &get_query_reply($queryid);
 1808:         my $maxtries = 5;
 1809:         my $tries = 1;
 1810:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1811:             $response = &get_query_reply($queryid);
 1812:             $tries ++;
 1813:         }
 1814:         if (!&error($response) && $response ne 'refused') {
 1815:             if ($response eq 'unavailable') {
 1816:                 $outcome = $response;
 1817:             } else {
 1818:                 $outcome = 'ok';
 1819:                 my @matches = split(/\n/,$response);
 1820:                 foreach my $match (@matches) {
 1821:                     my ($key,$value) = split(/=/,$match);
 1822:                     $results{&unescape($key)} = &thaw_unescape($value);
 1823:                 }
 1824:             }
 1825:         }
 1826:     }
 1827:     my %userinfo;
 1828:     if (ref($results{$uname}) eq 'HASH') {
 1829:         %userinfo = %{$results{$uname}};
 1830:     } 
 1831:     return ($outcome,%userinfo);
 1832: }
 1833: 
 1834: sub inst_rulecheck {
 1835:     my ($udom,$uname,$id,$item,$rules) = @_;
 1836:     my %returnhash;
 1837:     if ($udom ne '') {
 1838:         if (ref($rules) eq 'ARRAY') {
 1839:             @{$rules} = map {&escape($_);} (@{$rules});
 1840:             my $rulestr = join(':',@{$rules});
 1841:             my $homeserver=&domain($udom,'primary');
 1842:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1843:                 my $response;
 1844:                 if ($item eq 'username') {                
 1845:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 1846:                                               ':'.&escape($uname).':'.$rulestr,
 1847:                                               $homeserver));
 1848:                 } elsif ($item eq 'id') {
 1849:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 1850:                                               ':'.&escape($id).':'.$rulestr,
 1851:                                               $homeserver));
 1852:                 } elsif ($item eq 'selfcreate') {
 1853:                     $response=&unescape(&reply('instselfcreatecheck:'.
 1854:                                                &escape($udom).':'.&escape($uname).
 1855:                                               ':'.$rulestr,$homeserver));
 1856:                 }
 1857:                 if ($response ne 'refused') {
 1858:                     my @pairs=split(/\&/,$response);
 1859:                     foreach my $item (@pairs) {
 1860:                         my ($key,$value)=split(/=/,$item,2);
 1861:                         $key = &unescape($key);
 1862:                         next if ($key =~ /^error: 2 /);
 1863:                         $returnhash{$key}=&thaw_unescape($value);
 1864:                     }
 1865:                 }
 1866:             }
 1867:         }
 1868:     }
 1869:     return %returnhash;
 1870: }
 1871: 
 1872: sub inst_userrules {
 1873:     my ($udom,$check) = @_;
 1874:     my (%ruleshash,@ruleorder);
 1875:     if ($udom ne '') {
 1876:         my $homeserver=&domain($udom,'primary');
 1877:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1878:             my $response;
 1879:             if ($check eq 'id') {
 1880:                 $response=&reply('instidrules:'.&escape($udom),
 1881:                                  $homeserver);
 1882:             } elsif ($check eq 'email') {
 1883:                 $response=&reply('instemailrules:'.&escape($udom),
 1884:                                  $homeserver);
 1885:             } else {
 1886:                 $response=&reply('instuserrules:'.&escape($udom),
 1887:                                  $homeserver);
 1888:             }
 1889:             if (($response ne 'refused') && ($response ne 'error') && 
 1890:                 ($response ne 'unknown_cmd') && 
 1891:                 ($response ne 'no_such_host')) {
 1892:                 my ($hashitems,$orderitems) = split(/:/,$response);
 1893:                 my @pairs=split(/\&/,$hashitems);
 1894:                 foreach my $item (@pairs) {
 1895:                     my ($key,$value)=split(/=/,$item,2);
 1896:                     $key = &unescape($key);
 1897:                     next if ($key =~ /^error: 2 /);
 1898:                     $ruleshash{$key}=&thaw_unescape($value);
 1899:                 }
 1900:                 my @esc_order = split(/\&/,$orderitems);
 1901:                 foreach my $item (@esc_order) {
 1902:                     push(@ruleorder,&unescape($item));
 1903:                 }
 1904:             }
 1905:         }
 1906:     }
 1907:     return (\%ruleshash,\@ruleorder);
 1908: }
 1909: 
 1910: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 1911: 
 1912: sub get_domain_defaults {
 1913:     my ($domain) = @_;
 1914:     my $cachetime = 60*60*24;
 1915:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 1916:     if (defined($cached)) {
 1917:         if (ref($result) eq 'HASH') {
 1918:             return %{$result};
 1919:         }
 1920:     }
 1921:     my %domdefaults;
 1922:     my %domconfig =
 1923:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 1924:                                   'requestcourses','inststatus',
 1925:                                   'coursedefaults','usersessions'],$domain);
 1926:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 1927:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 1928:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 1929:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 1930:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 1931:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 1932:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
 1933:     } else {
 1934:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 1935:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 1936:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 1937:     }
 1938:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 1939:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 1940:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 1941:         } else {
 1942:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 1943:         } 
 1944:         my @usertools = ('aboutme','blog','portfolio');
 1945:         foreach my $item (@usertools) {
 1946:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 1947:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 1948:             }
 1949:         }
 1950:     }
 1951:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 1952:         foreach my $item ('official','unofficial','community') {
 1953:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 1954:         }
 1955:     }
 1956:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 1957:         foreach my $item ('inststatustypes','inststatusorder') {
 1958:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 1959:         }
 1960:     }
 1961:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 1962:         foreach my $item ('canuse_pdfforms') {
 1963:             $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
 1964:         }
 1965:     }
 1966:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1967:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 1968:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 1969:         }
 1970:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 1971:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 1972:         }
 1973:     }
 1974:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
 1975:                                   $cachetime);
 1976:     return %domdefaults;
 1977: }
 1978: 
 1979: # --------------------------------------------------- Assign a key to a student
 1980: 
 1981: sub assign_access_key {
 1982: #
 1983: # a valid key looks like uname:udom#comments
 1984: # comments are being appended
 1985: #
 1986:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 1987:     $kdom=
 1988:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 1989:     $knum=
 1990:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 1991:     $cdom=
 1992:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1993:     $cnum=
 1994:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1995:     $udom=$env{'user.name'} unless (defined($udom));
 1996:     $uname=$env{'user.domain'} unless (defined($uname));
 1997:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 1998:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 1999:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 2000:                                                   # assigned to this person
 2001:                                                   # - this should not happen,
 2002:                                                   # unless something went wrong
 2003:                                                   # the first time around
 2004: # ready to assign
 2005:         $logentry=$1.'; '.$logentry;
 2006:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 2007:                                                  $kdom,$knum) eq 'ok') {
 2008: # key now belongs to user
 2009: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 2010:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 2011:                 &appenv({'environment.'.$envkey => $ckey});
 2012:                 return 'ok';
 2013:             } else {
 2014:                 return 
 2015:   'error: Count not permanently assign key, will need to be re-entered later.';
 2016: 	    }
 2017:         } else {
 2018:             return 'error: Could not assign key, try again later.';
 2019:         }
 2020:     } elsif (!$existing{$ckey}) {
 2021: # the key does not exist
 2022: 	return 'error: The key does not exist';
 2023:     } else {
 2024: # the key is somebody else's
 2025: 	return 'error: The key is already in use';
 2026:     }
 2027: }
 2028: 
 2029: # ------------------------------------------ put an additional comment on a key
 2030: 
 2031: sub comment_access_key {
 2032: #
 2033: # a valid key looks like uname:udom#comments
 2034: # comments are being appended
 2035: #
 2036:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 2037:     $cdom=
 2038:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2039:     $cnum=
 2040:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2041:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2042:     if ($existing{$ckey}) {
 2043:         $existing{$ckey}.='; '.$logentry;
 2044: # ready to assign
 2045:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 2046:                                                  $cdom,$cnum) eq 'ok') {
 2047: 	    return 'ok';
 2048:         } else {
 2049: 	    return 'error: Count not store comment.';
 2050:         }
 2051:     } else {
 2052: # the key does not exist
 2053: 	return 'error: The key does not exist';
 2054:     }
 2055: }
 2056: 
 2057: # ------------------------------------------------------ Generate a set of keys
 2058: 
 2059: sub generate_access_keys {
 2060:     my ($number,$cdom,$cnum,$logentry)=@_;
 2061:     $cdom=
 2062:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2063:     $cnum=
 2064:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2065:     unless (&allowed('mky',$cdom)) { return 0; }
 2066:     unless (($cdom) && ($cnum)) { return 0; }
 2067:     if ($number>10000) { return 0; }
 2068:     sleep(2); # make sure don't get same seed twice
 2069:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 2070:     my $total=0;
 2071:     for (my $i=1;$i<=$number;$i++) {
 2072:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 2073:                   sprintf("%lx",int(100000*rand)).'-'.
 2074:                   sprintf("%lx",int(100000*rand));
 2075:        $newkey=~s/1/g/g; # folks mix up 1 and l
 2076:        $newkey=~s/0/h/g; # and also 0 and O
 2077:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 2078:        if ($existing{$newkey}) {
 2079:            $i--;
 2080:        } else {
 2081: 	  if (&put('accesskeys',
 2082:               { $newkey => '# generated '.localtime().
 2083:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 2084:                            '; '.$logentry },
 2085: 		   $cdom,$cnum) eq 'ok') {
 2086:               $total++;
 2087: 	  }
 2088:        }
 2089:     }
 2090:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 2091:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 2092:     return $total;
 2093: }
 2094: 
 2095: # ------------------------------------------------------- Validate an accesskey
 2096: 
 2097: sub validate_access_key {
 2098:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 2099:     $cdom=
 2100:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2101:     $cnum=
 2102:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2103:     $udom=$env{'user.domain'} unless (defined($udom));
 2104:     $uname=$env{'user.name'} unless (defined($uname));
 2105:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2106:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 2107: }
 2108: 
 2109: # ------------------------------------- Find the section of student in a course
 2110: sub devalidate_getsection_cache {
 2111:     my ($udom,$unam,$courseid)=@_;
 2112:     my $hashid="$udom:$unam:$courseid";
 2113:     &devalidate_cache_new('getsection',$hashid);
 2114: }
 2115: 
 2116: sub courseid_to_courseurl {
 2117:     my ($courseid) = @_;
 2118:     #already url style courseid
 2119:     return $courseid if ($courseid =~ m{^/});
 2120: 
 2121:     if (exists($env{'course.'.$courseid.'.num'})) {
 2122: 	my $cnum = $env{'course.'.$courseid.'.num'};
 2123: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 2124: 	return "/$cdom/$cnum";
 2125:     }
 2126: 
 2127:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 2128:     if (exists($courseinfo{'num'})) {
 2129: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 2130:     }
 2131: 
 2132:     return undef;
 2133: }
 2134: 
 2135: sub getsection {
 2136:     my ($udom,$unam,$courseid)=@_;
 2137:     my $cachetime=1800;
 2138: 
 2139:     my $hashid="$udom:$unam:$courseid";
 2140:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 2141:     if (defined($cached)) { return $result; }
 2142: 
 2143:     my %Pending; 
 2144:     my %Expired;
 2145:     #
 2146:     # Each role can either have not started yet (pending), be active, 
 2147:     #    or have expired.
 2148:     #
 2149:     # If there is an active role, we are done.
 2150:     #
 2151:     # If there is more than one role which has not started yet, 
 2152:     #     choose the one which will start sooner
 2153:     # If there is one role which has not started yet, return it.
 2154:     #
 2155:     # If there is more than one expired role, choose the one which ended last.
 2156:     # If there is a role which has expired, return it.
 2157:     #
 2158:     $courseid = &courseid_to_courseurl($courseid);
 2159:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 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|aa|in|cc|ep|cr|ta|co)/ ) {
 3494:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 3495:        $userrolehash
 3496:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 3497:                     =$tend.':'.$tstart;
 3498:     }
 3499:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
 3500:        $userrolehash
 3501:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 3502:                     =$tend.':'.$tstart;
 3503:     }
 3504:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
 3505:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 3506:        $domainrolehash
 3507:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 3508:                     = $tend.':'.$tstart;
 3509:     }
 3510: }
 3511: 
 3512: sub courserolelog {
 3513:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 3514:     if (($trole eq 'cc') || ($trole eq 'in') ||
 3515:         ($trole eq 'ep') || ($trole eq 'ad') ||
 3516:         ($trole eq 'ta') || ($trole eq 'st') ||
 3517:         ($trole=~/^cr/) || ($trole eq 'gr') ||
 3518:         ($trole eq 'co')) {
 3519:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 3520:             my $cdom = $1;
 3521:             my $cnum = $2;
 3522:             my $sec = $3;
 3523:             my $namespace = 'rolelog';
 3524:             my %storehash = (
 3525:                                role    => $trole,
 3526:                                start   => $tstart,
 3527:                                end     => $tend,
 3528:                                selfenroll => $selfenroll,
 3529:                                context    => $context,
 3530:                             );
 3531:             if ($trole eq 'gr') {
 3532:                 $namespace = 'groupslog';
 3533:                 $storehash{'group'} = $sec;
 3534:             } else {
 3535:                 $storehash{'section'} = $sec;
 3536:             }
 3537:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
 3538:             if (($trole ne 'st') || ($sec ne '')) {
 3539:                 &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 3540:             }
 3541:         }
 3542:     }
 3543:     return;
 3544: }
 3545: 
 3546: sub get_course_adv_roles {
 3547:     my ($cid,$codes) = @_;
 3548:     $cid=$env{'request.course.id'} unless (defined($cid));
 3549:     my %coursehash=&coursedescription($cid);
 3550:     my $crstype = &Apache::loncommon::course_type($cid);
 3551:     my %nothide=();
 3552:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3553:         if ($user !~ /:/) {
 3554: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 3555:         } else {
 3556:             $nothide{$user}=1;
 3557:         }
 3558:     }
 3559:     my %returnhash=();
 3560:     my %dumphash=
 3561:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 3562:     my $now=time;
 3563:     my %privileged;
 3564:     foreach my $entry (keys(%dumphash)) {
 3565: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 3566:         if (($tstart) && ($tstart<0)) { next; }
 3567:         if (($tend) && ($tend<$now)) { next; }
 3568:         if (($tstart) && ($now<$tstart)) { next; }
 3569:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 3570: 	if ($username eq '' || $domain eq '') { next; }
 3571:         unless (ref($privileged{$domain}) eq 'HASH') {
 3572:             my %dompersonnel =
 3573:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
 3574:             $privileged{$domain} = {};
 3575:             foreach my $server (keys(%dompersonnel)) {
 3576:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 3577:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
 3578:                         my ($trole,$uname,$udom) = split(/:/,$user);
 3579:                         $privileged{$udom}{$uname} = 1;
 3580:                     }
 3581:                 }
 3582:             }
 3583:         }
 3584:         if ((exists($privileged{$domain}{$username})) && 
 3585:             (!$nothide{$username.':'.$domain})) { next; }
 3586: 	if ($role eq 'cr') { next; }
 3587:         if ($codes) {
 3588:             if ($section) { $role .= ':'.$section; }
 3589:             if ($returnhash{$role}) {
 3590:                 $returnhash{$role}.=','.$username.':'.$domain;
 3591:             } else {
 3592:                 $returnhash{$role}=$username.':'.$domain;
 3593:             }
 3594:         } else {
 3595:             my $key=&plaintext($role,$crstype);
 3596:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 3597:             if ($returnhash{$key}) {
 3598: 	        $returnhash{$key}.=','.$username.':'.$domain;
 3599:             } else {
 3600:                 $returnhash{$key}=$username.':'.$domain;
 3601:             }
 3602:         }
 3603:     }
 3604:     return %returnhash;
 3605: }
 3606: 
 3607: sub get_my_roles {
 3608:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 3609:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 3610:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 3611:     my (%dumphash,%nothide);
 3612:     if ($context eq 'userroles') {
 3613:         %dumphash = &dump('roles',$udom,$uname);
 3614:     } else {
 3615:         %dumphash=
 3616:             &dump('nohist_userroles',$udom,$uname);
 3617:         if ($hidepriv) {
 3618:             my %coursehash=&coursedescription($udom.'_'.$uname);
 3619:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3620:                 if ($user !~ /:/) {
 3621:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 3622:                 } else {
 3623:                     $nothide{$user} = 1;
 3624:                 }
 3625:             }
 3626:         }
 3627:     }
 3628:     my %returnhash=();
 3629:     my $now=time;
 3630:     my %privileged;
 3631:     foreach my $entry (keys(%dumphash)) {
 3632:         my ($role,$tend,$tstart);
 3633:         if ($context eq 'userroles') {
 3634:             next if ($entry =~ /^rolesdef/);
 3635: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 3636:         } else {
 3637:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 3638:         }
 3639:         if (($tstart) && ($tstart<0)) { next; }
 3640:         my $status = 'active';
 3641:         if (($tend) && ($tend<=$now)) {
 3642:             $status = 'previous';
 3643:         } 
 3644:         if (($tstart) && ($now<$tstart)) {
 3645:             $status = 'future';
 3646:         }
 3647:         if (ref($types) eq 'ARRAY') {
 3648:             if (!grep(/^\Q$status\E$/,@{$types})) {
 3649:                 next;
 3650:             } 
 3651:         } else {
 3652:             if ($status ne 'active') {
 3653:                 next;
 3654:             }
 3655:         }
 3656:         my ($rolecode,$username,$domain,$section,$area);
 3657:         if ($context eq 'userroles') {
 3658:             ($area,$rolecode) = split(/_/,$entry);
 3659:             (undef,$domain,$username,$section) = split(/\//,$area);
 3660:         } else {
 3661:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 3662:         }
 3663:         if (ref($roledoms) eq 'ARRAY') {
 3664:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 3665:                 next;
 3666:             }
 3667:         }
 3668:         if (ref($roles) eq 'ARRAY') {
 3669:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 3670:                 if ($role =~ /^cr\//) {
 3671:                     if (!grep(/^cr$/,@{$roles})) {
 3672:                         next;
 3673:                     }
 3674:                 } elsif ($role =~ /^gr\//) {
 3675:                     if (!grep(/^gr$/,@{$roles})) {
 3676:                         next;
 3677:                     }
 3678:                 } else {
 3679:                     next;
 3680:                 }
 3681:             }
 3682:         }
 3683:         if ($hidepriv) {
 3684:             if ($context eq 'userroles') {
 3685:                 if ((&privileged($username,$domain)) &&
 3686:                     (!$nothide{$username.':'.$domain})) {
 3687:                     next;
 3688:                 }
 3689:             } else {
 3690:                 unless (ref($privileged{$domain}) eq 'HASH') {
 3691:                     my %dompersonnel =
 3692:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
 3693:                     $privileged{$domain} = {};
 3694:                     if (keys(%dompersonnel)) {
 3695:                         foreach my $server (keys(%dompersonnel)) {
 3696:                             if (ref($dompersonnel{$server}) eq 'HASH') {
 3697:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
 3698:                                     my ($trole,$uname,$udom) = split(/:/,$user);
 3699:                                     $privileged{$udom}{$uname} = $trole;
 3700:                                 }
 3701:                             }
 3702:                         }
 3703:                     }
 3704:                 }
 3705:                 if (exists($privileged{$domain}{$username})) {
 3706:                     if (!$nothide{$username.':'.$domain}) {
 3707:                         next;
 3708:                     }
 3709:                 }
 3710:             }
 3711:         }
 3712:         if ($withsec) {
 3713:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 3714:                 $tstart.':'.$tend;
 3715:         } else {
 3716:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 3717:         }
 3718:     }
 3719:     return %returnhash;
 3720: }
 3721: 
 3722: # ----------------------------------------------------- Frontpage Announcements
 3723: #
 3724: #
 3725: 
 3726: sub postannounce {
 3727:     my ($server,$text)=@_;
 3728:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 3729:     unless ($text=~/\w/) { $text=''; }
 3730:     return &reply('setannounce:'.&escape($text),$server);
 3731: }
 3732: 
 3733: sub getannounce {
 3734: 
 3735:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 3736: 	my $announcement='';
 3737: 	while (my $line = <$fh>) { $announcement .= $line; }
 3738: 	close($fh);
 3739: 	if ($announcement=~/\w/) { 
 3740: 	    return 
 3741:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 3742:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 3743: 	} else {
 3744: 	    return '';
 3745: 	}
 3746:     } else {
 3747: 	return '';
 3748:     }
 3749: }
 3750: 
 3751: # ---------------------------------------------------------- Course ID routines
 3752: # Deal with domain's nohist_courseid.db files
 3753: #
 3754: 
 3755: sub courseidput {
 3756:     my ($domain,$storehash,$coursehome,$caller) = @_;
 3757:     return unless (ref($storehash) eq 'HASH');
 3758:     my $outcome;
 3759:     if ($caller eq 'timeonly') {
 3760:         my $cids = '';
 3761:         foreach my $item (keys(%$storehash)) {
 3762:             $cids.=&escape($item).'&';
 3763:         }
 3764:         $cids=~s/\&$//;
 3765:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 3766:                           $coursehome);       
 3767:     } else {
 3768:         my $items = '';
 3769:         foreach my $item (keys(%$storehash)) {
 3770:             $items.= &escape($item).'='.
 3771:                      &freeze_escape($$storehash{$item}).'&';
 3772:         }
 3773:         $items=~s/\&$//;
 3774:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 3775:                           $coursehome);
 3776:     }
 3777:     if ($outcome eq 'unknown_cmd') {
 3778:         my $what;
 3779:         foreach my $cid (keys(%$storehash)) {
 3780:             $what .= &escape($cid).'=';
 3781:             foreach my $item ('description','inst_code','owner','type') {
 3782:                 $what .= &escape($storehash->{$cid}{$item}).':';
 3783:             }
 3784:             $what =~ s/\:$/&/;
 3785:         }
 3786:         $what =~ s/\&$//;  
 3787:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 3788:     } else {
 3789:         return $outcome;
 3790:     }
 3791: }
 3792: 
 3793: sub courseiddump {
 3794:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 3795:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 3796:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 3797:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
 3798:     my $as_hash = 1;
 3799:     my %returnhash;
 3800:     if (!$domfilter) { $domfilter=''; }
 3801:     my %libserv = &all_library();
 3802:     foreach my $tryserver (keys(%libserv)) {
 3803:         if ( (  $hostidflag == 1 
 3804: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 3805: 	     || (!defined($hostidflag)) ) {
 3806: 
 3807: 	    if (($domfilter eq '') ||
 3808: 		(&host_domain($tryserver) eq $domfilter)) {
 3809:                 my $rep = 
 3810:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
 3811:                          $sincefilter.':'.&escape($descfilter).':'.
 3812:                          &escape($instcodefilter).':'.&escape($ownerfilter).
 3813:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
 3814:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
 3815:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
 3816:                          $showhidden.':'.$caller.':'.&escape($cloner).':'.
 3817:                          &escape($cc_clone).':'.$cloneonly.':'.
 3818:                          &escape($createdbefore).':'.&escape($createdafter).':'.
 3819:                          &escape($creationcontext).':'.$domcloner,
 3820:                          $tryserver);
 3821:                 my @pairs=split(/\&/,$rep);
 3822:                 foreach my $item (@pairs) {
 3823:                     my ($key,$value)=split(/\=/,$item,2);
 3824:                     $key = &unescape($key);
 3825:                     next if ($key =~ /^error: 2 /);
 3826:                     my $result = &thaw_unescape($value);
 3827:                     if (ref($result) eq 'HASH') {
 3828:                         $returnhash{$key}=$result;
 3829:                     } else {
 3830:                         my @responses = split(/:/,$value);
 3831:                         my @items = ('description','inst_code','owner','type');
 3832:                         for (my $i=0; $i<@responses; $i++) {
 3833:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 3834:                         }
 3835:                     }
 3836:                 }
 3837:             }
 3838:         }
 3839:     }
 3840:     return %returnhash;
 3841: }
 3842: 
 3843: sub courselastaccess {
 3844:     my ($cdom,$cnum,$hostidref) = @_;
 3845:     my %returnhash;
 3846:     if ($cdom && $cnum) {
 3847:         my $chome = &homeserver($cnum,$cdom);
 3848:         if ($chome ne 'no_host') {
 3849:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 3850:             &extract_lastaccess(\%returnhash,$rep);
 3851:         }
 3852:     } else {
 3853:         if (!$cdom) { $cdom=''; }
 3854:         my %libserv = &all_library();
 3855:         foreach my $tryserver (keys(%libserv)) {
 3856:             if (ref($hostidref) eq 'ARRAY') {
 3857:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 3858:             } 
 3859:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 3860:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 3861:                 &extract_lastaccess(\%returnhash,$rep);
 3862:             }
 3863:         }
 3864:     }
 3865:     return %returnhash;
 3866: }
 3867: 
 3868: sub extract_lastaccess {
 3869:     my ($returnhash,$rep) = @_;
 3870:     if (ref($returnhash) eq 'HASH') {
 3871:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 3872:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 3873:                  $rep eq '') {
 3874:             my @pairs=split(/\&/,$rep);
 3875:             foreach my $item (@pairs) {
 3876:                 my ($key,$value)=split(/\=/,$item,2);
 3877:                 $key = &unescape($key);
 3878:                 next if ($key =~ /^error: 2 /);
 3879:                 $returnhash->{$key} = &thaw_unescape($value);
 3880:             }
 3881:         }
 3882:     }
 3883:     return;
 3884: }
 3885: 
 3886: # ---------------------------------------------------------- DC e-mail
 3887: 
 3888: sub dcmailput {
 3889:     my ($domain,$msgid,$message,$server)=@_;
 3890:     my $status = &Apache::lonnet::critical(
 3891:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 3892:        &escape($message),$server);
 3893:     return $status;
 3894: }
 3895: 
 3896: sub dcmaildump {
 3897:     my ($dom,$startdate,$enddate,$senders) = @_;
 3898:     my %returnhash=();
 3899: 
 3900:     if (defined(&domain($dom,'primary'))) {
 3901:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 3902:                                                          &escape($enddate).':';
 3903: 	my @esc_senders=map { &escape($_)} @$senders;
 3904: 	$cmd.=&escape(join('&',@esc_senders));
 3905: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 3906:             my ($key,$value) = split(/\=/,$line,2);
 3907:             if (($key) && ($value)) {
 3908:                 $returnhash{&unescape($key)} = &unescape($value);
 3909:             }
 3910:         }
 3911:     }
 3912:     return %returnhash;
 3913: }
 3914: # ---------------------------------------------------------- Domain roles
 3915: 
 3916: sub get_domain_roles {
 3917:     my ($dom,$roles,$startdate,$enddate)=@_;
 3918:     if ((!defined($startdate)) || ($startdate eq '')) {
 3919:         $startdate = '.';
 3920:     }
 3921:     if ((!defined($enddate)) || ($enddate eq '')) {
 3922:         $enddate = '.';
 3923:     }
 3924:     my $rolelist;
 3925:     if (ref($roles) eq 'ARRAY') {
 3926:         $rolelist = join(':',@{$roles});
 3927:     }
 3928:     my %personnel = ();
 3929: 
 3930:     my %servers = &get_servers($dom,'library');
 3931:     foreach my $tryserver (keys(%servers)) {
 3932: 	%{$personnel{$tryserver}}=();
 3933: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 3934: 					    &escape($startdate).':'.
 3935: 					    &escape($enddate).':'.
 3936: 					    &escape($rolelist), $tryserver))) {
 3937: 	    my ($key,$value) = split(/\=/,$line,2);
 3938: 	    if (($key) && ($value)) {
 3939: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 3940: 	    }
 3941: 	}
 3942:     }
 3943:     return %personnel;
 3944: }
 3945: 
 3946: # ----------------------------------------------------------- Interval timing 
 3947: 
 3948: {
 3949: # Caches needed for speedup of navmaps
 3950: # We don't want to cache this for very long at all (5 seconds at most)
 3951: # 
 3952: # The user for whom we cache
 3953: my $cachedkey='';
 3954: # The cached times for this user
 3955: my %cachedtimes=();
 3956: # When this was last done
 3957: my $cachedtime=();
 3958: 
 3959: sub load_all_first_access {
 3960:     my ($uname,$udom)=@_;
 3961:     if (($cachedkey eq $uname.':'.$udom) &&
 3962:         (abs($cachedtime-time)<5)) {
 3963:         return;
 3964:     }
 3965:     $cachedtime=time;
 3966:     $cachedkey=$uname.':'.$udom;
 3967:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 3968: }
 3969: 
 3970: sub get_first_access {
 3971:     my ($type,$argsymb,$argmap)=@_;
 3972:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 3973:     if ($argsymb) { $symb=$argsymb; }
 3974:     my ($map,$id,$res)=&decode_symb($symb);
 3975:     if ($argmap) { $map = $argmap; }
 3976:     if ($type eq 'course') {
 3977: 	$res='course';
 3978:     } elsif ($type eq 'map') {
 3979: 	$res=&symbread($map);
 3980:     } else {
 3981: 	$res=$symb;
 3982:     }
 3983:     &load_all_first_access($uname,$udom);
 3984:     return $cachedtimes{"$courseid\0$res"};
 3985: }
 3986: 
 3987: sub set_first_access {
 3988:     my ($type,$interval)=@_;
 3989:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 3990:     my ($map,$id,$res)=&decode_symb($symb);
 3991:     if ($type eq 'course') {
 3992: 	$res='course';
 3993:     } elsif ($type eq 'map') {
 3994: 	$res=&symbread($map);
 3995:     } else {
 3996: 	$res=$symb;
 3997:     }
 3998:     $cachedkey='';
 3999:     my $firstaccess=&get_first_access($type,$symb,$map);
 4000:     if (!$firstaccess) {
 4001:         my $start = time;
 4002: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 4003:                           $udom,$uname);
 4004:         if ($putres eq 'ok') {
 4005:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 4006:                  $udom,$uname); 
 4007:             &appenv(
 4008:                      {
 4009:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 4010:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 4011:                      }
 4012:                   );
 4013:         }
 4014:         return $putres;
 4015:     }
 4016:     return 'already_set';
 4017: }
 4018: }
 4019: # --------------------------------------------- Set Expire Date for Spreadsheet
 4020: 
 4021: sub expirespread {
 4022:     my ($uname,$udom,$stype,$usymb)=@_;
 4023:     my $cid=$env{'request.course.id'}; 
 4024:     if ($cid) {
 4025:        my $now=time;
 4026:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 4027:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 4028:                             $env{'course.'.$cid.'.num'}.
 4029: 	        	    ':nohist_expirationdates:'.
 4030:                             &escape($key).'='.$now,
 4031:                             $env{'course.'.$cid.'.home'})
 4032:     }
 4033:     return 'ok';
 4034: }
 4035: 
 4036: # ----------------------------------------------------- Devalidate Spreadsheets
 4037: 
 4038: sub devalidate {
 4039:     my ($symb,$uname,$udom)=@_;
 4040:     my $cid=$env{'request.course.id'}; 
 4041:     if ($cid) {
 4042:         # delete the stored spreadsheets for
 4043:         # - the student level sheet of this user in course's homespace
 4044:         # - the assessment level sheet for this resource 
 4045:         #   for this user in user's homespace
 4046: 	# - current conditional state info
 4047: 	my $key=$uname.':'.$udom.':';
 4048:         my $status=
 4049: 	    &del('nohist_calculatedsheets',
 4050: 		 [$key.'studentcalc:'],
 4051: 		 $env{'course.'.$cid.'.domain'},
 4052: 		 $env{'course.'.$cid.'.num'})
 4053: 		.' '.
 4054: 	    &del('nohist_calculatedsheets_'.$cid,
 4055: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 4056:         unless ($status eq 'ok ok') {
 4057:            &logthis('Could not devalidate spreadsheet '.
 4058:                     $uname.' at '.$udom.' for '.
 4059: 		    $symb.': '.$status);
 4060:         }
 4061: 	&delenv('user.state.'.$cid);
 4062:     }
 4063: }
 4064: 
 4065: sub get_scalar {
 4066:     my ($string,$end) = @_;
 4067:     my $value;
 4068:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 4069: 	$value = $1;
 4070:     } elsif ($$string =~ s/^([^&]*?)&//) {
 4071: 	$value = $1;
 4072:     }
 4073:     return &unescape($value);
 4074: }
 4075: 
 4076: sub array2str {
 4077:   my (@array) = @_;
 4078:   my $result=&arrayref2str(\@array);
 4079:   $result=~s/^__ARRAY_REF__//;
 4080:   $result=~s/__END_ARRAY_REF__$//;
 4081:   return $result;
 4082: }
 4083: 
 4084: sub arrayref2str {
 4085:   my ($arrayref) = @_;
 4086:   my $result='__ARRAY_REF__';
 4087:   foreach my $elem (@$arrayref) {
 4088:     if(ref($elem) eq 'ARRAY') {
 4089:       $result.=&arrayref2str($elem).'&';
 4090:     } elsif(ref($elem) eq 'HASH') {
 4091:       $result.=&hashref2str($elem).'&';
 4092:     } elsif(ref($elem)) {
 4093:       #print("Got a ref of ".(ref($elem))." skipping.");
 4094:     } else {
 4095:       $result.=&escape($elem).'&';
 4096:     }
 4097:   }
 4098:   $result=~s/\&$//;
 4099:   $result .= '__END_ARRAY_REF__';
 4100:   return $result;
 4101: }
 4102: 
 4103: sub hash2str {
 4104:   my (%hash) = @_;
 4105:   my $result=&hashref2str(\%hash);
 4106:   $result=~s/^__HASH_REF__//;
 4107:   $result=~s/__END_HASH_REF__$//;
 4108:   return $result;
 4109: }
 4110: 
 4111: sub hashref2str {
 4112:   my ($hashref)=@_;
 4113:   my $result='__HASH_REF__';
 4114:   foreach my $key (sort(keys(%$hashref))) {
 4115:     if (ref($key) eq 'ARRAY') {
 4116:       $result.=&arrayref2str($key).'=';
 4117:     } elsif (ref($key) eq 'HASH') {
 4118:       $result.=&hashref2str($key).'=';
 4119:     } elsif (ref($key)) {
 4120:       $result.='=';
 4121:       #print("Got a ref of ".(ref($key))." skipping.");
 4122:     } else {
 4123: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 4124:     }
 4125: 
 4126:     if(ref($hashref->{$key}) eq 'ARRAY') {
 4127:       $result.=&arrayref2str($hashref->{$key}).'&';
 4128:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 4129:       $result.=&hashref2str($hashref->{$key}).'&';
 4130:     } elsif(ref($hashref->{$key})) {
 4131:        $result.='&';
 4132:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 4133:     } else {
 4134:       $result.=&escape($hashref->{$key}).'&';
 4135:     }
 4136:   }
 4137:   $result=~s/\&$//;
 4138:   $result .= '__END_HASH_REF__';
 4139:   return $result;
 4140: }
 4141: 
 4142: sub str2hash {
 4143:     my ($string)=@_;
 4144:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 4145:     return %$hash;
 4146: }
 4147: 
 4148: sub str2hashref {
 4149:   my ($string) = @_;
 4150: 
 4151:   my %hash;
 4152: 
 4153:   if($string !~ /^__HASH_REF__/) {
 4154:       if (! ($string eq '' || !defined($string))) {
 4155: 	  $hash{'error'}='Not hash reference';
 4156:       }
 4157:       return (\%hash, $string);
 4158:   }
 4159: 
 4160:   $string =~ s/^__HASH_REF__//;
 4161: 
 4162:   while($string !~ /^__END_HASH_REF__/) {
 4163:       #key
 4164:       my $key='';
 4165:       if($string =~ /^__HASH_REF__/) {
 4166:           ($key, $string)=&str2hashref($string);
 4167:           if(defined($key->{'error'})) {
 4168:               $hash{'error'}='Bad data';
 4169:               return (\%hash, $string);
 4170:           }
 4171:       } elsif($string =~ /^__ARRAY_REF__/) {
 4172:           ($key, $string)=&str2arrayref($string);
 4173:           if($key->[0] eq 'Array reference error') {
 4174:               $hash{'error'}='Bad data';
 4175:               return (\%hash, $string);
 4176:           }
 4177:       } else {
 4178:           $string =~ s/^(.*?)=//;
 4179: 	  $key=&unescape($1);
 4180:       }
 4181:       $string =~ s/^=//;
 4182: 
 4183:       #value
 4184:       my $value='';
 4185:       if($string =~ /^__HASH_REF__/) {
 4186:           ($value, $string)=&str2hashref($string);
 4187:           if(defined($value->{'error'})) {
 4188:               $hash{'error'}='Bad data';
 4189:               return (\%hash, $string);
 4190:           }
 4191:       } elsif($string =~ /^__ARRAY_REF__/) {
 4192:           ($value, $string)=&str2arrayref($string);
 4193:           if($value->[0] eq 'Array reference error') {
 4194:               $hash{'error'}='Bad data';
 4195:               return (\%hash, $string);
 4196:           }
 4197:       } else {
 4198: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 4199:       }
 4200:       $string =~ s/^&//;
 4201: 
 4202:       $hash{$key}=$value;
 4203:   }
 4204: 
 4205:   $string =~ s/^__END_HASH_REF__//;
 4206: 
 4207:   return (\%hash, $string);
 4208: }
 4209: 
 4210: sub str2array {
 4211:     my ($string)=@_;
 4212:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 4213:     return @$array;
 4214: }
 4215: 
 4216: sub str2arrayref {
 4217:   my ($string) = @_;
 4218:   my @array;
 4219: 
 4220:   if($string !~ /^__ARRAY_REF__/) {
 4221:       if (! ($string eq '' || !defined($string))) {
 4222: 	  $array[0]='Array reference error';
 4223:       }
 4224:       return (\@array, $string);
 4225:   }
 4226: 
 4227:   $string =~ s/^__ARRAY_REF__//;
 4228: 
 4229:   while($string !~ /^__END_ARRAY_REF__/) {
 4230:       my $value='';
 4231:       if($string =~ /^__HASH_REF__/) {
 4232:           ($value, $string)=&str2hashref($string);
 4233:           if(defined($value->{'error'})) {
 4234:               $array[0] ='Array reference error';
 4235:               return (\@array, $string);
 4236:           }
 4237:       } elsif($string =~ /^__ARRAY_REF__/) {
 4238:           ($value, $string)=&str2arrayref($string);
 4239:           if($value->[0] eq 'Array reference error') {
 4240:               $array[0] ='Array reference error';
 4241:               return (\@array, $string);
 4242:           }
 4243:       } else {
 4244: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 4245:       }
 4246:       $string =~ s/^&//;
 4247: 
 4248:       push(@array, $value);
 4249:   }
 4250: 
 4251:   $string =~ s/^__END_ARRAY_REF__//;
 4252: 
 4253:   return (\@array, $string);
 4254: }
 4255: 
 4256: # -------------------------------------------------------------------Temp Store
 4257: 
 4258: sub tmpreset {
 4259:   my ($symb,$namespace,$domain,$stuname) = @_;
 4260:   if (!$symb) {
 4261:     $symb=&symbread();
 4262:     if (!$symb) { $symb= $env{'request.url'}; }
 4263:   }
 4264:   $symb=escape($symb);
 4265: 
 4266:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4267:   $namespace=~s/\//\_/g;
 4268:   $namespace=~s/\W//g;
 4269: 
 4270:   if (!$domain) { $domain=$env{'user.domain'}; }
 4271:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4272:   if ($domain eq 'public' && $stuname eq 'public') {
 4273:       $stuname=$ENV{'REMOTE_ADDR'};
 4274:   }
 4275:   my $path=LONCAPA::tempdir();
 4276:   my %hash;
 4277:   if (tie(%hash,'GDBM_File',
 4278: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4279: 	  &GDBM_WRCREAT(),0640)) {
 4280:     foreach my $key (keys(%hash)) {
 4281:       if ($key=~ /:$symb/) {
 4282: 	delete($hash{$key});
 4283:       }
 4284:     }
 4285:   }
 4286: }
 4287: 
 4288: sub tmpstore {
 4289:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4290: 
 4291:   if (!$symb) {
 4292:     $symb=&symbread();
 4293:     if (!$symb) { $symb= $env{'request.url'}; }
 4294:   }
 4295:   $symb=escape($symb);
 4296: 
 4297:   if (!$namespace) {
 4298:     # I don't think we would ever want to store this for a course.
 4299:     # it seems this will only be used if we don't have a course.
 4300:     #$namespace=$env{'request.course.id'};
 4301:     #if (!$namespace) {
 4302:       $namespace=$env{'request.state'};
 4303:     #}
 4304:   }
 4305:   $namespace=~s/\//\_/g;
 4306:   $namespace=~s/\W//g;
 4307:   if (!$domain) { $domain=$env{'user.domain'}; }
 4308:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4309:   if ($domain eq 'public' && $stuname eq 'public') {
 4310:       $stuname=$ENV{'REMOTE_ADDR'};
 4311:   }
 4312:   my $now=time;
 4313:   my %hash;
 4314:   my $path=LONCAPA::tempdir();
 4315:   if (tie(%hash,'GDBM_File',
 4316: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4317: 	  &GDBM_WRCREAT(),0640)) {
 4318:     $hash{"version:$symb"}++;
 4319:     my $version=$hash{"version:$symb"};
 4320:     my $allkeys=''; 
 4321:     foreach my $key (keys(%$storehash)) {
 4322:       $allkeys.=$key.':';
 4323:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 4324:     }
 4325:     $hash{"$version:$symb:timestamp"}=$now;
 4326:     $allkeys.='timestamp';
 4327:     $hash{"$version:keys:$symb"}=$allkeys;
 4328:     if (untie(%hash)) {
 4329:       return 'ok';
 4330:     } else {
 4331:       return "error:$!";
 4332:     }
 4333:   } else {
 4334:     return "error:$!";
 4335:   }
 4336: }
 4337: 
 4338: # -----------------------------------------------------------------Temp Restore
 4339: 
 4340: sub tmprestore {
 4341:   my ($symb,$namespace,$domain,$stuname) = @_;
 4342: 
 4343:   if (!$symb) {
 4344:     $symb=&symbread();
 4345:     if (!$symb) { $symb= $env{'request.url'}; }
 4346:   }
 4347:   $symb=escape($symb);
 4348: 
 4349:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4350: 
 4351:   if (!$domain) { $domain=$env{'user.domain'}; }
 4352:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4353:   if ($domain eq 'public' && $stuname eq 'public') {
 4354:       $stuname=$ENV{'REMOTE_ADDR'};
 4355:   }
 4356:   my %returnhash;
 4357:   $namespace=~s/\//\_/g;
 4358:   $namespace=~s/\W//g;
 4359:   my %hash;
 4360:   my $path=LONCAPA::tempdir();
 4361:   if (tie(%hash,'GDBM_File',
 4362: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4363: 	  &GDBM_READER(),0640)) {
 4364:     my $version=$hash{"version:$symb"};
 4365:     $returnhash{'version'}=$version;
 4366:     my $scope;
 4367:     for ($scope=1;$scope<=$version;$scope++) {
 4368:       my $vkeys=$hash{"$scope:keys:$symb"};
 4369:       my @keys=split(/:/,$vkeys);
 4370:       my $key;
 4371:       $returnhash{"$scope:keys"}=$vkeys;
 4372:       foreach $key (@keys) {
 4373: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4374: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4375:       }
 4376:     }
 4377:     if (!(untie(%hash))) {
 4378:       return "error:$!";
 4379:     }
 4380:   } else {
 4381:     return "error:$!";
 4382:   }
 4383:   return %returnhash;
 4384: }
 4385: 
 4386: # ----------------------------------------------------------------------- Store
 4387: 
 4388: sub store {
 4389:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4390:     my $home='';
 4391: 
 4392:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4393: 
 4394:     $symb=&symbclean($symb);
 4395:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 4396: 
 4397:     if (!$domain) { $domain=$env{'user.domain'}; }
 4398:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4399: 
 4400:     &devalidate($symb,$stuname,$domain);
 4401: 
 4402:     $symb=escape($symb);
 4403:     if (!$namespace) { 
 4404:        unless ($namespace=$env{'request.course.id'}) { 
 4405:           return ''; 
 4406:        } 
 4407:     }
 4408:     if (!$home) { $home=$env{'user.home'}; }
 4409: 
 4410:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 4411:     $$storehash{'host'}=$perlvar{'lonHostID'};
 4412: 
 4413:     my $namevalue='';
 4414:     foreach my $key (keys(%$storehash)) {
 4415:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4416:     }
 4417:     $namevalue=~s/\&$//;
 4418:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 4419:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 4420: }
 4421: 
 4422: # -------------------------------------------------------------- Critical Store
 4423: 
 4424: sub cstore {
 4425:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4426:     my $home='';
 4427: 
 4428:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4429: 
 4430:     $symb=&symbclean($symb);
 4431:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 4432: 
 4433:     if (!$domain) { $domain=$env{'user.domain'}; }
 4434:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4435: 
 4436:     &devalidate($symb,$stuname,$domain);
 4437: 
 4438:     $symb=escape($symb);
 4439:     if (!$namespace) { 
 4440:        unless ($namespace=$env{'request.course.id'}) { 
 4441:           return ''; 
 4442:        } 
 4443:     }
 4444:     if (!$home) { $home=$env{'user.home'}; }
 4445: 
 4446:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 4447:     $$storehash{'host'}=$perlvar{'lonHostID'};
 4448: 
 4449:     my $namevalue='';
 4450:     foreach my $key (keys(%$storehash)) {
 4451:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4452:     }
 4453:     $namevalue=~s/\&$//;
 4454:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 4455:     return critical
 4456:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 4457: }
 4458: 
 4459: # --------------------------------------------------------------------- Restore
 4460: 
 4461: sub restore {
 4462:     my ($symb,$namespace,$domain,$stuname) = @_;
 4463:     my $home='';
 4464: 
 4465:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4466: 
 4467:     if (!$symb) {
 4468:       unless ($symb=escape(&symbread())) { return ''; }
 4469:     } else {
 4470:       $symb=&escape(&symbclean($symb));
 4471:     }
 4472:     if (!$namespace) { 
 4473:        unless ($namespace=$env{'request.course.id'}) { 
 4474:           return ''; 
 4475:        } 
 4476:     }
 4477:     if (!$domain) { $domain=$env{'user.domain'}; }
 4478:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4479:     if (!$home) { $home=$env{'user.home'}; }
 4480:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 4481: 
 4482:     my %returnhash=();
 4483:     foreach my $line (split(/\&/,$answer)) {
 4484: 	my ($name,$value)=split(/\=/,$line);
 4485:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 4486:     }
 4487:     my $version;
 4488:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 4489:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 4490:           $returnhash{$item}=$returnhash{$version.':'.$item};
 4491:        }
 4492:     }
 4493:     return %returnhash;
 4494: }
 4495: 
 4496: # ---------------------------------------------------------- Course Description
 4497: #
 4498: #  
 4499: 
 4500: sub coursedescription {
 4501:     my ($courseid,$args)=@_;
 4502:     $courseid=~s/^\///;
 4503:     $courseid=~s/\_/\//g;
 4504:     my ($cdomain,$cnum)=split(/\//,$courseid);
 4505:     my $chome=&homeserver($cnum,$cdomain);
 4506:     my $normalid=$cdomain.'_'.$cnum;
 4507:     # need to always cache even if we get errors otherwise we keep 
 4508:     # trying and trying and trying to get the course description.
 4509:     my %envhash=();
 4510:     my %returnhash=();
 4511:     
 4512:     my $expiretime=600;
 4513:     if ($env{'request.course.id'} eq $normalid) {
 4514: 	$expiretime=120;
 4515:     }
 4516: 
 4517:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 4518:     if (!$args->{'freshen_cache'}
 4519: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 4520: 	foreach my $key (keys(%env)) {
 4521: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 4522: 	    my ($setting) = $1;
 4523: 	    $returnhash{$setting} = $env{$key};
 4524: 	}
 4525: 	return %returnhash;
 4526:     }
 4527: 
 4528:     # get the data again
 4529: 
 4530:     if (!$args->{'one_time'}) {
 4531: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 4532:     }
 4533: 
 4534:     if ($chome ne 'no_host') {
 4535:        %returnhash=&dump('environment',$cdomain,$cnum);
 4536:        if (!exists($returnhash{'con_lost'})) {
 4537: 	   my $username = $env{'user.name'}; # Defult username
 4538: 	   if(defined $args->{'user'}) {
 4539: 	       $username = $args->{'user'};
 4540: 	   }
 4541:            $returnhash{'home'}= $chome;
 4542: 	   $returnhash{'domain'} = $cdomain;
 4543: 	   $returnhash{'num'} = $cnum;
 4544:            if (!defined($returnhash{'type'})) {
 4545:                $returnhash{'type'} = 'Course';
 4546:            }
 4547:            while (my ($name,$value) = each %returnhash) {
 4548:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 4549:            }
 4550:            $returnhash{'url'}=&clutter($returnhash{'url'});
 4551:            $returnhash{'fn'}=LONCAPA::tempdir() .
 4552: 	       $username.'_'.$cdomain.'_'.$cnum;
 4553:            $envhash{'course.'.$normalid.'.home'}=$chome;
 4554:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 4555:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 4556:        }
 4557:     }
 4558:     if (!$args->{'one_time'}) {
 4559: 	&appenv(\%envhash);
 4560:     }
 4561:     return %returnhash;
 4562: }
 4563: 
 4564: sub update_released_required {
 4565:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 4566:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 4567:         $cid = $env{'request.course.id'};
 4568:         $cdom = $env{'course.'.$cid.'.domain'};
 4569:         $cnum = $env{'course.'.$cid.'.num'};
 4570:         $chome = $env{'course.'.$cid.'.home'};
 4571:     }
 4572:     if ($needsrelease) {
 4573:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 4574:         my $needsupdate;
 4575:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 4576:             $needsupdate = 1;
 4577:         } else {
 4578:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 4579:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 4580:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 4581:                 $needsupdate = 1;
 4582:             }
 4583:         }
 4584:         if ($needsupdate) {
 4585:             my %needshash = (
 4586:                              'internal.releaserequired' => $needsrelease,
 4587:                             );
 4588:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 4589:             if ($putresult eq 'ok') {
 4590:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 4591:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 4592:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 4593:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 4594:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 4595:                 }
 4596:             }
 4597:         }
 4598:     }
 4599:     return;
 4600: }
 4601: 
 4602: # -------------------------------------------------See if a user is privileged
 4603: 
 4604: sub privileged {
 4605:     my ($username,$domain)=@_;
 4606: 
 4607:     my %rolesdump = &dump("roles", $domain, $username) or return 0;
 4608:     my $now = time;
 4609: 
 4610:     for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
 4611:             my ($trole, $tend, $tstart) = split(/_/, $role);
 4612:             if (($trole eq 'dc') || ($trole eq 'su')) {
 4613:                 return 1 unless ($tend && $tend < $now) 
 4614:                     or ($tstart && $tstart > $now);
 4615:             }
 4616: 	}
 4617: 
 4618:     return 0;
 4619: }
 4620: 
 4621: # -------------------------------------------------------- Get user privileges
 4622: 
 4623: sub rolesinit {
 4624:     my ($domain, $username) = @_;
 4625:     my %userroles = ('user.login.time' => time);
 4626:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 4627: 
 4628:     # firstaccess and timerinterval are related to timed maps/resources. 
 4629:     # also, blocking can be triggered by an activating timer
 4630:     # it's saved in the user's %env.
 4631:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 4632:     my %timerinterval = &dump('timerinterval', $domain, $username);
 4633:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 4634:         %timerintchk, %timerintenv);
 4635: 
 4636:     foreach my $key (keys(%firstaccess)) {
 4637:         my ($cid, $rest) = split(/\0/, $key);
 4638:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 4639:     }
 4640: 
 4641:     foreach my $key (keys(%timerinterval)) {
 4642:         my ($cid,$rest) = split(/\0/,$key);
 4643:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 4644:     }
 4645: 
 4646:     my %allroles=();
 4647:     my %allgroups=();
 4648: 
 4649:     for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
 4650:         my $role = $rolesdump{$area};
 4651:         $area =~ s/\_\w\w$//;
 4652: 
 4653:         my ($trole, $tend, $tstart, $group_privs);
 4654: 
 4655:         if ($role =~ /^cr/) {
 4656:         # Custom role, defined by a user 
 4657:         # e.g., user.role.cr/msu/smith/mynewrole
 4658:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 4659:                 $trole = $1;
 4660:                 ($tend, $tstart) = split('_', $2);
 4661:             } else {
 4662:                 $trole = $role;
 4663:             }
 4664:         } elsif ($role =~ m|^gr/|) {
 4665:         # Role of member in a group, defined within a course/community
 4666:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 4667:             ($trole, $tend, $tstart) = split(/_/, $role);
 4668:             next if $tstart eq '-1';
 4669:             ($trole, $group_privs) = split(/\//, $trole);
 4670:             $group_privs = &unescape($group_privs);
 4671:         } else {
 4672:         # Just a normal role, defined in roles.tab
 4673:             ($trole, $tend, $tstart) = split(/_/,$role);
 4674:         }
 4675: 
 4676:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 4677:                  $username);
 4678:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 4679: 
 4680:         # role expired or not available yet?
 4681:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 4682:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 4683: 
 4684:         next if $area eq '' or $trole eq '';
 4685: 
 4686:         my $spec = "$trole.$area";
 4687:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 4688: 
 4689:         if ($trole =~ /^cr\//) {
 4690:         # Custom role, defined by a user
 4691:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 4692:         } elsif ($trole eq 'gr') {
 4693:         # Role of a member in a group, defined within a course/community
 4694:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 4695:             next;
 4696:         } else {
 4697:         # Normal role, defined in roles.tab
 4698:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 4699:         }
 4700: 
 4701:         my $cid = $tdomain.'_'.$trest;
 4702:         unless ($firstaccchk{$cid}) {
 4703:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 4704:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 4705:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 4706:                         $coursetimerstarts{$cid}{$item}; 
 4707:                 }
 4708:             }
 4709:             $firstaccchk{$cid} = 1;
 4710:         }
 4711:         unless ($timerintchk{$cid}) {
 4712:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 4713:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 4714:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 4715:                        $coursetimerintervals{$cid}{$item};
 4716:                 }
 4717:             }
 4718:             $timerintchk{$cid} = 1;
 4719:         }
 4720:     }
 4721: 
 4722:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
 4723:         \%allroles, \%allgroups);
 4724:     $env{'user.adv'} = $userroles{'user.adv'};
 4725: 
 4726:     return (\%userroles,\%firstaccenv,\%timerintenv);
 4727: }
 4728: 
 4729: sub set_arearole {
 4730:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
 4731: # log the associated role with the area
 4732:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 4733:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 4734: }
 4735: 
 4736: sub custom_roleprivs {
 4737:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 4738:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 4739:     my $homsvr=homeserver($rauthor,$rdomain);
 4740:     if (&hostname($homsvr) ne '') {
 4741:         my ($rdummy,$roledef)=
 4742:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 4743:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 4744:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 4745:             if (defined($syspriv)) {
 4746:                 if ($trest =~ /^$match_community$/) {
 4747:                     $syspriv =~ s/bre\&S//; 
 4748:                 }
 4749:                 $$allroles{'cm./'}.=':'.$syspriv;
 4750:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 4751:             }
 4752:             if ($tdomain ne '') {
 4753:                 if (defined($dompriv)) {
 4754:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 4755:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 4756:                 }
 4757:                 if (($trest ne '') && (defined($coursepriv))) {
 4758:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 4759:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 4760:                 }
 4761:             }
 4762:         }
 4763:     }
 4764: }
 4765: 
 4766: sub group_roleprivs {
 4767:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 4768:     my $access = 1;
 4769:     my $now = time;
 4770:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 4771:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 4772:     if ($access) {
 4773:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 4774:         $$allgroups{$course}{$group} .=':'.$group_privs;
 4775:     }
 4776: }
 4777: 
 4778: sub standard_roleprivs {
 4779:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 4780:     if (defined($pr{$trole.':s'})) {
 4781:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 4782:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 4783:     }
 4784:     if ($tdomain ne '') {
 4785:         if (defined($pr{$trole.':d'})) {
 4786:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 4787:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 4788:         }
 4789:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 4790:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 4791:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 4792:         }
 4793:     }
 4794: }
 4795: 
 4796: sub set_userprivs {
 4797:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 4798:     my $author=0;
 4799:     my $adv=0;
 4800:     my %grouproles = ();
 4801:     if (keys(%{$allgroups}) > 0) {
 4802:         my @groupkeys; 
 4803:         foreach my $role (keys(%{$allroles})) {
 4804:             push(@groupkeys,$role);
 4805:         }
 4806:         if (ref($groups_roles) eq 'HASH') {
 4807:             foreach my $key (keys(%{$groups_roles})) {
 4808:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 4809:                     push(@groupkeys,$key);
 4810:                 }
 4811:             }
 4812:         }
 4813:         if (@groupkeys > 0) {
 4814:             foreach my $role (@groupkeys) {
 4815:                 my ($trole,$area,$sec,$extendedarea);
 4816:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 4817:                     $trole = $1;
 4818:                     $area = $2;
 4819:                     $sec = $3;
 4820:                     $extendedarea = $area.$sec;
 4821:                     if (exists($$allgroups{$area})) {
 4822:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 4823:                             my $spec = $trole.'.'.$extendedarea;
 4824:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 4825:                                                 $$allgroups{$area}{$group};
 4826:                         }
 4827:                     }
 4828:                 }
 4829:             }
 4830:         }
 4831:     }
 4832:     foreach my $group (keys(%grouproles)) {
 4833:         $$allroles{$group} = $grouproles{$group};
 4834:     }
 4835:     foreach my $role (keys(%{$allroles})) {
 4836:         my %thesepriv;
 4837:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 4838:         foreach my $item (split(/:/,$$allroles{$role})) {
 4839:             if ($item ne '') {
 4840:                 my ($privilege,$restrictions)=split(/&/,$item);
 4841:                 if ($restrictions eq '') {
 4842:                     $thesepriv{$privilege}='F';
 4843:                 } elsif ($thesepriv{$privilege} ne 'F') {
 4844:                     $thesepriv{$privilege}.=$restrictions;
 4845:                 }
 4846:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 4847:             }
 4848:         }
 4849:         my $thesestr='';
 4850:         foreach my $priv (sort(keys(%thesepriv))) {
 4851: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 4852: 	}
 4853:         $userroles->{'user.priv.'.$role} = $thesestr;
 4854:     }
 4855:     return ($author,$adv);
 4856: }
 4857: 
 4858: sub role_status {
 4859:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 4860:     my @pwhere = ();
 4861:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 4862:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
 4863:         unless (!defined($$role) || $$role eq '') {
 4864:             $$where=join('.',@pwhere);
 4865:             $$trolecode=$$role.'.'.$$where;
 4866:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 4867:             $$tstatus='is';
 4868:             if ($$tstart && $$tstart>$update) {
 4869:                 $$tstatus='future';
 4870:                 if ($$tstart<$now) {
 4871:                     if ($$tstart && $$tstart>$refresh) {
 4872:                         if (($$where ne '') && ($$role ne '')) {
 4873:                             my (%allroles,%allgroups,$group_privs,
 4874:                                 %groups_roles,@rolecodes);
 4875:                             my %userroles = (
 4876:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 4877:                             );
 4878:                             @rolecodes = ('cm'); 
 4879:                             my $spec=$$role.'.'.$$where;
 4880:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 4881:                             if ($$role =~ /^cr\//) {
 4882:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 4883:                                 push(@rolecodes,'cr');
 4884:                             } elsif ($$role eq 'gr') {
 4885:                                 push(@rolecodes,$$role);
 4886:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 4887:                                                     $env{'user.name'});
 4888:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 4889:                                 (undef,my $group_privs) = split(/\//,$trole);
 4890:                                 $group_privs = &unescape($group_privs);
 4891:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 4892:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 4893:                                 &get_groups_roles($tdomain,$trest,
 4894:                                                   \%course_roles,\@rolecodes,
 4895:                                                   \%groups_roles);
 4896:                             } else {
 4897:                                 push(@rolecodes,$$role);
 4898:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 4899:                             }
 4900:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
 4901:                             &appenv(\%userroles,\@rolecodes);
 4902:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 4903:                         }
 4904:                     }
 4905:                     $$tstatus = 'is';
 4906:                 }
 4907:             }
 4908:             if ($$tend) {
 4909:                 if ($$tend<$update) {
 4910:                     $$tstatus='expired';
 4911:                 } elsif ($$tend<$now) {
 4912:                     $$tstatus='will_not';
 4913:                 }
 4914:             }
 4915:         }
 4916:     }
 4917: }
 4918: 
 4919: sub get_groups_roles {
 4920:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 4921:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 4922:                   (ref($rolecodes) eq 'ARRAY') && 
 4923:                   (ref($groups_roles) eq 'HASH')); 
 4924:     if (keys(%{$cdom_courseroles}) > 0) {
 4925:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 4926:         if ($cdom ne '' && $cnum ne '') {
 4927:             foreach my $key (keys(%{$cdom_courseroles})) {
 4928:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 4929:                     my $crsrole = $1;
 4930:                     my $crssec = $2;
 4931:                     if ($crsrole =~ /^cr/) {
 4932:                         unless (grep(/^cr$/,@{$rolecodes})) {
 4933:                             push(@{$rolecodes},'cr');
 4934:                         }
 4935:                     } else {
 4936:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 4937:                             push(@{$rolecodes},$crsrole);
 4938:                         }
 4939:                     }
 4940:                     my $rolekey = "$crsrole./$cdom/$cnum";
 4941:                     if ($crssec ne '') {
 4942:                         $rolekey .= "/$crssec";
 4943:                     }
 4944:                     $rolekey .= './';
 4945:                     $groups_roles->{$rolekey} = $rolecodes;
 4946:                 }
 4947:             }
 4948:         }
 4949:     }
 4950:     return;
 4951: }
 4952: 
 4953: sub delete_env_groupprivs {
 4954:     my ($where,$courseroles,$possroles) = @_;
 4955:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 4956:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 4957:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 4958:         %{$courseroles->{$udom}} =
 4959:             &get_my_roles('','','userroles',['active'],
 4960:                           $possroles,[$udom],1);
 4961:     }
 4962:     if (ref($courseroles->{$udom}) eq 'HASH') {
 4963:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 4964:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 4965:             my $area = '/'.$cdom.'/'.$cnum;
 4966:             my $privkey = "user.priv.$crsrole.$area";
 4967:             if ($crssec ne '') {
 4968:                 $privkey .= '/'.$crssec;
 4969:             }
 4970:             $privkey .= ".$area/$group";
 4971:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 4972:         }
 4973:     }
 4974:     return;
 4975: }
 4976: 
 4977: sub check_adhoc_privs {
 4978:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
 4979:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 4980:     if ($env{$cckey}) {
 4981:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 4982:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 4983:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 4984:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 4985:         }
 4986:     } else {
 4987:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 4988:     }
 4989: }
 4990: 
 4991: sub set_adhoc_privileges {
 4992: # role can be cc or ca
 4993:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
 4994:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 4995:     my $spec = $role.'.'.$area;
 4996:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 4997:                                   $env{'user.name'});
 4998:     my %ccrole = ();
 4999:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
 5000:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
 5001:     &appenv(\%userroles,[$role,'cm']);
 5002:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 5003:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
 5004:         &appenv( {'request.role'        => $spec,
 5005:                   'request.role.domain' => $dcdom,
 5006:                   'request.course.sec'  => ''
 5007:                  }
 5008:                );
 5009:         my $tadv=0;
 5010:         if (&allowed('adv') eq 'F') { $tadv=1; }
 5011:         &appenv({'request.role.adv'    => $tadv});
 5012:     }
 5013: }
 5014: 
 5015: # --------------------------------------------------------------- get interface
 5016: 
 5017: sub get {
 5018:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5019:    my $items='';
 5020:    foreach my $item (@$storearr) {
 5021:        $items.=&escape($item).'&';
 5022:    }
 5023:    $items=~s/\&$//;
 5024:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5025:    if (!$uname) { $uname=$env{'user.name'}; }
 5026:    my $uhome=&homeserver($uname,$udomain);
 5027: 
 5028:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 5029:    my @pairs=split(/\&/,$rep);
 5030:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 5031:      return @pairs;
 5032:    }
 5033:    my %returnhash=();
 5034:    my $i=0;
 5035:    foreach my $item (@$storearr) {
 5036:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 5037:       $i++;
 5038:    }
 5039:    return %returnhash;
 5040: }
 5041: 
 5042: # --------------------------------------------------------------- del interface
 5043: 
 5044: sub del {
 5045:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5046:    my $items='';
 5047:    foreach my $item (@$storearr) {
 5048:        $items.=&escape($item).'&';
 5049:    }
 5050: 
 5051:    $items=~s/\&$//;
 5052:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5053:    if (!$uname) { $uname=$env{'user.name'}; }
 5054:    my $uhome=&homeserver($uname,$udomain);
 5055:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 5056: }
 5057: 
 5058: # -------------------------------------------------------------- dump interface
 5059: 
 5060: sub dump {
 5061:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 5062:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5063:     if (!$uname) { $uname=$env{'user.name'}; }
 5064:     my $uhome=&homeserver($uname,$udomain);
 5065: 
 5066:     if ($regexp) {
 5067: 	$regexp=&escape($regexp);
 5068:     } else {
 5069: 	$regexp='.';
 5070:     }
 5071:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 5072:     my @pairs=split(/\&/,$rep);
 5073:     my %returnhash=();
 5074:     if (!($rep =~ /^error/ )) {
 5075: 	foreach my $item (@pairs) {
 5076: 	    my ($key,$value)=split(/=/,$item,2);
 5077: 	    $key = &unescape($key);
 5078: 	    next if ($key =~ /^error: 2 /);
 5079: 	    $returnhash{$key}=&thaw_unescape($value);
 5080: 	}
 5081:     }
 5082:     return %returnhash;
 5083: }
 5084: 
 5085: 
 5086: # --------------------------------------------------------- dumpstore interface
 5087: 
 5088: sub dumpstore {
 5089:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 5090:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5091:    if (!$uname) { $uname=$env{'user.name'}; }
 5092:    my $uhome=&homeserver($uname,$udomain);
 5093:    if ($regexp) {
 5094:        $regexp=&escape($regexp);
 5095:    } else {
 5096:        $regexp='.';
 5097:    }
 5098:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 5099:    my @pairs=split(/\&/,$rep);
 5100:    my %returnhash=();
 5101:    foreach my $item (@pairs) {
 5102:        my ($key,$value)=split(/=/,$item,2);
 5103:        next if ($key =~ /^error: 2 /);
 5104:        $returnhash{$key}=&thaw_unescape($value);
 5105:    }
 5106:    return %returnhash;
 5107: }
 5108: 
 5109: # -------------------------------------------------------------- keys interface
 5110: 
 5111: sub getkeys {
 5112:    my ($namespace,$udomain,$uname)=@_;
 5113:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5114:    if (!$uname) { $uname=$env{'user.name'}; }
 5115:    my $uhome=&homeserver($uname,$udomain);
 5116:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 5117:    my @keyarray=();
 5118:    foreach my $key (split(/\&/,$rep)) {
 5119:       next if ($key =~ /^error: 2 /);
 5120:       push(@keyarray,&unescape($key));
 5121:    }
 5122:    return @keyarray;
 5123: }
 5124: 
 5125: # --------------------------------------------------------------- currentdump
 5126: sub currentdump {
 5127:    my ($courseid,$sdom,$sname)=@_;
 5128:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 5129:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 5130:    $sname    = $env{'user.name'}         if (! defined($sname));
 5131:    my $uhome = &homeserver($sname,$sdom);
 5132:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 5133:    return if ($rep =~ /^(error:|no_such_host)/);
 5134:    #
 5135:    my %returnhash=();
 5136:    #
 5137:    if ($rep eq "unknown_cmd") { 
 5138:        # an old lond will not know currentdump
 5139:        # Do a dump and make it look like a currentdump
 5140:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 5141:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 5142:        my %hash = @tmp;
 5143:        @tmp=();
 5144:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 5145:    } else {
 5146:        my @pairs=split(/\&/,$rep);
 5147:        foreach my $pair (@pairs) {
 5148:            my ($key,$value)=split(/=/,$pair,2);
 5149:            my ($symb,$param) = split(/:/,$key);
 5150:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 5151:                                                         &thaw_unescape($value);
 5152:        }
 5153:    }
 5154:    return %returnhash;
 5155: }
 5156: 
 5157: sub convert_dump_to_currentdump{
 5158:     my %hash = %{shift()};
 5159:     my %returnhash;
 5160:     # Code ripped from lond, essentially.  The only difference
 5161:     # here is the unescaping done by lonnet::dump().  Conceivably
 5162:     # we might run in to problems with parameter names =~ /^v\./
 5163:     while (my ($key,$value) = each(%hash)) {
 5164:         my ($v,$symb,$param) = split(/:/,$key);
 5165: 	$symb  = &unescape($symb);
 5166: 	$param = &unescape($param);
 5167:         next if ($v eq 'version' || $symb eq 'keys');
 5168:         next if (exists($returnhash{$symb}) &&
 5169:                  exists($returnhash{$symb}->{$param}) &&
 5170:                  $returnhash{$symb}->{'v.'.$param} > $v);
 5171:         $returnhash{$symb}->{$param}=$value;
 5172:         $returnhash{$symb}->{'v.'.$param}=$v;
 5173:     }
 5174:     #
 5175:     # Remove all of the keys in the hashes which keep track of
 5176:     # the version of the parameter.
 5177:     while (my ($symb,$param_hash) = each(%returnhash)) {
 5178:         # use a foreach because we are going to delete from the hash.
 5179:         foreach my $key (keys(%$param_hash)) {
 5180:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 5181:         }
 5182:     }
 5183:     return \%returnhash;
 5184: }
 5185: 
 5186: # ------------------------------------------------------ critical inc interface
 5187: 
 5188: sub cinc {
 5189:     return &inc(@_,'critical');
 5190: }
 5191: 
 5192: # --------------------------------------------------------------- inc interface
 5193: 
 5194: sub inc {
 5195:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 5196:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5197:     if (!$uname) { $uname=$env{'user.name'}; }
 5198:     my $uhome=&homeserver($uname,$udomain);
 5199:     my $items='';
 5200:     if (! ref($store)) {
 5201:         # got a single value, so use that instead
 5202:         $items = &escape($store).'=&';
 5203:     } elsif (ref($store) eq 'SCALAR') {
 5204:         $items = &escape($$store).'=&';        
 5205:     } elsif (ref($store) eq 'ARRAY') {
 5206:         $items = join('=&',map {&escape($_);} @{$store});
 5207:     } elsif (ref($store) eq 'HASH') {
 5208:         while (my($key,$value) = each(%{$store})) {
 5209:             $items.= &escape($key).'='.&escape($value).'&';
 5210:         }
 5211:     }
 5212:     $items=~s/\&$//;
 5213:     if ($critical) {
 5214: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 5215:     } else {
 5216: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 5217:     }
 5218: }
 5219: 
 5220: # --------------------------------------------------------------- put interface
 5221: 
 5222: sub put {
 5223:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5224:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5225:    if (!$uname) { $uname=$env{'user.name'}; }
 5226:    my $uhome=&homeserver($uname,$udomain);
 5227:    my $items='';
 5228:    foreach my $item (keys(%$storehash)) {
 5229:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5230:    }
 5231:    $items=~s/\&$//;
 5232:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5233: }
 5234: 
 5235: # ------------------------------------------------------------ newput interface
 5236: 
 5237: sub newput {
 5238:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5239:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5240:    if (!$uname) { $uname=$env{'user.name'}; }
 5241:    my $uhome=&homeserver($uname,$udomain);
 5242:    my $items='';
 5243:    foreach my $key (keys(%$storehash)) {
 5244:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 5245:    }
 5246:    $items=~s/\&$//;
 5247:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 5248: }
 5249: 
 5250: # ---------------------------------------------------------  putstore interface
 5251: 
 5252: sub putstore {
 5253:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 5254:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5255:    if (!$uname) { $uname=$env{'user.name'}; }
 5256:    my $uhome=&homeserver($uname,$udomain);
 5257:    my $items='';
 5258:    foreach my $key (keys(%$storehash)) {
 5259:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 5260:    }
 5261:    $items=~s/\&$//;
 5262:    my $esc_symb=&escape($symb);
 5263:    my $esc_v=&escape($version);
 5264:    my $reply =
 5265:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 5266: 	      $uhome);
 5267:    if ($reply eq 'unknown_cmd') {
 5268:        # gfall back to way things use to be done
 5269:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 5270: 			    $uname);
 5271:    }
 5272:    return $reply;
 5273: }
 5274: 
 5275: sub old_putstore {
 5276:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 5277:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5278:     if (!$uname) { $uname=$env{'user.name'}; }
 5279:     my $uhome=&homeserver($uname,$udomain);
 5280:     my %newstorehash;
 5281:     foreach my $item (keys(%$storehash)) {
 5282: 	my $key = $version.':'.&escape($symb).':'.$item;
 5283: 	$newstorehash{$key} = $storehash->{$item};
 5284:     }
 5285:     my $items='';
 5286:     my %allitems = ();
 5287:     foreach my $item (keys(%newstorehash)) {
 5288: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 5289: 	    my $key = $1.':keys:'.$2;
 5290: 	    $allitems{$key} .= $3.':';
 5291: 	}
 5292: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 5293:     }
 5294:     foreach my $item (keys(%allitems)) {
 5295: 	$allitems{$item} =~ s/\:$//;
 5296: 	$items.= $item.'='.$allitems{$item}.'&';
 5297:     }
 5298:     $items=~s/\&$//;
 5299:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5300: }
 5301: 
 5302: # ------------------------------------------------------ critical put interface
 5303: 
 5304: sub cput {
 5305:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5306:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5307:    if (!$uname) { $uname=$env{'user.name'}; }
 5308:    my $uhome=&homeserver($uname,$udomain);
 5309:    my $items='';
 5310:    foreach my $item (keys(%$storehash)) {
 5311:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5312:    }
 5313:    $items=~s/\&$//;
 5314:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 5315: }
 5316: 
 5317: # -------------------------------------------------------------- eget interface
 5318: 
 5319: sub eget {
 5320:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5321:    my $items='';
 5322:    foreach my $item (@$storearr) {
 5323:        $items.=&escape($item).'&';
 5324:    }
 5325:    $items=~s/\&$//;
 5326:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5327:    if (!$uname) { $uname=$env{'user.name'}; }
 5328:    my $uhome=&homeserver($uname,$udomain);
 5329:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 5330:    my @pairs=split(/\&/,$rep);
 5331:    my %returnhash=();
 5332:    my $i=0;
 5333:    foreach my $item (@$storearr) {
 5334:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 5335:       $i++;
 5336:    }
 5337:    return %returnhash;
 5338: }
 5339: 
 5340: # ------------------------------------------------------------ tmpput interface
 5341: sub tmpput {
 5342:     my ($storehash,$server,$context)=@_;
 5343:     my $items='';
 5344:     foreach my $item (keys(%$storehash)) {
 5345: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5346:     }
 5347:     $items=~s/\&$//;
 5348:     if (defined($context)) {
 5349:         $items .= ':'.&escape($context);
 5350:     }
 5351:     return &reply("tmpput:$items",$server);
 5352: }
 5353: 
 5354: # ------------------------------------------------------------ tmpget interface
 5355: sub tmpget {
 5356:     my ($token,$server)=@_;
 5357:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 5358:     my $rep=&reply("tmpget:$token",$server);
 5359:     my %returnhash;
 5360:     foreach my $item (split(/\&/,$rep)) {
 5361: 	my ($key,$value)=split(/=/,$item);
 5362:         next if ($key =~ /^error: 2 /);
 5363: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 5364:     }
 5365:     return %returnhash;
 5366: }
 5367: 
 5368: # ------------------------------------------------------------ tmpdel interface
 5369: sub tmpdel {
 5370:     my ($token,$server)=@_;
 5371:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 5372:     return &reply("tmpdel:$token",$server);
 5373: }
 5374: 
 5375: # -------------------------------------------------- portfolio access checking
 5376: 
 5377: sub portfolio_access {
 5378:     my ($requrl) = @_;
 5379:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 5380:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 5381:     if ($result) {
 5382:         my %setters;
 5383:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 5384:             my ($startblock,$endblock) =
 5385:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 5386:             if ($startblock && $endblock) {
 5387:                 return 'B';
 5388:             }
 5389:         } else {
 5390:             my ($startblock,$endblock) =
 5391:                 &Apache::loncommon::blockcheck(\%setters,'port');
 5392:             if ($startblock && $endblock) {
 5393:                 return 'B';
 5394:             }
 5395:         }
 5396:     }
 5397:     if ($result eq 'ok') {
 5398:        return 'F';
 5399:     } elsif ($result =~ /^[^:]+:guest_/) {
 5400:        return 'A';
 5401:     }
 5402:     return '';
 5403: }
 5404: 
 5405: sub get_portfolio_access {
 5406:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 5407: 
 5408:     if (!ref($access_hash)) {
 5409: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 5410: 	my %access_controls = &get_access_controls($current_perms,$group,
 5411: 						   $file_name);
 5412: 	$access_hash = $access_controls{$file_name};
 5413:     }
 5414: 
 5415:     my ($public,$guest,@domains,@users,@courses,@groups);
 5416:     my $now = time;
 5417:     if (ref($access_hash) eq 'HASH') {
 5418:         foreach my $key (keys(%{$access_hash})) {
 5419:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 5420:             if ($start > $now) {
 5421:                 next;
 5422:             }
 5423:             if ($end && $end<$now) {
 5424:                 next;
 5425:             }
 5426:             if ($scope eq 'public') {
 5427:                 $public = $key;
 5428:                 last;
 5429:             } elsif ($scope eq 'guest') {
 5430:                 $guest = $key;
 5431:             } elsif ($scope eq 'domains') {
 5432:                 push(@domains,$key);
 5433:             } elsif ($scope eq 'users') {
 5434:                 push(@users,$key);
 5435:             } elsif ($scope eq 'course') {
 5436:                 push(@courses,$key);
 5437:             } elsif ($scope eq 'group') {
 5438:                 push(@groups,$key);
 5439:             }
 5440:         }
 5441:         if ($public) {
 5442:             return 'ok';
 5443:         }
 5444:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 5445:             if ($guest) {
 5446:                 return $guest;
 5447:             }
 5448:         } else {
 5449:             if (@domains > 0) {
 5450:                 foreach my $domkey (@domains) {
 5451:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 5452:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 5453:                             return 'ok';
 5454:                         }
 5455:                     }
 5456:                 }
 5457:             }
 5458:             if (@users > 0) {
 5459:                 foreach my $userkey (@users) {
 5460:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 5461:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 5462:                             if (ref($item) eq 'HASH') {
 5463:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 5464:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 5465:                                     return 'ok';
 5466:                                 }
 5467:                             }
 5468:                         }
 5469:                     } 
 5470:                 }
 5471:             }
 5472:             my %roleshash;
 5473:             my @courses_and_groups = @courses;
 5474:             push(@courses_and_groups,@groups); 
 5475:             if (@courses_and_groups > 0) {
 5476:                 my (%allgroups,%allroles); 
 5477:                 my ($start,$end,$role,$sec,$group);
 5478:                 foreach my $envkey (%env) {
 5479:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 5480:                         my $cid = $2.'_'.$3; 
 5481:                         if ($1 eq 'gr') {
 5482:                             $group = $4;
 5483:                             $allgroups{$cid}{$group} = $env{$envkey};
 5484:                         } else {
 5485:                             if ($4 eq '') {
 5486:                                 $sec = 'none';
 5487:                             } else {
 5488:                                 $sec = $4;
 5489:                             }
 5490:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 5491:                         }
 5492:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 5493:                         my $cid = $2.'_'.$3;
 5494:                         if ($4 eq '') {
 5495:                             $sec = 'none';
 5496:                         } else {
 5497:                             $sec = $4;
 5498:                         }
 5499:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 5500:                     }
 5501:                 }
 5502:                 if (keys(%allroles) == 0) {
 5503:                     return;
 5504:                 }
 5505:                 foreach my $key (@courses_and_groups) {
 5506:                     my %content = %{$$access_hash{$key}};
 5507:                     my $cnum = $content{'number'};
 5508:                     my $cdom = $content{'domain'};
 5509:                     my $cid = $cdom.'_'.$cnum;
 5510:                     if (!exists($allroles{$cid})) {
 5511:                         next;
 5512:                     }    
 5513:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 5514:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 5515:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 5516:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 5517:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 5518:                         foreach my $role (keys(%{$allroles{$cid}})) {
 5519:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 5520:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 5521:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 5522:                                         if (grep/^all$/,@sections) {
 5523:                                             return 'ok';
 5524:                                         } else {
 5525:                                             if (grep/^$sec$/,@sections) {
 5526:                                                 return 'ok';
 5527:                                             }
 5528:                                         }
 5529:                                     }
 5530:                                 }
 5531:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 5532:                                     if (grep/^none$/,@groups) {
 5533:                                         return 'ok';
 5534:                                     }
 5535:                                 } else {
 5536:                                     if (grep/^all$/,@groups) {
 5537:                                         return 'ok';
 5538:                                     } 
 5539:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 5540:                                         if (grep/^$group$/,@groups) {
 5541:                                             return 'ok';
 5542:                                         }
 5543:                                     }
 5544:                                 } 
 5545:                             }
 5546:                         }
 5547:                     }
 5548:                 }
 5549:             }
 5550:             if ($guest) {
 5551:                 return $guest;
 5552:             }
 5553:         }
 5554:     }
 5555:     return;
 5556: }
 5557: 
 5558: sub course_group_datechecker {
 5559:     my ($dates,$now,$status) = @_;
 5560:     my ($start,$end) = split(/\./,$dates);
 5561:     if (!$start && !$end) {
 5562:         return 'ok';
 5563:     }
 5564:     if (grep/^active$/,@{$status}) {
 5565:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 5566:             return 'ok';
 5567:         }
 5568:     }
 5569:     if (grep/^previous$/,@{$status}) {
 5570:         if ($end > $now ) {
 5571:             return 'ok';
 5572:         }
 5573:     }
 5574:     if (grep/^future$/,@{$status}) {
 5575:         if ($start > $now) {
 5576:             return 'ok';
 5577:         }
 5578:     }
 5579:     return; 
 5580: }
 5581: 
 5582: sub parse_portfolio_url {
 5583:     my ($url) = @_;
 5584: 
 5585:     my ($type,$udom,$unum,$group,$file_name);
 5586:     
 5587:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 5588: 	$type = 1;
 5589:         $udom = $1;
 5590:         $unum = $2;
 5591:         $file_name = $3;
 5592:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 5593: 	$type = 2;
 5594:         $udom = $1;
 5595:         $unum = $2;
 5596:         $group = $3;
 5597:         $file_name = $3.'/'.$4;
 5598:     }
 5599:     if (wantarray) {
 5600: 	return ($type,$udom,$unum,$file_name,$group);
 5601:     }
 5602:     return $type;
 5603: }
 5604: 
 5605: sub is_portfolio_url {
 5606:     my ($url) = @_;
 5607:     return scalar(&parse_portfolio_url($url));
 5608: }
 5609: 
 5610: sub is_portfolio_file {
 5611:     my ($file) = @_;
 5612:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 5613:         return 1;
 5614:     }
 5615:     return;
 5616: }
 5617: 
 5618: sub usertools_access {
 5619:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 5620:     my ($access,%tools);
 5621:     if ($context eq '') {
 5622:         $context = 'tools';
 5623:     }
 5624:     if ($context eq 'requestcourses') {
 5625:         %tools = (
 5626:                       official   => 1,
 5627:                       unofficial => 1,
 5628:                       community  => 1,
 5629:                  );
 5630:     } else {
 5631:         %tools = (
 5632:                       aboutme   => 1,
 5633:                       blog      => 1,
 5634:                       portfolio => 1,
 5635:                  );
 5636:     }
 5637:     return if (!defined($tools{$tool}));
 5638: 
 5639:     if ((!defined($udom)) || (!defined($uname))) {
 5640:         $udom = $env{'user.domain'};
 5641:         $uname = $env{'user.name'};
 5642:     }
 5643: 
 5644:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 5645:         if ($action ne 'reload') {
 5646:             if ($context eq 'requestcourses') {
 5647:                 return $env{'environment.canrequest.'.$tool};
 5648:             } else {
 5649:                 return $env{'environment.availabletools.'.$tool};
 5650:             }
 5651:         }
 5652:     }
 5653: 
 5654:     my ($toolstatus,$inststatus);
 5655: 
 5656:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 5657:          ($action ne 'reload')) {
 5658:         $toolstatus = $env{'environment.'.$context.'.'.$tool};
 5659:         $inststatus = $env{'environment.inststatus'};
 5660:     } else {
 5661:         if (ref($userenvref) eq 'HASH') {
 5662:             $toolstatus = $userenvref->{$context.'.'.$tool};
 5663:             $inststatus = $userenvref->{'inststatus'};
 5664:         } else {
 5665:             my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
 5666:             $toolstatus = $userenv{$context.'.'.$tool};
 5667:             $inststatus = $userenv{'inststatus'};
 5668:         }
 5669:     }
 5670: 
 5671:     if ($toolstatus ne '') {
 5672:         if ($toolstatus) {
 5673:             $access = 1;
 5674:         } else {
 5675:             $access = 0;
 5676:         }
 5677:         return $access;
 5678:     }
 5679: 
 5680:     my ($is_adv,%domdef);
 5681:     if (ref($is_advref) eq 'HASH') {
 5682:         $is_adv = $is_advref->{'is_adv'};
 5683:     } else {
 5684:         $is_adv = &is_advanced_user($udom,$uname);
 5685:     }
 5686:     if (ref($domdefref) eq 'HASH') {
 5687:         %domdef = %{$domdefref};
 5688:     } else {
 5689:         %domdef = &get_domain_defaults($udom);
 5690:     }
 5691:     if (ref($domdef{$tool}) eq 'HASH') {
 5692:         if ($is_adv) {
 5693:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 5694:                 if ($domdef{$tool}{'_LC_adv'}) { 
 5695:                     $access = 1;
 5696:                 } else {
 5697:                     $access = 0;
 5698:                 }
 5699:                 return $access;
 5700:             }
 5701:         }
 5702:         if ($inststatus ne '') {
 5703:             my ($hasaccess,$hasnoaccess);
 5704:             foreach my $affiliation (split(/:/,$inststatus)) {
 5705:                 if ($domdef{$tool}{$affiliation} ne '') { 
 5706:                     if ($domdef{$tool}{$affiliation}) {
 5707:                         $hasaccess = 1;
 5708:                     } else {
 5709:                         $hasnoaccess = 1;
 5710:                     }
 5711:                 }
 5712:             }
 5713:             if ($hasaccess || $hasnoaccess) {
 5714:                 if ($hasaccess) {
 5715:                     $access = 1;
 5716:                 } elsif ($hasnoaccess) {
 5717:                     $access = 0; 
 5718:                 }
 5719:                 return $access;
 5720:             }
 5721:         } else {
 5722:             if ($domdef{$tool}{'default'} ne '') {
 5723:                 if ($domdef{$tool}{'default'}) {
 5724:                     $access = 1;
 5725:                 } elsif ($domdef{$tool}{'default'} == 0) {
 5726:                     $access = 0;
 5727:                 }
 5728:                 return $access;
 5729:             }
 5730:         }
 5731:     } else {
 5732:         if ($context eq 'tools') {
 5733:             $access = 1;
 5734:         } else {
 5735:             $access = 0;
 5736:         }
 5737:         return $access;
 5738:     }
 5739: }
 5740: 
 5741: sub is_course_owner {
 5742:     my ($cdom,$cnum,$udom,$uname) = @_;
 5743:     if (($udom eq '') || ($uname eq '')) {
 5744:         $udom = $env{'user.domain'};
 5745:         $uname = $env{'user.name'};
 5746:     }
 5747:     unless (($udom eq '') || ($uname eq '')) {
 5748:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 5749:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 5750:                 return 1;
 5751:             } else {
 5752:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 5753:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 5754:                     return 1;
 5755:                 }
 5756:             }
 5757:         }
 5758:     }
 5759:     return;
 5760: }
 5761: 
 5762: sub is_advanced_user {
 5763:     my ($udom,$uname) = @_;
 5764:     if ($udom ne '' && $uname ne '') {
 5765:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 5766:             if (wantarray) {
 5767:                 return ($env{'user.adv'},$env{'user.author'});
 5768:             } else {
 5769:                 return $env{'user.adv'};
 5770:             }
 5771:         }
 5772:     }
 5773:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 5774:     my %allroles;
 5775:     my ($is_adv,$is_author);
 5776:     foreach my $role (keys(%roleshash)) {
 5777:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 5778:         my $area = '/'.$tdomain.'/'.$trest;
 5779:         if ($sec ne '') {
 5780:             $area .= '/'.$sec;
 5781:         }
 5782:         if (($area ne '') && ($trole ne '')) {
 5783:             my $spec=$trole.'.'.$area;
 5784:             if ($trole =~ /^cr\//) {
 5785:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 5786:             } elsif ($trole ne 'gr') {
 5787:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 5788:             }
 5789:             if ($trole eq 'au') {
 5790:                 $is_author = 1;
 5791:             }
 5792:         }
 5793:     }
 5794:     foreach my $role (keys(%allroles)) {
 5795:         last if ($is_adv);
 5796:         foreach my $item (split(/:/,$allroles{$role})) {
 5797:             if ($item ne '') {
 5798:                 my ($privilege,$restrictions)=split(/&/,$item);
 5799:                 if ($privilege eq 'adv') {
 5800:                     $is_adv = 1;
 5801:                     last;
 5802:                 }
 5803:             }
 5804:         }
 5805:     }
 5806:     if (wantarray) {
 5807:         return ($is_adv,$is_author);
 5808:     }
 5809:     return $is_adv;
 5810: }
 5811: 
 5812: sub check_can_request {
 5813:     my ($dom,$can_request,$request_domains) = @_;
 5814:     my $canreq = 0;
 5815:     my ($types,$typename) = &Apache::loncommon::course_types();
 5816:     my @options = ('approval','validate','autolimit');
 5817:     my $optregex = join('|',@options);
 5818:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 5819:         foreach my $type (@{$types}) {
 5820:             if (&usertools_access($env{'user.name'},
 5821:                                   $env{'user.domain'},
 5822:                                   $type,undef,'requestcourses')) {
 5823:                 $canreq ++;
 5824:                 if (ref($request_domains) eq 'HASH') {
 5825:                     push(@{$request_domains->{$type}},$env{'user.domain'});
 5826:                 }
 5827:                 if ($dom eq $env{'user.domain'}) {
 5828:                     $can_request->{$type} = 1;
 5829:                 }
 5830:             }
 5831:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
 5832:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 5833:                 if (@curr > 0) {
 5834:                     foreach my $item (@curr) {
 5835:                         if (ref($request_domains) eq 'HASH') {
 5836:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 5837:                             if ($otherdom ne '') {
 5838:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 5839:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 5840:                                         push(@{$request_domains->{$type}},$otherdom);
 5841:                                     }
 5842:                                 } else {
 5843:                                     push(@{$request_domains->{$type}},$otherdom);
 5844:                                 }
 5845:                             }
 5846:                         }
 5847:                     }
 5848:                     unless($dom eq $env{'user.domain'}) {
 5849:                         $canreq ++;
 5850:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 5851:                             $can_request->{$type} = 1;
 5852:                         }
 5853:                     }
 5854:                 }
 5855:             }
 5856:         }
 5857:     }
 5858:     return $canreq;
 5859: }
 5860: 
 5861: # ---------------------------------------------- Custom access rule evaluation
 5862: 
 5863: sub customaccess {
 5864:     my ($priv,$uri)=@_;
 5865:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 5866:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 5867:     $udom = &LONCAPA::clean_domain($udom);
 5868:     $ucrs = &LONCAPA::clean_username($ucrs);
 5869:     my $access=0;
 5870:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 5871: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 5872: 	if ($type eq 'user') {
 5873: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 5874: 		my ($tdom,$tuname)=split(m{/},$scope);
 5875: 		if ($tdom) {
 5876: 		    if ($tdom ne $env{'user.domain'}) { next; }
 5877: 		}
 5878: 		if ($tuname) {
 5879: 		    if ($tuname ne $env{'user.name'}) { next; }
 5880: 		}
 5881: 		$access=($effect eq 'allow');
 5882: 		last;
 5883: 	    }
 5884: 	} else {
 5885: 	    if ($role) {
 5886: 		if ($role ne $urole) { next; }
 5887: 	    }
 5888: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 5889: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 5890: 		if ($tdom) {
 5891: 		    if ($tdom ne $udom) { next; }
 5892: 		}
 5893: 		if ($tcrs) {
 5894: 		    if ($tcrs ne $ucrs) { next; }
 5895: 		}
 5896: 		if ($tsec) {
 5897: 		    if ($tsec ne $usec) { next; }
 5898: 		}
 5899: 		$access=($effect eq 'allow');
 5900: 		last;
 5901: 	    }
 5902: 	    if ($realm eq '' && $role eq '') {
 5903: 		$access=($effect eq 'allow');
 5904: 	    }
 5905: 	}
 5906:     }
 5907:     return $access;
 5908: }
 5909: 
 5910: # ------------------------------------------------- Check for a user privilege
 5911: 
 5912: sub allowed {
 5913:     my ($priv,$uri,$symb,$role)=@_;
 5914:     my $ver_orguri=$uri;
 5915:     $uri=&deversion($uri);
 5916:     my $orguri=$uri;
 5917:     $uri=&declutter($uri);
 5918: 
 5919:     if ($priv eq 'evb') {
 5920: # Evade communication block restrictions for specified role in a course
 5921:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 5922:             return $1;
 5923:         } else {
 5924:             return;
 5925:         }
 5926:     }
 5927: 
 5928:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 5929: # Free bre access to adm and meta resources
 5930:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 5931: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 5932: 	&& ($priv eq 'bre')) {
 5933: 	return 'F';
 5934:     }
 5935: 
 5936: # Free bre access to user's own portfolio contents
 5937:     my ($space,$domain,$name,@dir)=split('/',$uri);
 5938:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 5939: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 5940:         my %setters;
 5941:         my ($startblock,$endblock) = 
 5942:             &Apache::loncommon::blockcheck(\%setters,'port');
 5943:         if ($startblock && $endblock) {
 5944:             return 'B';
 5945:         } else {
 5946:             return 'F';
 5947:         }
 5948:     }
 5949: 
 5950: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 5951:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 5952:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 5953:         if (exists($env{'request.course.id'})) {
 5954:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5955:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5956:             if (($domain eq $cdom) && ($name eq $cnum)) {
 5957:                 my $courseprivid=$env{'request.course.id'};
 5958:                 $courseprivid=~s/\_/\//;
 5959:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 5960:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 5961:                     return $1; 
 5962:                 } else {
 5963:                     if ($env{'request.course.sec'}) {
 5964:                         $courseprivid.='/'.$env{'request.course.sec'};
 5965:                     }
 5966:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 5967:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 5968:                         return $2;
 5969:                     }
 5970:                 }
 5971:             }
 5972:         }
 5973:     }
 5974: 
 5975: # Free bre to public access
 5976: 
 5977:     if ($priv eq 'bre') {
 5978:         my $copyright=&metadata($uri,'copyright');
 5979: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 5980:            return 'F'; 
 5981:         }
 5982:         if ($copyright eq 'priv') {
 5983:             $uri=~/([^\/]+)\/([^\/]+)\//;
 5984: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 5985: 		return '';
 5986:             }
 5987:         }
 5988:         if ($copyright eq 'domain') {
 5989:             $uri=~/([^\/]+)\/([^\/]+)\//;
 5990: 	    unless (($env{'user.domain'} eq $1) ||
 5991:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 5992: 		return '';
 5993:             }
 5994:         }
 5995:         if ($env{'request.role'}=~ /li\.\//) {
 5996:             # Library role, so allow browsing of resources in this domain.
 5997:             return 'F';
 5998:         }
 5999:         if ($copyright eq 'custom') {
 6000: 	    unless (&customaccess($priv,$uri)) { return ''; }
 6001:         }
 6002:     }
 6003:     # Domain coordinator is trying to create a course
 6004:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 6005:         # uri is the requested domain in this case.
 6006:         # comparison to 'request.role.domain' shows if the user has selected
 6007:         # a role of dc for the domain in question.
 6008:         return 'F' if ($uri eq $env{'request.role.domain'});
 6009:     }
 6010: 
 6011:     my $thisallowed='';
 6012:     my $statecond=0;
 6013:     my $courseprivid='';
 6014: 
 6015:     my $ownaccess;
 6016:     # Community Coordinator or Assistant Co-author browsing resource space.
 6017:     if (($priv eq 'bro') && ($env{'user.author'})) {
 6018:         if ($uri eq '') {
 6019:             $ownaccess = 1;
 6020:         } else {
 6021:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 6022:                 my $udom = $env{'user.domain'};
 6023:                 my $uname = $env{'user.name'};
 6024:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 6025:                     $ownaccess = 1;
 6026:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 6027:                     unless ($uri =~ m{\.\./}) {
 6028:                         $ownaccess = 1;
 6029:                     }
 6030:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 6031:                     my $now = time;
 6032:                     if ($uri =~ m{^([^/]+)/?$}) {
 6033:                         my $adom = $1;
 6034:                         foreach my $key (keys(%env)) {
 6035:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 6036:                                 my ($start,$end) = split('.',$env{$key});
 6037:                                 if (($now >= $start) && (!$end || $end < $now)) {
 6038:                                     $ownaccess = 1;
 6039:                                     last;
 6040:                                 }
 6041:                             }
 6042:                         }
 6043:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 6044:                         my $adom = $1;
 6045:                         my $aname = $2;
 6046:                         foreach my $role ('ca','aa') { 
 6047:                             if ($env{"user.role.$role./$adom/$aname"}) {
 6048:                                 my ($start,$end) =
 6049:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 6050:                                 if (($now >= $start) && (!$end || $end < $now)) {
 6051:                                     $ownaccess = 1;
 6052:                                     last;
 6053:                                 }
 6054:                             }
 6055:                         }
 6056:                     }
 6057:                 }
 6058:             }
 6059:         }
 6060:     }
 6061: 
 6062: # Course
 6063: 
 6064:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 6065:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6066:             $thisallowed.=$1;
 6067:         }
 6068:     }
 6069: 
 6070: # Domain
 6071: 
 6072:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 6073:        =~/\Q$priv\E\&([^\:]*)/) {
 6074:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6075:             $thisallowed.=$1;
 6076:         }
 6077:     }
 6078: 
 6079: # User who is not author or co-author might still be able to edit
 6080: # resource of an author in the domain (e.g., if Domain Coordinator).
 6081:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 6082:         (&allowed('mdc',$env{'request.course.id'}))) {
 6083:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 6084:             $thisallowed.=$1;
 6085:         }
 6086:     }
 6087: 
 6088: # Course: uri itself is a course
 6089:     my $courseuri=$uri;
 6090:     $courseuri=~s/\_(\d)/\/$1/;
 6091:     $courseuri=~s/^([^\/])/\/$1/;
 6092: 
 6093:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 6094:        =~/\Q$priv\E\&([^\:]*)/) {
 6095:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6096:             $thisallowed.=$1;
 6097:         }
 6098:     }
 6099: 
 6100: # URI is an uploaded document for this course, default permissions don't matter
 6101: # not allowing 'edit' access (editupload) to uploaded course docs
 6102:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 6103: 	$thisallowed='';
 6104:         my ($match)=&is_on_map($uri);
 6105:         if ($match) {
 6106:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 6107:                   =~/\Q$priv\E\&([^\:]*)/) {
 6108:                 my @blockers = &has_comm_blocking($priv,$symb,$uri);
 6109:                 if (@blockers > 0) {
 6110:                     $thisallowed = 'B';
 6111:                 } else {
 6112:                     $thisallowed.=$1;
 6113:                 }
 6114:             }
 6115:         } else {
 6116:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 6117:             if ($refuri) {
 6118:                 if ($refuri =~ m|^/adm/|) {
 6119:                     $thisallowed='F';
 6120:                 } else {
 6121:                     $refuri=&declutter($refuri);
 6122:                     my ($match) = &is_on_map($refuri);
 6123:                     if ($match) {
 6124:                         my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 6125:                         if (@blockers > 0) {
 6126:                             $thisallowed = 'B';
 6127:                         } else {
 6128:                             $thisallowed='F';
 6129:                         }
 6130:                     }
 6131:                 }
 6132:             }
 6133:         }
 6134:     }
 6135: 
 6136:     if ($priv eq 'bre'
 6137: 	&& $thisallowed ne 'F' 
 6138: 	&& $thisallowed ne '2'
 6139: 	&& &is_portfolio_url($uri)) {
 6140: 	$thisallowed = &portfolio_access($uri);
 6141:     }
 6142:     
 6143: # Full access at system, domain or course-wide level? Exit.
 6144:     if ($thisallowed=~/F/) {
 6145: 	return 'F';
 6146:     }
 6147: 
 6148: # If this is generating or modifying users, exit with special codes
 6149: 
 6150:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 6151: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 6152: 	    my ($audom,$auname)=split('/',$uri);
 6153: # no author name given, so this just checks on the general right to make a co-author in this domain
 6154: 	    unless ($auname) { return $thisallowed; }
 6155: # an author name is given, so we are about to actually make a co-author for a certain account
 6156: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 6157: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 6158: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 6159: 	}
 6160: 	return $thisallowed;
 6161:     }
 6162: #
 6163: # Gathered so far: system, domain and course wide privileges
 6164: #
 6165: # Course: See if uri or referer is an individual resource that is part of 
 6166: # the course
 6167: 
 6168:     if ($env{'request.course.id'}) {
 6169: 
 6170:        $courseprivid=$env{'request.course.id'};
 6171:        if ($env{'request.course.sec'}) {
 6172:           $courseprivid.='/'.$env{'request.course.sec'};
 6173:        }
 6174:        $courseprivid=~s/\_/\//;
 6175:        my $checkreferer=1;
 6176:        my ($match,$cond)=&is_on_map($uri);
 6177:        if ($match) {
 6178:            $statecond=$cond;
 6179:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 6180:                =~/\Q$priv\E\&([^\:]*)/) {
 6181:                my $value = $1;
 6182:                if ($priv eq 'bre') {
 6183:                    my @blockers = &has_comm_blocking($priv,$symb,$uri);
 6184:                    if (@blockers > 0) {
 6185:                        $thisallowed = 'B';
 6186:                    } else {
 6187:                        $thisallowed.=$value;
 6188:                    }
 6189:                } else {
 6190:                    $thisallowed.=$value;
 6191:                }
 6192:                $checkreferer=0;
 6193:            }
 6194:        }
 6195:        
 6196:        if ($checkreferer) {
 6197: 	  my $refuri=$env{'httpref.'.$orguri};
 6198:             unless ($refuri) {
 6199:                 foreach my $key (keys(%env)) {
 6200: 		    if ($key=~/^httpref\..*\*/) {
 6201: 			my $pattern=$key;
 6202:                         $pattern=~s/^httpref\.\/res\///;
 6203:                         $pattern=~s/\*/\[\^\/\]\+/g;
 6204:                         $pattern=~s/\//\\\//g;
 6205:                         if ($orguri=~/$pattern/) {
 6206: 			    $refuri=$env{$key};
 6207:                         }
 6208:                     }
 6209:                 }
 6210:             }
 6211: 
 6212:          if ($refuri) { 
 6213: 	  $refuri=&declutter($refuri);
 6214:           my ($match,$cond)=&is_on_map($refuri);
 6215:             if ($match) {
 6216:               my $refstatecond=$cond;
 6217:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 6218:                   =~/\Q$priv\E\&([^\:]*)/) {
 6219:                   my $value = $1;
 6220:                   if ($priv eq 'bre') {
 6221:                       my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 6222:                       if (@blockers > 0) {
 6223:                           $thisallowed = 'B';
 6224:                       } else {
 6225:                           $thisallowed.=$value;
 6226:                       }
 6227:                   } else {
 6228:                       $thisallowed.=$value;
 6229:                   }
 6230:                   $uri=$refuri;
 6231:                   $statecond=$refstatecond;
 6232:               }
 6233:           }
 6234:         }
 6235:        }
 6236:    }
 6237: 
 6238: #
 6239: # Gathered now: all privileges that could apply, and condition number
 6240: # 
 6241: #
 6242: # Full or no access?
 6243: #
 6244: 
 6245:     if ($thisallowed=~/F/) {
 6246: 	return 'F';
 6247:     }
 6248: 
 6249:     unless ($thisallowed) {
 6250:         return '';
 6251:     }
 6252: 
 6253: # Restrictions exist, deal with them
 6254: #
 6255: #   C:according to course preferences
 6256: #   R:according to resource settings
 6257: #   L:unless locked
 6258: #   X:according to user session state
 6259: #
 6260: 
 6261: # Possibly locked functionality, check all courses
 6262: # Locks might take effect only after 10 minutes cache expiration for other
 6263: # courses, and 2 minutes for current course
 6264: 
 6265:     my $envkey;
 6266:     if ($thisallowed=~/L/) {
 6267:         foreach $envkey (keys(%env)) {
 6268:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 6269:                my $courseid=$2;
 6270:                my $roleid=$1.'.'.$2;
 6271:                $courseid=~s/^\///;
 6272:                my $expiretime=600;
 6273:                if ($env{'request.role'} eq $roleid) {
 6274: 		  $expiretime=120;
 6275:                }
 6276: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 6277:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 6278:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 6279: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 6280:                }
 6281:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 6282:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 6283: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 6284:                        &log($env{'user.domain'},$env{'user.name'},
 6285:                             $env{'user.home'},
 6286:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 6287:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 6288:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 6289: 		       return '';
 6290:                    }
 6291:                }
 6292:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 6293:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 6294: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 6295:                        &log($env{'user.domain'},$env{'user.name'},
 6296:                             $env{'user.home'},
 6297:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 6298:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 6299:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 6300: 		       return '';
 6301:                    }
 6302:                }
 6303: 	   }
 6304:        }
 6305:     }
 6306:    
 6307: #
 6308: # Rest of the restrictions depend on selected course
 6309: #
 6310: 
 6311:     unless ($env{'request.course.id'}) {
 6312: 	if ($thisallowed eq 'A') {
 6313: 	    return 'A';
 6314:         } elsif ($thisallowed eq 'B') {
 6315:             return 'B';
 6316: 	} else {
 6317: 	    return '1';
 6318: 	}
 6319:     }
 6320: 
 6321: #
 6322: # Now user is definitely in a course
 6323: #
 6324: 
 6325: 
 6326: # Course preferences
 6327: 
 6328:    if ($thisallowed=~/C/) {
 6329:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 6330:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 6331:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 6332: 	   =~/\Q$rolecode\E/) {
 6333: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6334: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 6335: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 6336: 			$env{'request.course.id'});
 6337: 	   }
 6338:            return '';
 6339:        }
 6340: 
 6341:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 6342: 	   =~/\Q$unamedom\E/) {
 6343: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6344: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 6345: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 6346: 			$env{'request.course.id'});
 6347: 	   }
 6348:            return '';
 6349:        }
 6350:    }
 6351: 
 6352: # Resource preferences
 6353: 
 6354:    if ($thisallowed=~/R/) {
 6355:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 6356:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 6357: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6358: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 6359: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 6360: 	   }
 6361: 	   return '';
 6362:        }
 6363:    }
 6364: 
 6365: # Restricted by state or randomout?
 6366: 
 6367:    if ($thisallowed=~/X/) {
 6368:       if ($env{'acc.randomout'}) {
 6369: 	 if (!$symb) { $symb=&symbread($uri,1); }
 6370:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 6371:             return ''; 
 6372:          }
 6373:       }
 6374:       if (&condval($statecond)) {
 6375: 	 return '2';
 6376:       } else {
 6377:          return '';
 6378:       }
 6379:    }
 6380: 
 6381:     if ($thisallowed eq 'A') {
 6382: 	return 'A';
 6383:     } elsif ($thisallowed eq 'B') {
 6384:         return 'B';
 6385:     }
 6386:    return 'F';
 6387: }
 6388: 
 6389: sub get_comm_blocks {
 6390:     my ($cdom,$cnum) = @_;
 6391:     if ($cdom eq '' || $cnum eq '') {
 6392:         return unless ($env{'request.course.id'});
 6393:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6394:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6395:     }
 6396:     my %commblocks;
 6397:     my $hashid=$cdom.'_'.$cnum;
 6398:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 6399:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 6400:         %commblocks = %{$blocksref};
 6401:     } else {
 6402:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 6403:         my $cachetime = 600;
 6404:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 6405:     }
 6406:     return %commblocks;
 6407: }
 6408: 
 6409: sub has_comm_blocking {
 6410:     my ($priv,$symb,$uri,$blocks) = @_;
 6411:     return unless ($env{'request.course.id'});
 6412:     return unless ($priv eq 'bre');
 6413:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 6414:     my %commblocks;
 6415:     if (ref($blocks) eq 'HASH') {
 6416:         %commblocks = %{$blocks};
 6417:     } else {
 6418:         %commblocks = &get_comm_blocks();
 6419:     }
 6420:     return unless (keys(%commblocks) > 0);
 6421:     if (!$symb) { $symb=&symbread($uri,1); }
 6422:     my ($map,$resid,undef)=&decode_symb($symb);
 6423:     my %tocheck = (
 6424:                     maps      => $map,
 6425:                     resources => $symb,
 6426:                   );
 6427:     my @blockers;
 6428:     my $now = time;
 6429:     my $navmap = Apache::lonnavmaps::navmap->new();
 6430:     foreach my $block (keys(%commblocks)) {
 6431:         if ($block =~ /^(\d+)____(\d+)$/) {
 6432:             my ($start,$end) = ($1,$2);
 6433:             if ($start <= $now && $end >= $now) {
 6434:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 6435:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 6436:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 6437:                             if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
 6438:                                 unless (grep(/^\Q$block\E$/,@blockers)) {
 6439:                                     push(@blockers,$block);
 6440:                                 }
 6441:                             }
 6442:                         }
 6443:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 6444:                             if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
 6445:                                 unless (grep(/^\Q$block\E$/,@blockers)) {  
 6446:                                     push(@blockers,$block);
 6447:                                 }
 6448:                             }
 6449:                         }
 6450:                     }
 6451:                 }
 6452:             }
 6453:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 6454:             my $item = $1;
 6455:             my @to_test;
 6456:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 6457:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 6458:                     my $check_interval;
 6459:                     if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
 6460:                         my @interval;
 6461:                         my $type = 'map';
 6462:                         if ($item eq 'course') {
 6463:                             $type = 'course';
 6464:                             @interval=&EXT("resource.0.interval");
 6465:                         } else {
 6466:                             if ($item =~ /___\d+___/) {
 6467:                                 $type = 'resource';
 6468:                                 @interval=&EXT("resource.0.interval",$item);
 6469:                                 if (ref($navmap)) {                        
 6470:                                     my $res = $navmap->getBySymb($item); 
 6471:                                     push(@to_test,$res);
 6472:                                 }
 6473:                             } else {
 6474:                                 my $mapsymb = &symbread($item,1);
 6475:                                 if ($mapsymb) {
 6476:                                     if (ref($navmap)) {
 6477:                                         my $mapres = $navmap->getBySymb($mapsymb);
 6478:                                         @to_test = $mapres->retrieveResources($mapres,undef,0,1);
 6479:                                         foreach my $res (@to_test) {
 6480:                                             my $symb = $res->symb();
 6481:                                             next if ($symb eq $mapsymb);
 6482:                                             if ($symb ne '') {
 6483:                                                 @interval=&EXT("resource.0.interval",$symb);
 6484:                                                 last;
 6485:                                             }
 6486:                                         }
 6487:                                     }
 6488:                                 }
 6489:                             }
 6490:                         }
 6491:                         if ($interval[0] =~ /\d+/) {
 6492:                             my $first_access;
 6493:                             if ($type eq 'resource') {
 6494:                                 $first_access=&get_first_access($interval[1],$item);
 6495:                             } elsif ($type eq 'map') {
 6496:                                 $first_access=&get_first_access($interval[1],undef,$item);
 6497:                             } else {
 6498:                                 $first_access=&get_first_access($interval[1]);
 6499:                             }
 6500:                             if ($first_access) {
 6501:                                 my $timesup = $first_access+$interval[0];
 6502:                                 if ($timesup > $now) {
 6503:                                     foreach my $res (@to_test) {
 6504:                                         if ($res->is_problem()) {
 6505:                                             if ($res->completable()) {
 6506:                                                 unless (grep(/^\Q$block\E$/,@blockers)) {
 6507:                                                     push(@blockers,$block);
 6508:                                                 }
 6509:                                                 last;
 6510:                                             }
 6511:                                         }
 6512:                                     }
 6513:                                 }
 6514:                             }
 6515:                         }
 6516:                     }
 6517:                 }
 6518:             }
 6519:         }
 6520:     }
 6521:     return @blockers;
 6522: }
 6523: 
 6524: sub check_docs_block {
 6525:     my ($docsblock,$tocheck) =@_;
 6526:     if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
 6527:         return;
 6528:     }
 6529:     if (ref($docsblock->{'maps'}) eq 'HASH') {
 6530:         if ($tocheck->{'maps'}) {
 6531:             if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
 6532:                 return 1;
 6533:             }
 6534:         }
 6535:     }
 6536:     if (ref($docsblock->{'resources'}) eq 'HASH') {
 6537:         if ($tocheck->{'resources'}) {
 6538:             if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
 6539:                 return 1;
 6540:             }
 6541:         }
 6542:     }
 6543:     return;
 6544: }
 6545: 
 6546: #
 6547: #   Removes the versino from a URI and
 6548: #   splits it in to its filename and path to the filename.
 6549: #   Seems like File::Basename could have done this more clearly.
 6550: #   Parameters:
 6551: #      $uri   - input URI
 6552: #   Returns:
 6553: #     Two element list consisting of 
 6554: #     $pathname  - the URI up to and excluding the trailing /
 6555: #     $filename  - The part of the URI following the last /
 6556: #  NOTE:
 6557: #    Another realization of this is simply:
 6558: #    use File::Basename;
 6559: #    ...
 6560: #    $uri = shift;
 6561: #    $filename = basename($uri);
 6562: #    $path     = dirname($uri);
 6563: #    return ($filename, $path);
 6564: #
 6565: #     The implementation below is probably faster however.
 6566: #
 6567: sub split_uri_for_cond {
 6568:     my $uri=&deversion(&declutter(shift));
 6569:     my @uriparts=split(/\//,$uri);
 6570:     my $filename=pop(@uriparts);
 6571:     my $pathname=join('/',@uriparts);
 6572:     return ($pathname,$filename);
 6573: }
 6574: # --------------------------------------------------- Is a resource on the map?
 6575: 
 6576: sub is_on_map {
 6577:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 6578:     #Trying to find the conditional for the file
 6579:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 6580: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 6581:     if ($match) {
 6582: 	return (1,$1);
 6583:     } else {
 6584: 	return (0,0);
 6585:     }
 6586: }
 6587: 
 6588: # --------------------------------------------------------- Get symb from alias
 6589: 
 6590: sub get_symb_from_alias {
 6591:     my $symb=shift;
 6592:     my ($map,$resid,$url)=&decode_symb($symb);
 6593: # Already is a symb
 6594:     if ($url) { return $symb; }
 6595: # Must be an alias
 6596:     my $aliassymb='';
 6597:     my %bighash;
 6598:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6599:                             &GDBM_READER(),0640)) {
 6600:         my $rid=$bighash{'mapalias_'.$symb};
 6601: 	if ($rid) {
 6602: 	    my ($mapid,$resid)=split(/\./,$rid);
 6603: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 6604: 				    $resid,$bighash{'src_'.$rid});
 6605: 	}
 6606:         untie %bighash;
 6607:     }
 6608:     return $aliassymb;
 6609: }
 6610: 
 6611: # ----------------------------------------------------------------- Define Role
 6612: 
 6613: sub definerole {
 6614:   if (allowed('mcr','/')) {
 6615:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 6616:     foreach my $role (split(':',$sysrole)) {
 6617: 	my ($crole,$cqual)=split(/\&/,$role);
 6618:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 6619:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 6620: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 6621:                return "refused:s:$crole&$cqual"; 
 6622:             }
 6623:         }
 6624:     }
 6625:     foreach my $role (split(':',$domrole)) {
 6626: 	my ($crole,$cqual)=split(/\&/,$role);
 6627:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 6628:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 6629: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 6630:                return "refused:d:$crole&$cqual"; 
 6631:             }
 6632:         }
 6633:     }
 6634:     foreach my $role (split(':',$courole)) {
 6635: 	my ($crole,$cqual)=split(/\&/,$role);
 6636:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 6637:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 6638: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 6639:                return "refused:c:$crole&$cqual"; 
 6640:             }
 6641:         }
 6642:     }
 6643:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 6644:                 "$env{'user.domain'}:$env{'user.name'}:".
 6645: 	        "rolesdef_$rolename=".
 6646:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 6647:     return reply($command,$env{'user.home'});
 6648:   } else {
 6649:     return 'refused';
 6650:   }
 6651: }
 6652: 
 6653: # ---------------- Make a metadata query against the network of library servers
 6654: 
 6655: sub metadata_query {
 6656:     my ($query,$custom,$customshow,$server_array)=@_;
 6657:     my %rhash;
 6658:     my %libserv = &all_library();
 6659:     my @server_list = (defined($server_array) ? @$server_array
 6660:                                               : keys(%libserv) );
 6661:     for my $server (@server_list) {
 6662: 	unless ($custom or $customshow) {
 6663: 	    my $reply=&reply("querysend:".&escape($query),$server);
 6664: 	    $rhash{$server}=$reply;
 6665: 	}
 6666: 	else {
 6667: 	    my $reply=&reply("querysend:".&escape($query).':'.
 6668: 			     &escape($custom).':'.&escape($customshow),
 6669: 			     $server);
 6670: 	    $rhash{$server}=$reply;
 6671: 	}
 6672:     }
 6673:     return \%rhash;
 6674: }
 6675: 
 6676: # ----------------------------------------- Send log queries and wait for reply
 6677: 
 6678: sub log_query {
 6679:     my ($uname,$udom,$query,%filters)=@_;
 6680:     my $uhome=&homeserver($uname,$udom);
 6681:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 6682:     my $uhost=&hostname($uhome);
 6683:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 6684:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 6685:                        $uhome);
 6686:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 6687:     return get_query_reply($queryid);
 6688: }
 6689: 
 6690: # -------------------------- Update MySQL table for portfolio file
 6691: 
 6692: sub update_portfolio_table {
 6693:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 6694:     if ($group ne '') {
 6695:         $file_name =~s /^\Q$group\E//;
 6696:     }
 6697:     my $homeserver = &homeserver($uname,$udom);
 6698:     my $queryid=
 6699:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 6700:                ':'.&escape($file_name).':'.$action,$homeserver);
 6701:     my $reply = &get_query_reply($queryid);
 6702:     return $reply;
 6703: }
 6704: 
 6705: # -------------------------- Update MySQL allusers table
 6706: 
 6707: sub update_allusers_table {
 6708:     my ($uname,$udom,$names) = @_;
 6709:     my $homeserver = &homeserver($uname,$udom);
 6710:     my $queryid=
 6711:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 6712:                'lastname='.&escape($names->{'lastname'}).'%%'.
 6713:                'firstname='.&escape($names->{'firstname'}).'%%'.
 6714:                'middlename='.&escape($names->{'middlename'}).'%%'.
 6715:                'generation='.&escape($names->{'generation'}).'%%'.
 6716:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 6717:                'id='.&escape($names->{'id'}),$homeserver);
 6718:     return;
 6719: }
 6720: 
 6721: # ------- Request retrieval of institutional classlists for course(s)
 6722: 
 6723: sub fetch_enrollment_query {
 6724:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 6725:     my $homeserver;
 6726:     my $maxtries = 1;
 6727:     if ($context eq 'automated') {
 6728:         $homeserver = $perlvar{'lonHostID'};
 6729:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 6730:     } else {
 6731:         $homeserver = &homeserver($cnum,$dom);
 6732:     }
 6733:     my $host=&hostname($homeserver);
 6734:     my $cmd = '';
 6735:     foreach my $affiliate (keys(%{$affiliatesref})) {
 6736:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 6737:     }
 6738:     $cmd =~ s/%%$//;
 6739:     $cmd = &escape($cmd);
 6740:     my $query = 'fetchenrollment';
 6741:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 6742:     unless ($queryid=~/^\Q$host\E\_/) { 
 6743:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 6744:         return 'error: '.$queryid;
 6745:     }
 6746:     my $reply = &get_query_reply($queryid);
 6747:     my $tries = 1;
 6748:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 6749:         $reply = &get_query_reply($queryid);
 6750:         $tries ++;
 6751:     }
 6752:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 6753:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 6754:     } else {
 6755:         my @responses = split(/:/,$reply);
 6756:         if ($homeserver eq $perlvar{'lonHostID'}) {
 6757:             foreach my $line (@responses) {
 6758:                 my ($key,$value) = split(/=/,$line,2);
 6759:                 $$replyref{$key} = $value;
 6760:             }
 6761:         } else {
 6762:             my $pathname = LONCAPA::tempdir();
 6763:             foreach my $line (@responses) {
 6764:                 my ($key,$value) = split(/=/,$line);
 6765:                 $$replyref{$key} = $value;
 6766:                 if ($value > 0) {
 6767:                     foreach my $item (@{$$affiliatesref{$key}}) {
 6768:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 6769:                         my $destname = $pathname.'/'.$filename;
 6770:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 6771:                         if ($xml_classlist =~ /^error/) {
 6772:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 6773:                         } else {
 6774:                             if ( open(FILE,">$destname") ) {
 6775:                                 print FILE &unescape($xml_classlist);
 6776:                                 close(FILE);
 6777:                             } else {
 6778:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 6779:                             }
 6780:                         }
 6781:                     }
 6782:                 }
 6783:             }
 6784:         }
 6785:         return 'ok';
 6786:     }
 6787:     return 'error';
 6788: }
 6789: 
 6790: sub get_query_reply {
 6791:     my $queryid=shift;
 6792:     my $replyfile=LONCAPA::tempdir().$queryid;
 6793:     my $reply='';
 6794:     for (1..100) {
 6795: 	sleep 2;
 6796:         if (-e $replyfile.'.end') {
 6797: 	    if (open(my $fh,$replyfile)) {
 6798: 		$reply = join('',<$fh>);
 6799: 		close($fh);
 6800: 	   } else { return 'error: reply_file_error'; }
 6801:            return &unescape($reply);
 6802: 	}
 6803:     }
 6804:     return 'timeout:'.$queryid;
 6805: }
 6806: 
 6807: sub courselog_query {
 6808: #
 6809: # possible filters:
 6810: # url: url or symb
 6811: # username
 6812: # domain
 6813: # action: view, submit, grade
 6814: # start: timestamp
 6815: # end: timestamp
 6816: #
 6817:     my (%filters)=@_;
 6818:     unless ($env{'request.course.id'}) { return 'no_course'; }
 6819:     if ($filters{'url'}) {
 6820: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 6821:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 6822:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 6823:     }
 6824:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6825:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6826:     return &log_query($cname,$cdom,'courselog',%filters);
 6827: }
 6828: 
 6829: sub userlog_query {
 6830: #
 6831: # possible filters:
 6832: # action: log check role
 6833: # start: timestamp
 6834: # end: timestamp
 6835: #
 6836:     my ($uname,$udom,%filters)=@_;
 6837:     return &log_query($uname,$udom,'userlog',%filters);
 6838: }
 6839: 
 6840: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 6841: 
 6842: sub auto_run {
 6843:     my ($cnum,$cdom) = @_;
 6844:     my $response = 0;
 6845:     my $settings;
 6846:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 6847:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 6848:         $settings = $domconfig{'autoenroll'};
 6849:         if ($settings->{'run'} eq '1') {
 6850:             $response = 1;
 6851:         }
 6852:     } else {
 6853:         my $homeserver;
 6854:         if (&is_course($cdom,$cnum)) {
 6855:             $homeserver = &homeserver($cnum,$cdom);
 6856:         } else {
 6857:             $homeserver = &domain($cdom,'primary');
 6858:         }
 6859:         if ($homeserver ne 'no_host') {
 6860:             $response = &reply('autorun:'.$cdom,$homeserver);
 6861:         }
 6862:     }
 6863:     return $response;
 6864: }
 6865: 
 6866: sub auto_get_sections {
 6867:     my ($cnum,$cdom,$inst_coursecode) = @_;
 6868:     my $homeserver;
 6869:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 6870:         $homeserver = &homeserver($cnum,$cdom);
 6871:     }
 6872:     if (!defined($homeserver)) { 
 6873:         if ($cdom =~ /^$match_domain$/) {
 6874:             $homeserver = &domain($cdom,'primary');
 6875:         }
 6876:     }
 6877:     my @secs;
 6878:     if (defined($homeserver)) {
 6879:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 6880:         unless ($response eq 'refused') {
 6881:             @secs = split(/:/,$response);
 6882:         }
 6883:     }
 6884:     return @secs;
 6885: }
 6886: 
 6887: sub auto_new_course {
 6888:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 6889:     my $homeserver = &homeserver($cnum,$cdom);
 6890:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 6891:     return $response;
 6892: }
 6893: 
 6894: sub auto_validate_courseID {
 6895:     my ($cnum,$cdom,$inst_course_id) = @_;
 6896:     my $homeserver = &homeserver($cnum,$cdom);
 6897:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 6898:     return $response;
 6899: }
 6900: 
 6901: sub auto_validate_instcode {
 6902:     my ($cnum,$cdom,$instcode,$owner) = @_;
 6903:     my ($homeserver,$response);
 6904:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 6905:         $homeserver = &homeserver($cnum,$cdom);
 6906:     }
 6907:     if (!defined($homeserver)) {
 6908:         if ($cdom =~ /^$match_domain$/) {
 6909:             $homeserver = &domain($cdom,'primary');
 6910:         }
 6911:     }
 6912:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 6913:                         &escape($instcode).':'.&escape($owner),$homeserver));
 6914:     my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
 6915:     return ($outcome,$description);
 6916: }
 6917: 
 6918: sub auto_create_password {
 6919:     my ($cnum,$cdom,$authparam,$udom) = @_;
 6920:     my ($homeserver,$response);
 6921:     my $create_passwd = 0;
 6922:     my $authchk = '';
 6923:     if ($udom =~ /^$match_domain$/) {
 6924:         $homeserver = &domain($udom,'primary');
 6925:     }
 6926:     if ($homeserver eq '') {
 6927:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 6928:             $homeserver = &homeserver($cnum,$cdom);
 6929:         }
 6930:     }
 6931:     if ($homeserver eq '') {
 6932:         $authchk = 'nodomain';
 6933:     } else {
 6934:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 6935:         if ($response eq 'refused') {
 6936:             $authchk = 'refused';
 6937:         } else {
 6938:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 6939:         }
 6940:     }
 6941:     return ($authparam,$create_passwd,$authchk);
 6942: }
 6943: 
 6944: sub auto_photo_permission {
 6945:     my ($cnum,$cdom,$students) = @_;
 6946:     my $homeserver = &homeserver($cnum,$cdom);
 6947:     my ($outcome,$perm_reqd,$conditions) = 
 6948: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 6949:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 6950: 	return (undef,undef);
 6951:     }
 6952:     return ($outcome,$perm_reqd,$conditions);
 6953: }
 6954: 
 6955: sub auto_checkphotos {
 6956:     my ($uname,$udom,$pid) = @_;
 6957:     my $homeserver = &homeserver($uname,$udom);
 6958:     my ($result,$resulttype);
 6959:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 6960: 				   &escape($uname).':'.&escape($pid),
 6961: 				   $homeserver));
 6962:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 6963: 	return (undef,undef);
 6964:     }
 6965:     if ($outcome) {
 6966:         ($result,$resulttype) = split(/:/,$outcome);
 6967:     } 
 6968:     return ($result,$resulttype);
 6969: }
 6970: 
 6971: sub auto_photochoice {
 6972:     my ($cnum,$cdom) = @_;
 6973:     my $homeserver = &homeserver($cnum,$cdom);
 6974:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 6975: 						       &escape($cdom),
 6976: 						       $homeserver)));
 6977:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 6978: 	return (undef,undef);
 6979:     }
 6980:     return ($update,$comment);
 6981: }
 6982: 
 6983: sub auto_photoupdate {
 6984:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 6985:     my $homeserver = &homeserver($cnum,$dom);
 6986:     my $host=&hostname($homeserver);
 6987:     my $cmd = '';
 6988:     my $maxtries = 1;
 6989:     foreach my $affiliate (keys(%{$affiliatesref})) {
 6990:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 6991:     }
 6992:     $cmd =~ s/%%$//;
 6993:     $cmd = &escape($cmd);
 6994:     my $query = 'institutionalphotos';
 6995:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 6996:     unless ($queryid=~/^\Q$host\E\_/) {
 6997:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 6998:         return 'error: '.$queryid;
 6999:     }
 7000:     my $reply = &get_query_reply($queryid);
 7001:     my $tries = 1;
 7002:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 7003:         $reply = &get_query_reply($queryid);
 7004:         $tries ++;
 7005:     }
 7006:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 7007:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 7008:     } else {
 7009:         my @responses = split(/:/,$reply);
 7010:         my $outcome = shift(@responses); 
 7011:         foreach my $item (@responses) {
 7012:             my ($key,$value) = split(/=/,$item);
 7013:             $$photo{$key} = $value;
 7014:         }
 7015:         return $outcome;
 7016:     }
 7017:     return 'error';
 7018: }
 7019: 
 7020: sub auto_instcode_format {
 7021:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 7022: 	$cat_order) = @_;
 7023:     my $courses = '';
 7024:     my @homeservers;
 7025:     if ($caller eq 'global') {
 7026: 	my %servers = &get_servers($codedom,'library');
 7027: 	foreach my $tryserver (keys(%servers)) {
 7028: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7029: 		push(@homeservers,$tryserver);
 7030: 	    }
 7031:         }
 7032:     } elsif ($caller eq 'requests') {
 7033:         if ($codedom =~ /^$match_domain$/) {
 7034:             my $chome = &domain($codedom,'primary');
 7035:             unless ($chome eq 'no_host') {
 7036:                 push(@homeservers,$chome);
 7037:             }
 7038:         }
 7039:     } else {
 7040:         push(@homeservers,&homeserver($caller,$codedom));
 7041:     }
 7042:     foreach my $code (keys(%{$instcodes})) {
 7043:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 7044:     }
 7045:     chop($courses);
 7046:     my $ok_response = 0;
 7047:     my $response;
 7048:     while (@homeservers > 0 && $ok_response == 0) {
 7049:         my $server = shift(@homeservers); 
 7050:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 7051:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 7052:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 7053: 		split(/:/,$response);
 7054:             %{$codes} = (%{$codes},&str2hash($codes_str));
 7055:             push(@{$codetitles},&str2array($codetitles_str));
 7056:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 7057:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 7058:             $ok_response = 1;
 7059:         }
 7060:     }
 7061:     if ($ok_response) {
 7062:         return 'ok';
 7063:     } else {
 7064:         return $response;
 7065:     }
 7066: }
 7067: 
 7068: sub auto_instcode_defaults {
 7069:     my ($domain,$returnhash,$code_order) = @_;
 7070:     my @homeservers;
 7071: 
 7072:     my %servers = &get_servers($domain,'library');
 7073:     foreach my $tryserver (keys(%servers)) {
 7074: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7075: 	    push(@homeservers,$tryserver);
 7076: 	}
 7077:     }
 7078: 
 7079:     my $response;
 7080:     foreach my $server (@homeservers) {
 7081:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 7082:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 7083: 	
 7084: 	foreach my $pair (split(/\&/,$response)) {
 7085: 	    my ($name,$value)=split(/\=/,$pair);
 7086: 	    if ($name eq 'code_order') {
 7087: 		@{$code_order} = split(/\&/,&unescape($value));
 7088: 	    } else {
 7089: 		$returnhash->{&unescape($name)}=&unescape($value);
 7090: 	    }
 7091: 	}
 7092: 	return 'ok';
 7093:     }
 7094: 
 7095:     return $response;
 7096: }
 7097: 
 7098: sub auto_possible_instcodes {
 7099:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 7100:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 7101:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 7102:         return;
 7103:     }
 7104:     my (@homeservers,$uhome);
 7105:     if (defined(&domain($domain,'primary'))) {
 7106:         $uhome=&domain($domain,'primary');
 7107:         push(@homeservers,&domain($domain,'primary'));
 7108:     } else {
 7109:         my %servers = &get_servers($domain,'library');
 7110:         foreach my $tryserver (keys(%servers)) {
 7111:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7112:                 push(@homeservers,$tryserver);
 7113:             }
 7114:         }
 7115:     }
 7116:     my $response;
 7117:     foreach my $server (@homeservers) {
 7118:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 7119:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 7120:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 7121:             split(':',$response);
 7122:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 7123:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 7124:         foreach my $item (split('&',$cat_title)) {   
 7125:             my ($name,$value)=split('=',$item);
 7126:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 7127:         }
 7128:         foreach my $item (split('&',$cat_order)) {
 7129:             my ($name,$value)=split('=',$item);
 7130:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 7131:         }
 7132:         return 'ok';
 7133:     }
 7134:     return $response;
 7135: }
 7136: 
 7137: sub auto_courserequest_checks {
 7138:     my ($dom) = @_;
 7139:     my ($homeserver,%validations);
 7140:     if ($dom =~ /^$match_domain$/) {
 7141:         $homeserver = &domain($dom,'primary');
 7142:     }
 7143:     unless ($homeserver eq 'no_host') {
 7144:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 7145:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 7146:             my @items = split(/&/,$response);
 7147:             foreach my $item (@items) {
 7148:                 my ($key,$value) = split('=',$item);
 7149:                 $validations{&unescape($key)} = &thaw_unescape($value);
 7150:             }
 7151:         }
 7152:     }
 7153:     return %validations; 
 7154: }
 7155: 
 7156: sub auto_courserequest_validation {
 7157:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
 7158:     my ($homeserver,$response);
 7159:     if ($dom =~ /^$match_domain$/) {
 7160:         $homeserver = &domain($dom,'primary');
 7161:     }
 7162:     unless ($homeserver eq 'no_host') {  
 7163:           
 7164:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 7165:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 7166:                                     ':'.&escape($instcode).':'.&escape($instseclist),
 7167:                                     $homeserver));
 7168:     }
 7169:     return $response;
 7170: }
 7171: 
 7172: sub auto_validate_class_sec {
 7173:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 7174:     my $homeserver = &homeserver($cnum,$cdom);
 7175:     my $ownerlist;
 7176:     if (ref($owners) eq 'ARRAY') {
 7177:         $ownerlist = join(',',@{$owners});
 7178:     } else {
 7179:         $ownerlist = $owners;
 7180:     }
 7181:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 7182:                         &escape($ownerlist).':'.$cdom,$homeserver);
 7183:     return $response;
 7184: }
 7185: 
 7186: # ------------------------------------------------------- Course Group routines
 7187: 
 7188: sub get_coursegroups {
 7189:     my ($cdom,$cnum,$group,$namespace) = @_;
 7190:     return(&dump($namespace,$cdom,$cnum,$group));
 7191: }
 7192: 
 7193: sub modify_coursegroup {
 7194:     my ($cdom,$cnum,$groupsettings) = @_;
 7195:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 7196: }
 7197: 
 7198: sub toggle_coursegroup_status {
 7199:     my ($cdom,$cnum,$group,$action) = @_;
 7200:     my ($from_namespace,$to_namespace);
 7201:     if ($action eq 'delete') {
 7202:         $from_namespace = 'coursegroups';
 7203:         $to_namespace = 'deleted_groups';
 7204:     } else {
 7205:         $from_namespace = 'deleted_groups';
 7206:         $to_namespace = 'coursegroups';
 7207:     }
 7208:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 7209:     if (my $tmp = &error(%curr_group)) {
 7210:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 7211:         return ('read error',$tmp);
 7212:     } else {
 7213:         my %savedsettings = %curr_group; 
 7214:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 7215:         my $deloutcome;
 7216:         if ($result eq 'ok') {
 7217:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 7218:         } else {
 7219:             return ('write error',$result);
 7220:         }
 7221:         if ($deloutcome eq 'ok') {
 7222:             return 'ok';
 7223:         } else {
 7224:             return ('delete error',$deloutcome);
 7225:         }
 7226:     }
 7227: }
 7228: 
 7229: sub modify_group_roles {
 7230:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 7231:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 7232:     my $role = 'gr/'.&escape($userprivs);
 7233:     my ($uname,$udom) = split(/:/,$user);
 7234:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 7235:     if ($result eq 'ok') {
 7236:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 7237:     }
 7238:     return $result;
 7239: }
 7240: 
 7241: sub modify_coursegroup_membership {
 7242:     my ($cdom,$cnum,$membership) = @_;
 7243:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 7244:     return $result;
 7245: }
 7246: 
 7247: sub get_active_groups {
 7248:     my ($udom,$uname,$cdom,$cnum) = @_;
 7249:     my $now = time;
 7250:     my %groups = ();
 7251:     foreach my $key (keys(%env)) {
 7252:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 7253:             my ($start,$end) = split(/\./,$env{$key});
 7254:             if (($end!=0) && ($end<$now)) { next; }
 7255:             if (($start!=0) && ($start>$now)) { next; }
 7256:             if ($1 eq $cdom && $2 eq $cnum) {
 7257:                 $groups{$3} = $env{$key} ;
 7258:             }
 7259:         }
 7260:     }
 7261:     return %groups;
 7262: }
 7263: 
 7264: sub get_group_membership {
 7265:     my ($cdom,$cnum,$group) = @_;
 7266:     return(&dump('groupmembership',$cdom,$cnum,$group));
 7267: }
 7268: 
 7269: sub get_users_groups {
 7270:     my ($udom,$uname,$courseid) = @_;
 7271:     my @usersgroups;
 7272:     my $cachetime=1800;
 7273: 
 7274:     my $hashid="$udom:$uname:$courseid";
 7275:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 7276:     if (defined($cached)) {
 7277:         @usersgroups = split(/:/,$grouplist);
 7278:     } else {  
 7279:         $grouplist = '';
 7280:         my $courseurl = &courseid_to_courseurl($courseid);
 7281:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 7282:         my $access_end = $env{'course.'.$courseid.
 7283:                               '.default_enrollment_end_date'};
 7284:         my $now = time;
 7285:         foreach my $key (keys(%roleshash)) {
 7286:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 7287:                 my $group = $1;
 7288:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 7289:                     my $start = $2;
 7290:                     my $end = $1;
 7291:                     if ($start == -1) { next; } # deleted from group
 7292:                     if (($start!=0) && ($start>$now)) { next; }
 7293:                     if (($end!=0) && ($end<$now)) {
 7294:                         if ($access_end && $access_end < $now) {
 7295:                             if ($access_end - $end < 86400) {
 7296:                                 push(@usersgroups,$group);
 7297:                             }
 7298:                         }
 7299:                         next;
 7300:                     }
 7301:                     push(@usersgroups,$group);
 7302:                 }
 7303:             }
 7304:         }
 7305:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 7306:         $grouplist = join(':',@usersgroups);
 7307:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 7308:     }
 7309:     return @usersgroups;
 7310: }
 7311: 
 7312: sub devalidate_getgroups_cache {
 7313:     my ($udom,$uname,$cdom,$cnum)=@_;
 7314:     my $courseid = $cdom.'_'.$cnum;
 7315: 
 7316:     my $hashid="$udom:$uname:$courseid";
 7317:     &devalidate_cache_new('getgroups',$hashid);
 7318: }
 7319: 
 7320: # ------------------------------------------------------------------ Plain Text
 7321: 
 7322: sub plaintext {
 7323:     my ($short,$type,$cid,$forcedefault) = @_;
 7324:     if ($short =~ m{^cr/}) {
 7325: 	return (split('/',$short))[-1];
 7326:     }
 7327:     if (!defined($cid)) {
 7328:         $cid = $env{'request.course.id'};
 7329:     }
 7330:     my %rolenames = (
 7331:                       Course    => 'std',
 7332:                       Community => 'alt1',
 7333:                     );
 7334:     if ($cid ne '') {
 7335:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 7336:             unless ($forcedefault) {
 7337:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 7338:                 &Apache::lonlocal::mt_escape(\$roletext);
 7339:                 return &Apache::lonlocal::mt($roletext);
 7340:             }
 7341:         }
 7342:     }
 7343:     if ((defined($type)) && (defined($rolenames{$type})) &&
 7344:         (defined($rolenames{$type})) && 
 7345:         (defined($prp{$short}{$rolenames{$type}}))) {
 7346:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 7347:     } elsif ($cid ne '') {
 7348:         my $crstype = $env{'course.'.$cid.'.type'};
 7349:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
 7350:             (defined($prp{$short}{$rolenames{$crstype}}))) {
 7351:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
 7352:         }
 7353:     }
 7354:     return &Apache::lonlocal::mt($prp{$short}{'std'});
 7355: }
 7356: 
 7357: # ----------------------------------------------------------------- Assign Role
 7358: 
 7359: sub assignrole {
 7360:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 7361:         $context)=@_;
 7362:     my $mrole;
 7363:     if ($role =~ /^cr\//) {
 7364:         my $cwosec=$url;
 7365:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 7366: 	unless (&allowed('ccr',$cwosec)) {
 7367:            my $refused = 1;
 7368:            if ($context eq 'requestcourses') {
 7369:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 7370:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
 7371:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
 7372:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 7373:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 7374:                            if ($crsenv{'internal.courseowner'} eq
 7375:                                $env{'user.name'}.':'.$env{'user.domain'}) {
 7376:                                $refused = '';
 7377:                            }
 7378:                        }
 7379:                    }
 7380:                }
 7381:            }
 7382:            if ($refused) {
 7383:                &logthis('Refused custom assignrole: '.
 7384:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
 7385:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
 7386:                return 'refused';
 7387:            }
 7388:         }
 7389:         $mrole='cr';
 7390:     } elsif ($role =~ /^gr\//) {
 7391:         my $cwogrp=$url;
 7392:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 7393:         unless (&allowed('mdg',$cwogrp)) {
 7394:             &logthis('Refused group assignrole: '.
 7395:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 7396:                     $env{'user.name'}.' at '.$env{'user.domain'});
 7397:             return 'refused';
 7398:         }
 7399:         $mrole='gr';
 7400:     } else {
 7401:         my $cwosec=$url;
 7402:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 7403:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 7404:             my $refused;
 7405:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 7406:                 if (!(&allowed('c'.$role,$url))) {
 7407:                     $refused = 1;
 7408:                 }
 7409:             } else {
 7410:                 $refused = 1;
 7411:             }
 7412:             if ($refused) {
 7413:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 7414:                 if (!$selfenroll && $context eq 'course') {
 7415:                     my %crsenv;
 7416:                     if ($role eq 'cc' || $role eq 'co') {
 7417:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 7418:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
 7419:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
 7420:                                 if ($crsenv{'internal.courseowner'} eq 
 7421:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 7422:                                     $refused = '';
 7423:                                 }
 7424:                             }
 7425:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
 7426:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
 7427:                                 if ($crsenv{'internal.courseowner'} eq 
 7428:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 7429:                                     $refused = '';
 7430:                                 }
 7431:                             }
 7432:                         }
 7433:                     }
 7434:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7435:                     $refused = '';
 7436:                 } elsif ($context eq 'requestcourses') {
 7437:                     my @possroles = ('st','ta','ep','in','cc','co');
 7438:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
 7439:                         my $wrongcc;
 7440:                         if ($cnum =~ /^$match_community$/) {
 7441:                             $wrongcc = 1 if ($role eq 'cc');
 7442:                         } else {
 7443:                             $wrongcc = 1 if ($role eq 'co');
 7444:                         }
 7445:                         unless ($wrongcc) {
 7446:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 7447:                             if ($crsenv{'internal.courseowner'} eq 
 7448:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
 7449:                                 $refused = '';
 7450:                             }
 7451:                         }
 7452:                     }
 7453:                 }
 7454:                 if ($refused) {
 7455:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 7456:                              ' '.$role.' '.$end.' '.$start.' by '.
 7457: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 7458:                     return 'refused';
 7459:                 }
 7460:             }
 7461:         } elsif ($role eq 'au') {
 7462:             if ($url ne '/'.$udom.'/') {
 7463:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
 7464:                          ' to assign author role for '.$uname.':'.$udom.
 7465:                          ' in domain: '.$url.' refused (wrong domain).');
 7466:                 return 'refused';
 7467:             }
 7468:         }
 7469:         $mrole=$role;
 7470:     }
 7471:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 7472:                 "$udom:$uname:$url".'_'."$mrole=$role";
 7473:     if ($end) { $command.='_'.$end; }
 7474:     if ($start) {
 7475: 	if ($end) { 
 7476:            $command.='_'.$start; 
 7477:         } else {
 7478:            $command.='_0_'.$start;
 7479:         }
 7480:     }
 7481:     my $origstart = $start;
 7482:     my $origend = $end;
 7483:     my $delflag;
 7484: # actually delete
 7485:     if ($deleteflag) {
 7486: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 7487: # modify command to delete the role
 7488:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 7489:                 "$udom:$uname:$url".'_'."$mrole";
 7490: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 7491: # set start and finish to negative values for userrolelog
 7492:            $start=-1;
 7493:            $end=-1;
 7494:            $delflag = 1;
 7495:         }
 7496:     }
 7497: # send command
 7498:     my $answer=&reply($command,&homeserver($uname,$udom));
 7499: # log new user role if status is ok
 7500:     if ($answer eq 'ok') {
 7501: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 7502: # for course roles, perform group memberships changes triggered by role change.
 7503:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
 7504:         unless ($role =~ /^gr/) {
 7505:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 7506:                                              $origstart,$selfenroll,$context);
 7507:         }
 7508:         if ($role eq 'cc') {
 7509:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
 7510:         }
 7511:     }
 7512:     return $answer;
 7513: }
 7514: 
 7515: sub autoupdate_coowners {
 7516:     my ($url,$end,$start,$uname,$udom) = @_;
 7517:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
 7518:     if (($cdom ne '') && ($cnum ne '')) {
 7519:         my $now = time;
 7520:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
 7521:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
 7522:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
 7523:             my $instcode = $coursehash{'internal.coursecode'};
 7524:             if ($instcode ne '') {
 7525:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
 7526:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
 7527:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
 7528:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
 7529:                         if ($result eq 'valid') {
 7530:                             if ($coursehash{'internal.co-owners'}) {
 7531:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 7532:                                     push(@newcoowners,$coowner);
 7533:                                 }
 7534:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
 7535:                                     push(@newcoowners,$uname.':'.$udom);
 7536:                                 }
 7537:                                 @newcoowners = sort(@newcoowners);
 7538:                             } else {
 7539:                                 push(@newcoowners,$uname.':'.$udom);
 7540:                             }
 7541:                         } else {
 7542:                             if ($coursehash{'internal.co-owners'}) {
 7543:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 7544:                                     unless ($coowner eq $uname.':'.$udom) {
 7545:                                         push(@newcoowners,$coowner);
 7546:                                     }
 7547:                                 }
 7548:                                 unless (@newcoowners > 0) {
 7549:                                     $delcoowners = 1;
 7550:                                     $coowners = '';
 7551:                                 }
 7552:                             }
 7553:                         }
 7554:                         if (@newcoowners || $delcoowners) {
 7555:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
 7556:                                             $delcoowners,@newcoowners);
 7557:                         }
 7558:                     }
 7559:                 }
 7560:             }
 7561:         }
 7562:     }
 7563: }
 7564: 
 7565: sub store_coowners {
 7566:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
 7567:     my $cid = $cdom.'_'.$cnum;
 7568:     my ($coowners,$delresult,$putresult);
 7569:     if (@newcoowners) {
 7570:         $coowners = join(',',@newcoowners);
 7571:         my %coownershash = (
 7572:                             'internal.co-owners' => $coowners,
 7573:                            );
 7574:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
 7575:         if ($putresult eq 'ok') {
 7576:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
 7577:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
 7578:             }
 7579:         }
 7580:     }
 7581:     if ($delcoowners) {
 7582:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
 7583:         if ($delresult eq 'ok') {
 7584:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
 7585:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
 7586:             }
 7587:         }
 7588:     }
 7589:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
 7590:         my %crsinfo =
 7591:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 7592:         if (ref($crsinfo{$cid}) eq 'HASH') {
 7593:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
 7594:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
 7595:         }
 7596:     }
 7597: }
 7598: 
 7599: # -------------------------------------------------- Modify user authentication
 7600: # Overrides without validation
 7601: 
 7602: sub modifyuserauth {
 7603:     my ($udom,$uname,$umode,$upass)=@_;
 7604:     my $uhome=&homeserver($uname,$udom);
 7605:     unless (&allowed('mau',$udom)) { return 'refused'; }
 7606:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 7607:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 7608:              ' in domain '.$env{'request.role.domain'});  
 7609:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 7610: 		     &escape($upass),$uhome);
 7611:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 7612:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 7613:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 7614:     &log($udom,,$uname,$uhome,
 7615:         'Authentication changed by '.$env{'user.domain'}.', '.
 7616:                                      $env{'user.name'}.', '.$umode.
 7617:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 7618:     unless ($reply eq 'ok') {
 7619:         &logthis('Authentication mode error: '.$reply);
 7620: 	return 'error: '.$reply;
 7621:     }   
 7622:     return 'ok';
 7623: }
 7624: 
 7625: # --------------------------------------------------------------- Modify a user
 7626: 
 7627: sub modifyuser {
 7628:     my ($udom,    $uname, $uid,
 7629:         $umode,   $upass, $first,
 7630:         $middle,  $last,  $gene,
 7631:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
 7632:     $udom= &LONCAPA::clean_domain($udom);
 7633:     $uname=&LONCAPA::clean_username($uname);
 7634:     my $showcandelete = 'none';
 7635:     if (ref($candelete) eq 'ARRAY') {
 7636:         if (@{$candelete} > 0) {
 7637:             $showcandelete = join(', ',@{$candelete});
 7638:         }
 7639:     }
 7640:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 7641:              $umode.', '.$first.', '.$middle.', '.
 7642: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
 7643:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 7644:                                      ' desiredhome not specified'). 
 7645:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 7646:              ' in domain '.$env{'request.role.domain'});
 7647:     my $uhome=&homeserver($uname,$udom,'true');
 7648:     my $newuser;
 7649:     if ($uhome eq 'no_host') {
 7650:         $newuser = 1;
 7651:     }
 7652: # ----------------------------------------------------------------- Create User
 7653:     if (($uhome eq 'no_host') && 
 7654: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 7655:         my $unhome='';
 7656:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 7657:             $unhome = $desiredhome;
 7658: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 7659: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 7660:         } else { # load balancing routine for determining $unhome
 7661:             my $loadm=10000000;
 7662: 	    my %servers = &get_servers($udom,'library');
 7663: 	    foreach my $tryserver (keys(%servers)) {
 7664: 		my $answer=reply('load',$tryserver);
 7665: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 7666: 		    $loadm=$answer;
 7667: 		    $unhome=$tryserver;
 7668: 		}
 7669: 	    }
 7670:         }
 7671:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 7672: 	    return 'error: unable to find a home server for '.$uname.
 7673:                    ' in domain '.$udom;
 7674:         }
 7675:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 7676:                          &escape($upass),$unhome);
 7677: 	unless ($reply eq 'ok') {
 7678:             return 'error: '.$reply;
 7679:         }   
 7680:         $uhome=&homeserver($uname,$udom,'true');
 7681:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 7682: 	    return 'error: unable verify users home machine.';
 7683:         }
 7684:     }   # End of creation of new user
 7685: # ---------------------------------------------------------------------- Add ID
 7686:     if ($uid) {
 7687:        $uid=~tr/A-Z/a-z/;
 7688:        my %uidhash=&idrget($udom,$uname);
 7689:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 7690:          && (!$forceid)) {
 7691: 	  unless ($uid eq $uidhash{$uname}) {
 7692: 	      return 'error: user id "'.$uid.'" does not match '.
 7693:                   'current user id "'.$uidhash{$uname}.'".';
 7694:           }
 7695:        } else {
 7696: 	  &idput($udom,($uname => $uid));
 7697:        }
 7698:     }
 7699: # -------------------------------------------------------------- Add names, etc
 7700:     my @tmp=&get('environment',
 7701: 		   ['firstname','middlename','lastname','generation','id',
 7702:                     'permanentemail','inststatus'],
 7703: 		   $udom,$uname);
 7704:     my (%names,%oldnames);
 7705:     if ($tmp[0] =~ m/^error:.*/) { 
 7706:         %names=(); 
 7707:     } else {
 7708:         %names = @tmp;
 7709:         %oldnames = %names;
 7710:     }
 7711: #
 7712: # If name, email and/or uid are blank (e.g., because an uploaded file
 7713: # of users did not contain them), do not overwrite existing values
 7714: # unless field is in $candelete array ref.  
 7715: #
 7716: 
 7717:     my @fields = ('firstname','middlename','lastname','generation',
 7718:                   'permanentemail','id');
 7719:     my %newvalues;
 7720:     if (ref($candelete) eq 'ARRAY') {
 7721:         foreach my $field (@fields) {
 7722:             if (grep(/^\Q$field\E$/,@{$candelete})) {
 7723:                 if ($field eq 'firstname') {
 7724:                     $names{$field} = $first;
 7725:                 } elsif ($field eq 'middlename') {
 7726:                     $names{$field} = $middle;
 7727:                 } elsif ($field eq 'lastname') {
 7728:                     $names{$field} = $last;
 7729:                 } elsif ($field eq 'generation') { 
 7730:                     $names{$field} = $gene;
 7731:                 } elsif ($field eq 'permanentemail') {
 7732:                     $names{$field} = $email;
 7733:                 } elsif ($field eq 'id') {
 7734:                     $names{$field}  = $uid;
 7735:                 }
 7736:             }
 7737:         }
 7738:     }
 7739:     if ($first)  { $names{'firstname'}  = $first; }
 7740:     if (defined($middle)) { $names{'middlename'} = $middle; }
 7741:     if ($last)   { $names{'lastname'}   = $last; }
 7742:     if (defined($gene))   { $names{'generation'} = $gene; }
 7743:     if ($email) {
 7744:        $email=~s/[^\w\@\.\-\,]//gs;
 7745:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 7746:     }
 7747:     if ($uid) { $names{'id'}  = $uid; }
 7748:     if (defined($inststatus)) {
 7749:         $names{'inststatus'} = '';
 7750:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
 7751:         if (ref($usertypes) eq 'HASH') {
 7752:             my @okstatuses; 
 7753:             foreach my $item (split(/:/,$inststatus)) {
 7754:                 if (defined($usertypes->{$item})) {
 7755:                     push(@okstatuses,$item);  
 7756:                 }
 7757:             }
 7758:             if (@okstatuses) {
 7759:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
 7760:             }
 7761:         }
 7762:     }
 7763:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
 7764:                  $umode.', '.$first.', '.$middle.', '.
 7765:                  $last.', '.$gene.', '.$email.', '.$inststatus;
 7766:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 7767:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 7768:     } else {
 7769:         $logmsg .= ' during self creation';
 7770:     }
 7771:     my $changed;
 7772:     if ($newuser) {
 7773:         $changed = 1;
 7774:     } else {
 7775:         foreach my $field (@fields) {
 7776:             if ($names{$field} ne $oldnames{$field}) {
 7777:                 $changed = 1;
 7778:                 last;
 7779:             }
 7780:         }
 7781:     }
 7782:     unless ($changed) {
 7783:         $logmsg = 'No changes in user information needed for: '.$logmsg;
 7784:         &logthis($logmsg);
 7785:         return 'ok';
 7786:     }
 7787:     my $reply = &put('environment', \%names, $udom,$uname);
 7788:     if ($reply ne 'ok') { 
 7789:         return 'error: '.$reply;
 7790:     }
 7791:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
 7792:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
 7793:     }
 7794:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 7795:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 7796:     $logmsg = 'Success modifying user '.$logmsg;
 7797:     &logthis($logmsg);
 7798:     return 'ok';
 7799: }
 7800: 
 7801: # -------------------------------------------------------------- Modify student
 7802: 
 7803: sub modifystudent {
 7804:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 7805:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 7806:         $selfenroll,$context,$inststatus)=@_;
 7807:     if (!$cid) {
 7808: 	unless ($cid=$env{'request.course.id'}) {
 7809: 	    return 'not_in_class';
 7810: 	}
 7811:     }
 7812: # --------------------------------------------------------------- Make the user
 7813:     my $reply=&modifyuser
 7814: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 7815:          $desiredhome,$email,$inststatus);
 7816:     unless ($reply eq 'ok') { return $reply; }
 7817:     # This will cause &modify_student_enrollment to get the uid from the
 7818:     # students environment
 7819:     $uid = undef if (!$forceid);
 7820:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 7821: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
 7822:     return $reply;
 7823: }
 7824: 
 7825: sub modify_student_enrollment {
 7826:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
 7827:     my ($cdom,$cnum,$chome);
 7828:     if (!$cid) {
 7829: 	unless ($cid=$env{'request.course.id'}) {
 7830: 	    return 'not_in_class';
 7831: 	}
 7832: 	$cdom=$env{'course.'.$cid.'.domain'};
 7833: 	$cnum=$env{'course.'.$cid.'.num'};
 7834:     } else {
 7835: 	($cdom,$cnum)=split(/_/,$cid);
 7836:     }
 7837:     $chome=$env{'course.'.$cid.'.home'};
 7838:     if (!$chome) {
 7839: 	$chome=&homeserver($cnum,$cdom);
 7840:     }
 7841:     if (!$chome) { return 'unknown_course'; }
 7842:     # Make sure the user exists
 7843:     my $uhome=&homeserver($uname,$udom);
 7844:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 7845: 	return 'error: no such user';
 7846:     }
 7847:     # Get student data if we were not given enough information
 7848:     if (!defined($first)  || $first  eq '' || 
 7849:         !defined($last)   || $last   eq '' || 
 7850:         !defined($uid)    || $uid    eq '' || 
 7851:         !defined($middle) || $middle eq '' || 
 7852:         !defined($gene)   || $gene   eq '') {
 7853:         # They did not supply us with enough data to enroll the student, so
 7854:         # we need to pick up more information.
 7855:         my %tmp = &get('environment',
 7856:                        ['firstname','middlename','lastname', 'generation','id']
 7857:                        ,$udom,$uname);
 7858: 
 7859:         #foreach my $key (keys(%tmp)) {
 7860:         #    &logthis("key $key = ".$tmp{$key});
 7861:         #}
 7862:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 7863:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 7864:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 7865:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 7866:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 7867:     }
 7868:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 7869:     my $user = "$uname:$udom";
 7870:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
 7871:     my $reply=cput('classlist',
 7872: 		   {$user => 
 7873: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
 7874: 		   $cdom,$cnum);
 7875:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
 7876:         &devalidate_getsection_cache($udom,$uname,$cid);
 7877:     } else { 
 7878: 	return 'error: '.$reply;
 7879:     }
 7880:     # Add student role to user
 7881:     my $uurl='/'.$cid;
 7882:     $uurl=~s/\_/\//g;
 7883:     if ($usec) {
 7884: 	$uurl.='/'.$usec;
 7885:     }
 7886:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
 7887:                              $selfenroll,$context);
 7888:     if ($result ne 'ok') {
 7889:         if ($old_entry{$user} ne '') {
 7890:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
 7891:         } else {
 7892:             $reply = &del('classlist',[$user],$cdom,$cnum);
 7893:         }
 7894:     }
 7895:     return $result; 
 7896: }
 7897: 
 7898: sub format_name {
 7899:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 7900:     my $name;
 7901:     if ($first ne 'lastname') {
 7902: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 7903:     } else {
 7904: 	if ($lastname=~/\S/) {
 7905: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 7906: 	    $name=~s/\s+,/,/;
 7907: 	} else {
 7908: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 7909: 	}
 7910:     }
 7911:     $name=~s/^\s+//;
 7912:     $name=~s/\s+$//;
 7913:     $name=~s/\s+/ /g;
 7914:     return $name;
 7915: }
 7916: 
 7917: # ------------------------------------------------- Write to course preferences
 7918: 
 7919: sub writecoursepref {
 7920:     my ($courseid,%prefs)=@_;
 7921:     $courseid=~s/^\///;
 7922:     $courseid=~s/\_/\//g;
 7923:     my ($cdomain,$cnum)=split(/\//,$courseid);
 7924:     my $chome=homeserver($cnum,$cdomain);
 7925:     if (($chome eq '') || ($chome eq 'no_host')) { 
 7926: 	return 'error: no such course';
 7927:     }
 7928:     my $cstring='';
 7929:     foreach my $pref (keys(%prefs)) {
 7930: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 7931:     }
 7932:     $cstring=~s/\&$//;
 7933:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 7934: }
 7935: 
 7936: # ---------------------------------------------------------- Make/modify course
 7937: 
 7938: sub createcourse {
 7939:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 7940:         $course_owner,$crstype,$cnum,$context,$category)=@_;
 7941:     $url=&declutter($url);
 7942:     my $cid='';
 7943:     if ($context eq 'requestcourses') {
 7944:         my $can_create = 0;
 7945:         my ($ownername,$ownerdom) = split(':',$course_owner);
 7946:         if ($udom eq $ownerdom) {
 7947:             if (&usertools_access($ownername,$ownerdom,$category,undef,
 7948:                                   $context)) {
 7949:                 $can_create = 1;
 7950:             }
 7951:         } else {
 7952:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
 7953:                                            $category);
 7954:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
 7955:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
 7956:                 if (@curr > 0) {
 7957:                     my @options = qw(approval validate autolimit);
 7958:                     my $optregex = join('|',@options);
 7959:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
 7960:                         $can_create = 1;
 7961:                     }
 7962:                 }
 7963:             }
 7964:         }
 7965:         if ($can_create) {
 7966:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
 7967:                 unless (&allowed('ccc',$udom)) {
 7968:                     return 'refused'; 
 7969:                 }
 7970:             }
 7971:         } else {
 7972:             return 'refused';
 7973:         }
 7974:     } elsif (!&allowed('ccc',$udom)) {
 7975:         return 'refused';
 7976:     }
 7977: # --------------------------------------------------------------- Get Unique ID
 7978:     my $uname;
 7979:     if ($cnum =~ /^$match_courseid$/) {
 7980:         my $chome=&homeserver($cnum,$udom,'true');
 7981:         if (($chome eq '') || ($chome eq 'no_host')) {
 7982:             $uname = $cnum;
 7983:         } else {
 7984:             $uname = &generate_coursenum($udom,$crstype);
 7985:         }
 7986:     } else {
 7987:         $uname = &generate_coursenum($udom,$crstype);
 7988:     }
 7989:     return $uname if ($uname =~ /^error/);
 7990: # -------------------------------------------------- Check supplied server name
 7991:     if (!defined($course_server)) {
 7992:         if (defined(&domain($udom,'primary'))) {
 7993:             $course_server = &domain($udom,'primary');
 7994:         } else {
 7995:             $course_server = $env{'user.home'}; 
 7996:         }
 7997:     }
 7998:     my %host_servers =
 7999:         &Apache::lonnet::get_servers($udom,'library');
 8000:     unless ($host_servers{$course_server}) {
 8001:         return 'error: invalid home server for course: '.$course_server;
 8002:     }
 8003: # ------------------------------------------------------------- Make the course
 8004:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 8005:                       $course_server);
 8006:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 8007:     my $uhome=&homeserver($uname,$udom,'true');
 8008:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 8009: 	return 'error: no such course';
 8010:     }
 8011: # ----------------------------------------------------------------- Course made
 8012: # log existence
 8013:     my $now = time;
 8014:     my $newcourse = {
 8015:                     $udom.'_'.$uname => {
 8016:                                      description => $description,
 8017:                                      inst_code   => $inst_code,
 8018:                                      owner       => $course_owner,
 8019:                                      type        => $crstype,
 8020:                                      creator     => $env{'user.name'}.':'.
 8021:                                                     $env{'user.domain'},
 8022:                                      created     => $now,
 8023:                                      context     => $context,
 8024:                                                 },
 8025:                     };
 8026:     &courseidput($udom,$newcourse,$uhome,'notime');
 8027: # set toplevel url
 8028:     my $topurl=$url;
 8029:     unless ($nonstandard) {
 8030: # ------------------------------------------ For standard courses, make top url
 8031:         my $mapurl=&clutter($url);
 8032:         if ($mapurl eq '/res/') { $mapurl=''; }
 8033:         $env{'form.initmap'}=(<<ENDINITMAP);
 8034: <map>
 8035: <resource id="1" type="start"></resource>
 8036: <resource id="2" src="$mapurl"></resource>
 8037: <resource id="3" type="finish"></resource>
 8038: <link index="1" from="1" to="2"></link>
 8039: <link index="2" from="2" to="3"></link>
 8040: </map>
 8041: ENDINITMAP
 8042:         $topurl=&declutter(
 8043:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 8044:                           );
 8045:     }
 8046: # ----------------------------------------------------------- Write preferences
 8047:     &writecoursepref($udom.'_'.$uname,
 8048:                      ('description'              => $description,
 8049:                       'url'                      => $topurl,
 8050:                       'internal.creator'         => $env{'user.name'}.':'.
 8051:                                                     $env{'user.domain'},
 8052:                       'internal.created'         => $now,
 8053:                       'internal.creationcontext' => $context)
 8054:                     );
 8055:     return '/'.$udom.'/'.$uname;
 8056: }
 8057: 
 8058: # ------------------------------------------------------------------- Create ID
 8059: sub generate_coursenum {
 8060:     my ($udom,$crstype) = @_;
 8061:     my $domdesc = &domain($udom);
 8062:     return 'error: invalid domain' if ($domdesc eq '');
 8063:     my $first;
 8064:     if ($crstype eq 'Community') {
 8065:         $first = '0';
 8066:     } else {
 8067:         $first = int(1+rand(9)); 
 8068:     } 
 8069:     my $uname=$first.
 8070:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 8071:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
 8072:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 8073: # ----------------------------------------------- Make sure that does not exist
 8074:     my $uhome=&homeserver($uname,$udom,'true');
 8075:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
 8076:         if ($crstype eq 'Community') {
 8077:             $first = '0';
 8078:         } else {
 8079:             $first = int(1+rand(9));
 8080:         }
 8081:         $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:         $uhome=&homeserver($uname,$udom,'true');
 8086:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
 8087:             return 'error: unable to generate unique course-ID';
 8088:         }
 8089:     }
 8090:     return $uname;
 8091: }
 8092: 
 8093: sub is_course {
 8094:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
 8095:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
 8096: 
 8097:     return unless $cdom and $cnum;
 8098: 
 8099:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
 8100:         '.');
 8101: 
 8102:     return unless exists($courses{$cdom.'_'.$cnum});
 8103:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
 8104: }
 8105: 
 8106: sub store_userdata {
 8107:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
 8108:     my $result;
 8109:     if ($datakey ne '') {
 8110:         if (ref($storehash) eq 'HASH') {
 8111:             if ($udom eq '' || $uname eq '') {
 8112:                 $udom = $env{'user.domain'};
 8113:                 $uname = $env{'user.name'};
 8114:             }
 8115:             my $uhome=&homeserver($uname,$udom);
 8116:             if (($uhome eq '') || ($uhome eq 'no_host')) {
 8117:                 $result = 'error: no_host';
 8118:             } else {
 8119:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
 8120:                 $storehash->{'host'} = $perlvar{'lonHostID'};
 8121: 
 8122:                 my $namevalue='';
 8123:                 foreach my $key (keys(%{$storehash})) {
 8124:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 8125:                 }
 8126:                 $namevalue=~s/\&$//;
 8127:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
 8128:                                   $namevalue,$uhome);
 8129:             }
 8130:         } else {
 8131:             $result = 'error: data to store was not a hash reference'; 
 8132:         }
 8133:     } else {
 8134:         $result= 'error: invalid requestkey'; 
 8135:     }
 8136:     return $result;
 8137: }
 8138: 
 8139: # ---------------------------------------------------------- Assign Custom Role
 8140: 
 8141: sub assigncustomrole {
 8142:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
 8143:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 8144:                        $end,$start,$deleteflag,$selfenroll,$context);
 8145: }
 8146: 
 8147: # ----------------------------------------------------------------- Revoke Role
 8148: 
 8149: sub revokerole {
 8150:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
 8151:     my $now=time;
 8152:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
 8153: }
 8154: 
 8155: # ---------------------------------------------------------- Revoke Custom Role
 8156: 
 8157: sub revokecustomrole {
 8158:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
 8159:     my $now=time;
 8160:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 8161:            $deleteflag,$selfenroll,$context);
 8162: }
 8163: 
 8164: # ------------------------------------------------------------ Disk usage
 8165: sub diskusage {
 8166:     my ($udom,$uname,$directorypath,$getpropath)=@_;
 8167:     $directorypath =~ s/\/$//;
 8168:     my $listing=&reply('du2:'.&escape($directorypath).':'
 8169:                        .&escape($getpropath).':'.&escape($uname).':'
 8170:                        .&escape($udom),homeserver($uname,$udom));
 8171:     if ($listing eq 'unknown_cmd') {
 8172:         if ($getpropath) {
 8173:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
 8174:         }
 8175:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
 8176:     }
 8177:     return $listing;
 8178: }
 8179: 
 8180: sub is_locked {
 8181:     my ($file_name, $domain, $user, $which) = @_;
 8182:     my @check;
 8183:     my $is_locked;
 8184:     push (@check,$file_name);
 8185:     my %locked = &get('file_permissions',\@check,
 8186: 		      $env{'user.domain'},$env{'user.name'});
 8187:     my ($tmp)=keys(%locked);
 8188:     if ($tmp=~/^error:/) { undef(%locked); }
 8189:     
 8190:     if (ref($locked{$file_name}) eq 'ARRAY') {
 8191:         $is_locked = 'false';
 8192:         foreach my $entry (@{$locked{$file_name}}) {
 8193:            if (ref($entry) eq 'ARRAY') {
 8194:                $is_locked = 'true';
 8195:                if (ref($which) eq 'ARRAY') {
 8196:                    push(@{$which},$entry);
 8197:                } else {
 8198:                    last;
 8199:                }
 8200:            }
 8201:        }
 8202:     } else {
 8203:         $is_locked = 'false';
 8204:     }
 8205:     return $is_locked;
 8206: }
 8207: 
 8208: sub declutter_portfile {
 8209:     my ($file) = @_;
 8210:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 8211:     return $file;
 8212: }
 8213: 
 8214: # ------------------------------------------------------------- Mark as Read Only
 8215: 
 8216: sub mark_as_readonly {
 8217:     my ($domain,$user,$files,$what) = @_;
 8218:     my %current_permissions = &dump('file_permissions',$domain,$user);
 8219:     my ($tmp)=keys(%current_permissions);
 8220:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 8221:     foreach my $file (@{$files}) {
 8222: 	$file = &declutter_portfile($file);
 8223:         push(@{$current_permissions{$file}},$what);
 8224:     }
 8225:     &put('file_permissions',\%current_permissions,$domain,$user);
 8226:     return;
 8227: }
 8228: 
 8229: # ------------------------------------------------------------Save Selected Files
 8230: 
 8231: sub save_selected_files {
 8232:     my ($user, $path, @files) = @_;
 8233:     my $filename = $user."savedfiles";
 8234:     my @other_files = &files_not_in_path($user, $path);
 8235:     open (OUT, '>'.$tmpdir.$filename);
 8236:     foreach my $file (@files) {
 8237:         print (OUT $env{'form.currentpath'}.$file."\n");
 8238:     }
 8239:     foreach my $file (@other_files) {
 8240:         print (OUT $file."\n");
 8241:     }
 8242:     close (OUT);
 8243:     return 'ok';
 8244: }
 8245: 
 8246: sub clear_selected_files {
 8247:     my ($user) = @_;
 8248:     my $filename = $user."savedfiles";
 8249:     open (OUT, '>'.LONCAPA::tempdir().$filename);
 8250:     print (OUT undef);
 8251:     close (OUT);
 8252:     return ("ok");    
 8253: }
 8254: 
 8255: sub files_in_path {
 8256:     my ($user, $path) = @_;
 8257:     my $filename = $user."savedfiles";
 8258:     my %return_files;
 8259:     open (IN, '<'.LONCAPA::tempdir().$filename);
 8260:     while (my $line_in = <IN>) {
 8261:         chomp ($line_in);
 8262:         my @paths_and_file = split (m!/!, $line_in);
 8263:         my $file_part = pop (@paths_and_file);
 8264:         my $path_part = join ('/', @paths_and_file);
 8265:         $path_part.='/';
 8266:         my $path_and_file = $path_part.$file_part;
 8267:         if ($path_part eq $path) {
 8268:             $return_files{$file_part}= 'selected';
 8269:         }
 8270:     }
 8271:     close (IN);
 8272:     return (\%return_files);
 8273: }
 8274: 
 8275: # called in portfolio select mode, to show files selected NOT in current directory
 8276: sub files_not_in_path {
 8277:     my ($user, $path) = @_;
 8278:     my $filename = $user."savedfiles";
 8279:     my @return_files;
 8280:     my $path_part;
 8281:     open(IN, '<'.LONCAPA::.$filename);
 8282:     while (my $line = <IN>) {
 8283:         #ok, I know it's clunky, but I want it to work
 8284:         my @paths_and_file = split(m|/|, $line);
 8285:         my $file_part = pop(@paths_and_file);
 8286:         chomp($file_part);
 8287:         my $path_part = join('/', @paths_and_file);
 8288:         $path_part .= '/';
 8289:         my $path_and_file = $path_part.$file_part;
 8290:         if ($path_part ne $path) {
 8291:             push(@return_files, ($path_and_file));
 8292:         }
 8293:     }
 8294:     close(OUT);
 8295:     return (@return_files);
 8296: }
 8297: 
 8298: #----------------------------------------------Get portfolio file permissions
 8299: 
 8300: sub get_portfile_permissions {
 8301:     my ($domain,$user) = @_;
 8302:     my %current_permissions = &dump('file_permissions',$domain,$user);
 8303:     my ($tmp)=keys(%current_permissions);
 8304:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 8305:     return \%current_permissions;
 8306: }
 8307: 
 8308: #---------------------------------------------Get portfolio file access controls
 8309: 
 8310: sub get_access_controls {
 8311:     my ($current_permissions,$group,$file) = @_;
 8312:     my %access;
 8313:     my $real_file = $file;
 8314:     $file =~ s/\.meta$//;
 8315:     if (defined($file)) {
 8316:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 8317:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 8318:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 8319:             }
 8320:         }
 8321:     } else {
 8322:         foreach my $key (keys(%{$current_permissions})) {
 8323:             if ($key =~ /\0accesscontrol$/) {
 8324:                 if (defined($group)) {
 8325:                     if ($key !~ m-^\Q$group\E/-) {
 8326:                         next;
 8327:                     }
 8328:                 }
 8329:                 my ($fullpath) = split(/\0/,$key);
 8330:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 8331:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 8332:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 8333:                     }
 8334:                 }
 8335:             }
 8336:         }
 8337:     }
 8338:     return %access;
 8339: }
 8340: 
 8341: sub modify_access_controls {
 8342:     my ($file_name,$changes,$domain,$user)=@_;
 8343:     my ($outcome,$deloutcome);
 8344:     my %store_permissions;
 8345:     my %new_values;
 8346:     my %new_control;
 8347:     my %translation;
 8348:     my @deletions = ();
 8349:     my $now = time;
 8350:     if (exists($$changes{'activate'})) {
 8351:         if (ref($$changes{'activate'}) eq 'HASH') {
 8352:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 8353:             my $numnew = scalar(@newitems);
 8354:             for (my $i=0; $i<$numnew; $i++) {
 8355:                 my $newkey = $newitems[$i];
 8356:                 my $newid = &Apache::loncommon::get_cgi_id();
 8357:                 if ($newkey =~ /^\d+:/) { 
 8358:                     $newkey =~ s/^(\d+)/$newid/;
 8359:                     $translation{$1} = $newid;
 8360:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 8361:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 8362:                     $translation{$1} = $newid;
 8363:                 }
 8364:                 $new_values{$file_name."\0".$newkey} = 
 8365:                                           $$changes{'activate'}{$newitems[$i]};
 8366:                 $new_control{$newkey} = $now;
 8367:             }
 8368:         }
 8369:     }
 8370:     my %todelete;
 8371:     my %changed_items;
 8372:     foreach my $action ('delete','update') {
 8373:         if (exists($$changes{$action})) {
 8374:             if (ref($$changes{$action}) eq 'HASH') {
 8375:                 foreach my $key (keys(%{$$changes{$action}})) {
 8376:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 8377:                     if ($action eq 'delete') { 
 8378:                         $todelete{$itemnum} = 1;
 8379:                     } else {
 8380:                         $changed_items{$itemnum} = $key;
 8381:                     }
 8382:                 }
 8383:             }
 8384:         }
 8385:     }
 8386:     # get lock on access controls for file.
 8387:     my $lockhash = {
 8388:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 8389:                                                        ':'.$env{'user.domain'},
 8390:                    }; 
 8391:     my $tries = 0;
 8392:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 8393:    
 8394:     while (($gotlock ne 'ok') && $tries <3) {
 8395:         $tries ++;
 8396:         sleep 1;
 8397:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 8398:     }
 8399:     if ($gotlock eq 'ok') {
 8400:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 8401:         my ($tmp)=keys(%curr_permissions);
 8402:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 8403:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 8404:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 8405:             if (ref($curr_controls) eq 'HASH') {
 8406:                 foreach my $control_item (keys(%{$curr_controls})) {
 8407:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 8408:                     if (defined($todelete{$itemnum})) {
 8409:                         push(@deletions,$file_name."\0".$control_item);
 8410:                     } else {
 8411:                         if (defined($changed_items{$itemnum})) {
 8412:                             $new_control{$changed_items{$itemnum}} = $now;
 8413:                             push(@deletions,$file_name."\0".$control_item);
 8414:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 8415:                         } else {
 8416:                             $new_control{$control_item} = $$curr_controls{$control_item};
 8417:                         }
 8418:                     }
 8419:                 }
 8420:             }
 8421:         }
 8422:         my ($group);
 8423:         if (&is_course($domain,$user)) {
 8424:             ($group,my $file) = split(/\//,$file_name,2);
 8425:         }
 8426:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 8427:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 8428:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 8429:         #  remove lock
 8430:         my @del_lock = ($file_name."\0".'locked_access_records');
 8431:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 8432:         my $sqlresult =
 8433:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
 8434:                                     $group);
 8435:     } else {
 8436:         $outcome = "error: could not obtain lockfile\n";  
 8437:     }
 8438:     return ($outcome,$deloutcome,\%new_values,\%translation);
 8439: }
 8440: 
 8441: sub make_public_indefinitely {
 8442:     my ($requrl) = @_;
 8443:     my $now = time;
 8444:     my $action = 'activate';
 8445:     my $aclnum = 0;
 8446:     if (&is_portfolio_url($requrl)) {
 8447:         my (undef,$udom,$unum,$file_name,$group) =
 8448:             &parse_portfolio_url($requrl);
 8449:         my $current_perms = &get_portfile_permissions($udom,$unum);
 8450:         my %access_controls = &get_access_controls($current_perms,
 8451:                                                    $group,$file_name);
 8452:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 8453:             my ($num,$scope,$end,$start) = 
 8454:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 8455:             if ($scope eq 'public') {
 8456:                 if ($start <= $now && $end == 0) {
 8457:                     $action = 'none';
 8458:                 } else {
 8459:                     $action = 'update';
 8460:                     $aclnum = $num;
 8461:                 }
 8462:                 last;
 8463:             }
 8464:         }
 8465:         if ($action eq 'none') {
 8466:              return 'ok';
 8467:         } else {
 8468:             my %changes;
 8469:             my $newend = 0;
 8470:             my $newstart = $now;
 8471:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 8472:             $changes{$action}{$newkey} = {
 8473:                 type => 'public',
 8474:                 time => {
 8475:                     start => $newstart,
 8476:                     end   => $newend,
 8477:                 },
 8478:             };
 8479:             my ($outcome,$deloutcome,$new_values,$translation) =
 8480:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 8481:             return $outcome;
 8482:         }
 8483:     } else {
 8484:         return 'invalid';
 8485:     }
 8486: }
 8487: 
 8488: #------------------------------------------------------Get Marked as Read Only
 8489: 
 8490: sub get_marked_as_readonly {
 8491:     my ($domain,$user,$what,$group) = @_;
 8492:     my $current_permissions = &get_portfile_permissions($domain,$user);
 8493:     my @readonly_files;
 8494:     my $cmp1=$what;
 8495:     if (ref($what)) { $cmp1=join('',@{$what}) };
 8496:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 8497:         if (defined($group)) {
 8498:             if ($file_name !~ m-^\Q$group\E/-) {
 8499:                 next;
 8500:             }
 8501:         }
 8502:         if (ref($value) eq "ARRAY"){
 8503:             foreach my $stored_what (@{$value}) {
 8504:                 my $cmp2=$stored_what;
 8505:                 if (ref($stored_what) eq 'ARRAY') {
 8506:                     $cmp2=join('',@{$stored_what});
 8507:                 }
 8508:                 if ($cmp1 eq $cmp2) {
 8509:                     push(@readonly_files, $file_name);
 8510:                     last;
 8511:                 } elsif (!defined($what)) {
 8512:                     push(@readonly_files, $file_name);
 8513:                     last;
 8514:                 }
 8515:             }
 8516:         }
 8517:     }
 8518:     return @readonly_files;
 8519: }
 8520: #-----------------------------------------------------------Get Marked as Read Only Hash
 8521: 
 8522: sub get_marked_as_readonly_hash {
 8523:     my ($current_permissions,$group,$what) = @_;
 8524:     my %readonly_files;
 8525:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 8526:         if (defined($group)) {
 8527:             if ($file_name !~ m-^\Q$group\E/-) {
 8528:                 next;
 8529:             }
 8530:         }
 8531:         if (ref($value) eq "ARRAY"){
 8532:             foreach my $stored_what (@{$value}) {
 8533:                 if (ref($stored_what) eq 'ARRAY') {
 8534:                     foreach my $lock_descriptor(@{$stored_what}) {
 8535:                         if ($lock_descriptor eq 'graded') {
 8536:                             $readonly_files{$file_name} = 'graded';
 8537:                         } elsif ($lock_descriptor eq 'handback') {
 8538:                             $readonly_files{$file_name} = 'handback';
 8539:                         } else {
 8540:                             if (!exists($readonly_files{$file_name})) {
 8541:                                 $readonly_files{$file_name} = 'locked';
 8542:                             }
 8543:                         }
 8544:                     }
 8545:                 } 
 8546:             }
 8547:         } 
 8548:     }
 8549:     return %readonly_files;
 8550: }
 8551: # ------------------------------------------------------------ Unmark as Read Only
 8552: 
 8553: sub unmark_as_readonly {
 8554:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 8555:     # for portfolio submissions, $what contains [$symb,$crsid] 
 8556:     my ($domain,$user,$what,$file_name,$group) = @_;
 8557:     $file_name = &declutter_portfile($file_name);
 8558:     my $symb_crs = $what;
 8559:     if (ref($what)) { $symb_crs=join('',@$what); }
 8560:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 8561:     my ($tmp)=keys(%current_permissions);
 8562:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 8563:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 8564:     foreach my $file (@readonly_files) {
 8565: 	my $clean_file = &declutter_portfile($file);
 8566: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 8567: 	my $current_locks = $current_permissions{$file};
 8568:         my @new_locks;
 8569:         my @del_keys;
 8570:         if (ref($current_locks) eq "ARRAY"){
 8571:             foreach my $locker (@{$current_locks}) {
 8572:                 my $compare=$locker;
 8573:                 if (ref($locker) eq 'ARRAY') {
 8574:                     $compare=join('',@{$locker});
 8575:                     if ($compare ne $symb_crs) {
 8576:                         push(@new_locks, $locker);
 8577:                     }
 8578:                 }
 8579:             }
 8580:             if (scalar(@new_locks) > 0) {
 8581:                 $current_permissions{$file} = \@new_locks;
 8582:             } else {
 8583:                 push(@del_keys, $file);
 8584:                 &del('file_permissions',\@del_keys, $domain, $user);
 8585:                 delete($current_permissions{$file});
 8586:             }
 8587:         }
 8588:     }
 8589:     &put('file_permissions',\%current_permissions,$domain,$user);
 8590:     return;
 8591: }
 8592: 
 8593: # ------------------------------------------------------------ Directory lister
 8594: 
 8595: sub dirlist {
 8596:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
 8597:     $uri=~s/^\///;
 8598:     $uri=~s/\/$//;
 8599:     my ($udom, $uname);
 8600:     if ($getuserdir) {
 8601:         $udom = $userdomain;
 8602:         $uname = $username;
 8603:     } else {
 8604:         (undef,$udom,$uname)=split(/\//,$uri);
 8605:         if(defined($userdomain)) {
 8606:             $udom = $userdomain;
 8607:         }
 8608:         if(defined($username)) {
 8609:             $uname = $username;
 8610:         }
 8611:     }
 8612:     my ($dirRoot,$listing,@listing_results);
 8613: 
 8614:     $dirRoot = $perlvar{'lonDocRoot'};
 8615:     if (defined($getpropath)) {
 8616:         $dirRoot = &propath($udom,$uname);
 8617:         $dirRoot =~ s/\/$//;
 8618:     } elsif (defined($getuserdir)) {
 8619:         my $subdir=$uname.'__';
 8620:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 8621:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
 8622:                    ."/$udom/$subdir/$uname";
 8623:     } elsif (defined($alternateRoot)) {
 8624:         $dirRoot = $alternateRoot;
 8625:     }
 8626: 
 8627:     if($udom) {
 8628:         if($uname) {
 8629:             my $uhome = &homeserver($uname,$udom);
 8630:             if ($uhome eq 'no_host') {
 8631:                 return ([],'no_host');
 8632:             }
 8633:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
 8634:                               .$getuserdir.':'.&escape($dirRoot)
 8635:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
 8636:             if ($listing eq 'unknown_cmd') {
 8637:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
 8638:             } else {
 8639:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 8640:             }
 8641:             if ($listing eq 'unknown_cmd') {
 8642:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
 8643:                 @listing_results = split(/:/,$listing);
 8644:             } else {
 8645:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 8646:             }
 8647:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
 8648:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
 8649:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 8650:                 return ([],$listing);
 8651:             } else {
 8652:                 return (\@listing_results);
 8653:             }
 8654:         } elsif(!$alternateRoot) {
 8655:             my (%allusers,%listerror);
 8656: 	    my %servers = &get_servers($udom,'library');
 8657:  	    foreach my $tryserver (keys(%servers)) {
 8658:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
 8659:                                   &escape($udom),$tryserver);
 8660:                 if ($listing eq 'unknown_cmd') {
 8661: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 8662: 				      $udom, $tryserver);
 8663:                 } else {
 8664:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
 8665:                 }
 8666: 		if ($listing eq 'unknown_cmd') {
 8667: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 8668: 				      $udom, $tryserver);
 8669: 		    @listing_results = split(/:/,$listing);
 8670: 		} else {
 8671: 		    @listing_results =
 8672: 			map { &unescape($_); } split(/:/,$listing);
 8673: 		}
 8674:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
 8675:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
 8676:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 8677:                     $listerror{$tryserver} = $listing;
 8678:                 } else {
 8679: 		    foreach my $line (@listing_results) {
 8680: 			my ($entry) = split(/&/,$line,2);
 8681: 			$allusers{$entry} = 1;
 8682: 		    }
 8683: 		}
 8684:             }
 8685:             my @alluserslist=();
 8686:             foreach my $user (sort(keys(%allusers))) {
 8687:                 push(@alluserslist,$user.'&user');
 8688:             }
 8689:             return (\@alluserslist);
 8690:         } else {
 8691:             return ([],'missing username');
 8692:         }
 8693:     } elsif(!defined($getpropath)) {
 8694:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
 8695:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
 8696:         return (\@all_domains);
 8697:     } else {
 8698:         return ([],'missing domain');
 8699:     }
 8700: }
 8701: 
 8702: # --------------------------------------------- GetFileTimestamp
 8703: # This function utilizes dirlist and returns the date stamp for
 8704: # when it was last modified.  It will also return an error of -1
 8705: # if an error occurs
 8706: 
 8707: sub GetFileTimestamp {
 8708:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
 8709:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 8710:     $studentName   = &LONCAPA::clean_username($studentName);
 8711:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
 8712:                                     undef,$getuserdir);
 8713:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 8714:         return -1;
 8715:     }
 8716:     if (ref($fileref) eq 'ARRAY') {
 8717:         my @stats = split('&',$fileref->[0]);
 8718:         # @stats contains first the filename, then the stat output
 8719:         return $stats[10]; # so this is 10 instead of 9.
 8720:     } else {
 8721:         return -1;
 8722:     }
 8723: }
 8724: 
 8725: sub stat_file {
 8726:     my ($uri) = @_;
 8727:     $uri = &clutter_with_no_wrapper($uri);
 8728: 
 8729:     my ($udom,$uname,$file);
 8730:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 8731: 	($udom,$uname,$file) =
 8732: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 8733: 	$file = 'userfiles/'.$file;
 8734:     }
 8735:     if ($uri =~ m-^/res/-) {
 8736: 	($udom,$uname) = 
 8737: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 8738: 	$file = $uri;
 8739:     }
 8740: 
 8741:     if (!$udom || !$uname || !$file) {
 8742: 	# unable to handle the uri
 8743: 	return ();
 8744:     }
 8745:     my $getpropath;
 8746:     if ($file =~ /^userfiles\//) {
 8747:         $getpropath = 1;
 8748:     }
 8749:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
 8750:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 8751:         return ();
 8752:     } else {
 8753:         if (ref($listref) eq 'ARRAY') {
 8754:             my @stats = split('&',$listref->[0]);
 8755: 	    shift(@stats); #filename is first
 8756: 	    return @stats;
 8757:         }
 8758:     }
 8759:     return ();
 8760: }
 8761: 
 8762: # -------------------------------------------------------- Value of a Condition
 8763: 
 8764: # gets the value of a specific preevaluated condition
 8765: #    stored in the string  $env{user.state.<cid>}
 8766: # or looks up a condition reference in the bighash and if if hasn't
 8767: # already been evaluated recurses into docondval to get the value of
 8768: # the condition, then memoizing it to 
 8769: #   $env{user.state.<cid>.<condition>}
 8770: sub directcondval {
 8771:     my $number=shift;
 8772:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 8773: 	&Apache::lonuserstate::evalstate();
 8774:     }
 8775:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 8776: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 8777:     } elsif ($number =~ /^_/) {
 8778: 	my $sub_condition;
 8779: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8780: 		&GDBM_READER(),0640)) {
 8781: 	    $sub_condition=$bighash{'conditions'.$number};
 8782: 	    untie(%bighash);
 8783: 	}
 8784: 	my $value = &docondval($sub_condition);
 8785: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
 8786: 	return $value;
 8787:     }
 8788:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 8789:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 8790:     } else {
 8791:        return 2;
 8792:     }
 8793: }
 8794: 
 8795: # get the collection of conditions for this resource
 8796: sub condval {
 8797:     my $condidx=shift;
 8798:     my $allpathcond='';
 8799:     foreach my $cond (split(/\|/,$condidx)) {
 8800: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 8801: 	    $allpathcond.=
 8802: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 8803: 	}
 8804:     }
 8805:     $allpathcond=~s/\|$//;
 8806:     return &docondval($allpathcond);
 8807: }
 8808: 
 8809: #evaluates an expression of conditions
 8810: sub docondval {
 8811:     my ($allpathcond) = @_;
 8812:     my $result=0;
 8813:     if ($env{'request.course.id'}
 8814: 	&& defined($allpathcond)) {
 8815: 	my $operand='|';
 8816: 	my @stack;
 8817: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 8818: 	    if ($chunk eq '(') {
 8819: 		push @stack,($operand,$result);
 8820: 	    } elsif ($chunk eq ')') {
 8821: 		my $before=pop @stack;
 8822: 		if (pop @stack eq '&') {
 8823: 		    $result=$result>$before?$before:$result;
 8824: 		} else {
 8825: 		    $result=$result>$before?$result:$before;
 8826: 		}
 8827: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 8828: 		$operand=$chunk;
 8829: 	    } else {
 8830: 		my $new=directcondval($chunk);
 8831: 		if ($operand eq '&') {
 8832: 		    $result=$result>$new?$new:$result;
 8833: 		} else {
 8834: 		    $result=$result>$new?$result:$new;
 8835: 		}
 8836: 	    }
 8837: 	}
 8838:     }
 8839:     return $result;
 8840: }
 8841: 
 8842: # ---------------------------------------------------- Devalidate courseresdata
 8843: 
 8844: sub devalidatecourseresdata {
 8845:     my ($coursenum,$coursedomain)=@_;
 8846:     my $hashid=$coursenum.':'.$coursedomain;
 8847:     &devalidate_cache_new('courseres',$hashid);
 8848: }
 8849: 
 8850: 
 8851: # --------------------------------------------------- Course Resourcedata Query
 8852: #
 8853: #  Parameters:
 8854: #      $coursenum    - Number of the course.
 8855: #      $coursedomain - Domain at which the course was created.
 8856: #  Returns:
 8857: #     A hash of the course parameters along (I think) with timestamps
 8858: #     and version info.
 8859: 
 8860: sub get_courseresdata {
 8861:     my ($coursenum,$coursedomain)=@_;
 8862:     my $coursehom=&homeserver($coursenum,$coursedomain);
 8863:     my $hashid=$coursenum.':'.$coursedomain;
 8864:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 8865:     my %dumpreply;
 8866:     unless (defined($cached)) {
 8867: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 8868: 	$result=\%dumpreply;
 8869: 	my ($tmp) = keys(%dumpreply);
 8870: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 8871: 	    &do_cache_new('courseres',$hashid,$result,600);
 8872: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 8873: 	    return $tmp;
 8874: 	} elsif ($tmp =~ /^(error)/) {
 8875: 	    $result=undef;
 8876: 	    &do_cache_new('courseres',$hashid,$result,600);
 8877: 	}
 8878:     }
 8879:     return $result;
 8880: }
 8881: 
 8882: sub devalidateuserresdata {
 8883:     my ($uname,$udom)=@_;
 8884:     my $hashid="$udom:$uname";
 8885:     &devalidate_cache_new('userres',$hashid);
 8886: }
 8887: 
 8888: sub get_userresdata {
 8889:     my ($uname,$udom)=@_;
 8890:     #most student don\'t have any data set, check if there is some data
 8891:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 8892: 
 8893:     my $hashid="$udom:$uname";
 8894:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 8895:     if (!defined($cached)) {
 8896: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 8897: 	$result=\%resourcedata;
 8898: 	&do_cache_new('userres',$hashid,$result,600);
 8899:     }
 8900:     my ($tmp)=keys(%$result);
 8901:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 8902: 	return $result;
 8903:     }
 8904:     #error 2 occurs when the .db doesn't exist
 8905:     if ($tmp!~/error: 2 /) {
 8906: 	&logthis("<font color=\"blue\">WARNING:".
 8907: 		 " Trying to get resource data for ".
 8908: 		 $uname." at ".$udom.": ".
 8909: 		 $tmp."</font>");
 8910:     } elsif ($tmp=~/error: 2 /) {
 8911: 	#&EXT_cache_set($udom,$uname);
 8912: 	&do_cache_new('userres',$hashid,undef,600);
 8913: 	undef($tmp); # not really an error so don't send it back
 8914:     }
 8915:     return $tmp;
 8916: }
 8917: #----------------------------------------------- resdata - return resource data
 8918: #  Purpose:
 8919: #    Return resource data for either users or for a course.
 8920: #  Parameters:
 8921: #     $name      - Course/user name.
 8922: #     $domain    - Name of the domain the user/course is registered on.
 8923: #     $type      - Type of thing $name is (must be 'course' or 'user'
 8924: #     @which     - Array of names of resources desired.
 8925: #  Returns:
 8926: #     The value of the first reasource in @which that is found in the
 8927: #     resource hash.
 8928: #  Exceptional Conditions:
 8929: #     If the $type passed in is not valid (not the string 'course' or 
 8930: #     'user', an undefined  reference is returned.
 8931: #     If none of the resources are found, an undef is returned
 8932: sub resdata {
 8933:     my ($name,$domain,$type,@which)=@_;
 8934:     my $result;
 8935:     if ($type eq 'course') {
 8936: 	$result=&get_courseresdata($name,$domain);
 8937:     } elsif ($type eq 'user') {
 8938: 	$result=&get_userresdata($name,$domain);
 8939:     }
 8940:     if (!ref($result)) { return $result; }    
 8941:     foreach my $item (@which) {
 8942: 	if (defined($result->{$item->[0]})) {
 8943: 	    return [$result->{$item->[0]},$item->[1]];
 8944: 	}
 8945:     }
 8946:     return undef;
 8947: }
 8948: 
 8949: #
 8950: # EXT resource caching routines
 8951: #
 8952: 
 8953: sub clear_EXT_cache_status {
 8954:     &delenv('cache.EXT.');
 8955: }
 8956: 
 8957: sub EXT_cache_status {
 8958:     my ($target_domain,$target_user) = @_;
 8959:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 8960:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 8961:         # We know already the user has no data
 8962:         return 1;
 8963:     } else {
 8964:         return 0;
 8965:     }
 8966: }
 8967: 
 8968: sub EXT_cache_set {
 8969:     my ($target_domain,$target_user) = @_;
 8970:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 8971:     #&appenv({$cachename => time});
 8972: }
 8973: 
 8974: # --------------------------------------------------------- Value of a Variable
 8975: sub EXT {
 8976: 
 8977:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
 8978:     unless ($varname) { return ''; }
 8979:     #get real user name/domain, courseid and symb
 8980:     my $courseid;
 8981:     my $publicuser;
 8982:     if ($symbparm) {
 8983: 	$symbparm=&get_symb_from_alias($symbparm);
 8984:     }
 8985:     if (!($uname && $udom)) {
 8986:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 8987:       if (!$symbparm) {	$symbparm=$cursymb; }
 8988:     } else {
 8989: 	$courseid=$env{'request.course.id'};
 8990:     }
 8991:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 8992:     my $rest;
 8993:     if (defined($therest[0])) {
 8994:        $rest=join('.',@therest);
 8995:     } else {
 8996:        $rest='';
 8997:     }
 8998: 
 8999:     my $qualifierrest=$qualifier;
 9000:     if ($rest) { $qualifierrest.='.'.$rest; }
 9001:     my $spacequalifierrest=$space;
 9002:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 9003:     if ($realm eq 'user') {
 9004: # --------------------------------------------------------------- user.resource
 9005: 	if ($space eq 'resource') {
 9006: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 9007: 		  || defined($Apache::lonhomework::parsing_a_task))
 9008: 		 &&
 9009: 		 ($symbparm eq &symbread()) ) {	
 9010: 		# if we are in the middle of processing the resource the
 9011: 		# get the value we are planning on committing
 9012:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 9013:                     return $Apache::lonhomework::results{$qualifierrest};
 9014:                 } else {
 9015:                     return $Apache::lonhomework::history{$qualifierrest};
 9016:                 }
 9017: 	    } else {
 9018: 		my %restored;
 9019: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 9020: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 9021: 		} else {
 9022: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 9023: 		}
 9024: 		return $restored{$qualifierrest};
 9025: 	    }
 9026: # ----------------------------------------------------------------- user.access
 9027:         } elsif ($space eq 'access') {
 9028: 	    # FIXME - not supporting calls for a specific user
 9029:             return &allowed($qualifier,$rest);
 9030: # ------------------------------------------ user.preferences, user.environment
 9031:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 9032: 	    if (($uname eq $env{'user.name'}) &&
 9033: 		($udom eq $env{'user.domain'})) {
 9034: 		return $env{join('.',('environment',$qualifierrest))};
 9035: 	    } else {
 9036: 		my %returnhash;
 9037: 		if (!$publicuser) {
 9038: 		    %returnhash=&userenvironment($udom,$uname,
 9039: 						 $qualifierrest);
 9040: 		}
 9041: 		return $returnhash{$qualifierrest};
 9042: 	    }
 9043: # ----------------------------------------------------------------- user.course
 9044:         } elsif ($space eq 'course') {
 9045: 	    # FIXME - not supporting calls for a specific user
 9046:             return $env{join('.',('request.course',$qualifier))};
 9047: # ------------------------------------------------------------------- user.role
 9048:         } elsif ($space eq 'role') {
 9049: 	    # FIXME - not supporting calls for a specific user
 9050:             my ($role,$where)=split(/\./,$env{'request.role'});
 9051:             if ($qualifier eq 'value') {
 9052: 		return $role;
 9053:             } elsif ($qualifier eq 'extent') {
 9054:                 return $where;
 9055:             }
 9056: # ----------------------------------------------------------------- user.domain
 9057:         } elsif ($space eq 'domain') {
 9058:             return $udom;
 9059: # ------------------------------------------------------------------- user.name
 9060:         } elsif ($space eq 'name') {
 9061:             return $uname;
 9062: # ---------------------------------------------------- Any other user namespace
 9063:         } else {
 9064: 	    my %reply;
 9065: 	    if (!$publicuser) {
 9066: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 9067: 	    }
 9068: 	    return $reply{$qualifierrest};
 9069:         }
 9070:     } elsif ($realm eq 'query') {
 9071: # ---------------------------------------------- pull stuff out of query string
 9072:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 9073: 						[$spacequalifierrest]);
 9074: 	return $env{'form.'.$spacequalifierrest}; 
 9075:    } elsif ($realm eq 'request') {
 9076: # ------------------------------------------------------------- request.browser
 9077:         if ($space eq 'browser') {
 9078:             return $env{'browser.'.$qualifier};
 9079: # ------------------------------------------------------------ request.filename
 9080:         } else {
 9081:             return $env{'request.'.$spacequalifierrest};
 9082:         }
 9083:     } elsif ($realm eq 'course') {
 9084: # ---------------------------------------------------------- course.description
 9085:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 9086:     } elsif ($realm eq 'resource') {
 9087: 
 9088: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 9089: 	    if (!$symbparm) { $symbparm=&symbread(); }
 9090: 	}
 9091: 
 9092: 	if ($space eq 'title') {
 9093: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 9094: 	    return &gettitle($symbparm);
 9095: 	}
 9096: 	
 9097: 	if ($space eq 'map') {
 9098: 	    my ($map) = &decode_symb($symbparm);
 9099: 	    return &symbread($map);
 9100: 	}
 9101: 	if ($space eq 'filename') {
 9102: 	    if ($symbparm) {
 9103: 		return &clutter((&decode_symb($symbparm))[2]);
 9104: 	    }
 9105: 	    return &hreflocation('',$env{'request.filename'});
 9106: 	}
 9107: 
 9108: 	my ($section, $group, @groups);
 9109: 	my ($courselevelm,$courselevel);
 9110: 	if ($symbparm && defined($courseid) && 
 9111: 	    $courseid eq $env{'request.course.id'}) {
 9112: 
 9113: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 9114: 
 9115: # ----------------------------------------------------- Cascading lookup scheme
 9116: 	    my $symbp=$symbparm;
 9117: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 9118: 
 9119: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 9120: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 9121: 
 9122: 	    if (($env{'user.name'} eq $uname) &&
 9123: 		($env{'user.domain'} eq $udom)) {
 9124: 		$section=$env{'request.course.sec'};
 9125:                 @groups = split(/:/,$env{'request.course.groups'});  
 9126:                 @groups=&sort_course_groups($courseid,@groups); 
 9127: 	    } else {
 9128: 		if (! defined($usection)) {
 9129: 		    $section=&getsection($udom,$uname,$courseid);
 9130: 		} else {
 9131: 		    $section = $usection;
 9132: 		}
 9133:                 @groups = &get_users_groups($udom,$uname,$courseid);
 9134: 	    }
 9135: 
 9136: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 9137: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 9138: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 9139: 
 9140: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 9141: 	    my $courselevelr=$courseid.'.'.$symbparm;
 9142: 	    $courselevelm=$courseid.'.'.$mapparm;
 9143: 
 9144: # ----------------------------------------------------------- first, check user
 9145: 
 9146: 	    my $userreply=&resdata($uname,$udom,'user',
 9147: 				       ([$courselevelr,'resource'],
 9148: 					[$courselevelm,'map'     ],
 9149: 					[$courselevel, 'course'  ]));
 9150: 	    if (defined($userreply)) { return &get_reply($userreply); }
 9151: 
 9152: # ------------------------------------------------ second, check some of course
 9153:             my $coursereply;
 9154:             if (@groups > 0) {
 9155:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 9156:                                        $mapparm,$spacequalifierrest);
 9157:                 if (defined($coursereply)) { return &get_reply($coursereply); }
 9158:             }
 9159: 
 9160: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 9161: 				  $env{'course.'.$courseid.'.domain'},
 9162: 				  'course',
 9163: 				  ([$seclevelr,   'resource'],
 9164: 				   [$seclevelm,   'map'     ],
 9165: 				   [$seclevel,    'course'  ],
 9166: 				   [$courselevelr,'resource']));
 9167: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 9168: 
 9169: # ------------------------------------------------------ third, check map parms
 9170: 	    my %parmhash=();
 9171: 	    my $thisparm='';
 9172: 	    if (tie(%parmhash,'GDBM_File',
 9173: 		    $env{'request.course.fn'}.'_parms.db',
 9174: 		    &GDBM_READER(),0640)) {
 9175: 		$thisparm=$parmhash{$symbparm};
 9176: 		untie(%parmhash);
 9177: 	    }
 9178: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
 9179: 	}
 9180: # ------------------------------------------ fourth, look in resource metadata
 9181: 
 9182: 	$spacequalifierrest=~s/\./\_/;
 9183: 	my $filename;
 9184: 	if (!$symbparm) { $symbparm=&symbread(); }
 9185: 	if ($symbparm) {
 9186: 	    $filename=(&decode_symb($symbparm))[2];
 9187: 	} else {
 9188: 	    $filename=$env{'request.filename'};
 9189: 	}
 9190: 	my $metadata=&metadata($filename,$spacequalifierrest);
 9191: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 9192: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 9193: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 9194: 
 9195: # ---------------------------------------------- fourth, look in rest of course
 9196: 	if ($symbparm && defined($courseid) && 
 9197: 	    $courseid eq $env{'request.course.id'}) {
 9198: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 9199: 				     $env{'course.'.$courseid.'.domain'},
 9200: 				     'course',
 9201: 				     ([$courselevelm,'map'   ],
 9202: 				      [$courselevel, 'course']));
 9203: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 9204: 	}
 9205: # ------------------------------------------------------------------ Cascade up
 9206: 	unless ($space eq '0') {
 9207: 	    my @parts=split(/_/,$space);
 9208: 	    my $id=pop(@parts);
 9209: 	    my $part=join('_',@parts);
 9210: 	    if ($part eq '') { $part='0'; }
 9211: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 9212: 				 $symbparm,$udom,$uname,$section,1);
 9213: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
 9214: 	}
 9215: 	if ($recurse) { return undef; }
 9216: 	my $pack_def=&packages_tab_default($filename,$varname);
 9217: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
 9218: # ---------------------------------------------------- Any other user namespace
 9219:     } elsif ($realm eq 'environment') {
 9220: # ----------------------------------------------------------------- environment
 9221: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 9222: 	    return $env{'environment.'.$spacequalifierrest};
 9223: 	} else {
 9224: 	    if ($uname eq 'anonymous' && $udom eq '') {
 9225: 		return '';
 9226: 	    }
 9227: 	    my %returnhash=&userenvironment($udom,$uname,
 9228: 					    $spacequalifierrest);
 9229: 	    return $returnhash{$spacequalifierrest};
 9230: 	}
 9231:     } elsif ($realm eq 'system') {
 9232: # ----------------------------------------------------------------- system.time
 9233: 	if ($space eq 'time') {
 9234: 	    return time;
 9235:         }
 9236:     } elsif ($realm eq 'server') {
 9237: # ----------------------------------------------------------------- system.time
 9238: 	if ($space eq 'name') {
 9239: 	    return $ENV{'SERVER_NAME'};
 9240:         }
 9241:     }
 9242:     return '';
 9243: }
 9244: 
 9245: sub get_reply {
 9246:     my ($reply_value) = @_;
 9247:     if (ref($reply_value) eq 'ARRAY') {
 9248:         if (wantarray) {
 9249: 	    return @$reply_value;
 9250:         }
 9251:         return $reply_value->[0];
 9252:     } else {
 9253:         return $reply_value;
 9254:     }
 9255: }
 9256: 
 9257: sub check_group_parms {
 9258:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
 9259:     my @groupitems = ();
 9260:     my $resultitem;
 9261:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
 9262:     foreach my $group (@{$groups}) {
 9263:         foreach my $level (@levels) {
 9264:              my $item = $courseid.'.['.$group.'].'.$level->[0];
 9265:              push(@groupitems,[$item,$level->[1]]);
 9266:         }
 9267:     }
 9268:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
 9269:                             $env{'course.'.$courseid.'.domain'},
 9270:                                      'course',@groupitems);
 9271:     return $coursereply;
 9272: }
 9273: 
 9274: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
 9275:     my ($courseid,@groups) = @_;
 9276:     @groups = sort(@groups);
 9277:     return @groups;
 9278: }
 9279: 
 9280: sub packages_tab_default {
 9281:     my ($uri,$varname)=@_;
 9282:     my (undef,$part,$name)=split(/\./,$varname);
 9283: 
 9284:     my (@extension,@specifics,$do_default);
 9285:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
 9286: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 9287: 	if ($pack_type eq 'default') {
 9288: 	    $do_default=1;
 9289: 	} elsif ($pack_type eq 'extension') {
 9290: 	    push(@extension,[$package,$pack_type,$pack_part]);
 9291: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
 9292: 	    # only look at packages defaults for packages that this id is
 9293: 	    push(@specifics,[$package,$pack_type,$pack_part]);
 9294: 	}
 9295:     }
 9296:     # first look for a package that matches the requested part id
 9297:     foreach my $package (@specifics) {
 9298: 	my (undef,$pack_type,$pack_part)=@{$package};
 9299: 	next if ($pack_part ne $part);
 9300: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 9301: 	    return $packagetab{"$pack_type&$name&default"};
 9302: 	}
 9303:     }
 9304:     # look for any possible matching non extension_ package
 9305:     foreach my $package (@specifics) {
 9306: 	my (undef,$pack_type,$pack_part)=@{$package};
 9307: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 9308: 	    return $packagetab{"$pack_type&$name&default"};
 9309: 	}
 9310: 	if ($pack_type eq 'part') { $pack_part='0'; }
 9311: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
 9312: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
 9313: 	}
 9314:     }
 9315:     # look for any posible extension_ match
 9316:     foreach my $package (@extension) {
 9317: 	my ($package,$pack_type)=@{$package};
 9318: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 9319: 	    return $packagetab{"$pack_type&$name&default"};
 9320: 	}
 9321: 	if (defined($packagetab{$package."&$name&default"})) {
 9322: 	    return $packagetab{$package."&$name&default"};
 9323: 	}
 9324:     }
 9325:     # look for a global default setting
 9326:     if ($do_default && defined($packagetab{"default&$name&default"})) {
 9327: 	return $packagetab{"default&$name&default"};
 9328:     }
 9329:     return undef;
 9330: }
 9331: 
 9332: sub add_prefix_and_part {
 9333:     my ($prefix,$part)=@_;
 9334:     my $keyroot;
 9335:     if (defined($prefix) && $prefix !~ /^__/) {
 9336: 	# prefix that has a part already
 9337: 	$keyroot=$prefix;
 9338:     } elsif (defined($prefix)) {
 9339: 	# prefix that is missing a part
 9340: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 9341:     } else {
 9342: 	# no prefix at all
 9343: 	if (defined($part)) { $keyroot='_'.$part; }
 9344:     }
 9345:     return $keyroot;
 9346: }
 9347: 
 9348: # ---------------------------------------------------------------- Get metadata
 9349: 
 9350: my %metaentry;
 9351: my %importedpartids;
 9352: sub metadata {
 9353:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 9354:     $uri=&declutter($uri);
 9355:     # if it is a non metadata possible uri return quickly
 9356:     if (($uri eq '') || 
 9357: 	(($uri =~ m|^/*adm/|) && 
 9358: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
 9359:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
 9360: 	return undef;
 9361:     }
 9362:     if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) 
 9363: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
 9364: 	return undef;
 9365:     }
 9366:     my $filename=$uri;
 9367:     $uri=~s/\.meta$//;
 9368: #
 9369: # Is the metadata already cached?
 9370: # Look at timestamp of caching
 9371: # Everything is cached by the main uri, libraries are never directly cached
 9372: #
 9373:     if (!defined($liburi)) {
 9374: 	my ($result,$cached)=&is_cached_new('meta',$uri);
 9375: 	if (defined($cached)) { return $result->{':'.$what}; }
 9376:     }
 9377:     {
 9378: # Imported parts would go here
 9379:         my %importedids=();
 9380:         my @origfileimportpartids=();
 9381:         my $importedparts=0;
 9382: #
 9383: # Is this a recursive call for a library?
 9384: #
 9385: #	if (! exists($metacache{$uri})) {
 9386: #	    $metacache{$uri}={};
 9387: #	}
 9388: 	my $cachetime = 60*60;
 9389:         if ($liburi) {
 9390: 	    $liburi=&declutter($liburi);
 9391:             $filename=$liburi;
 9392:         } else {
 9393: 	    &devalidate_cache_new('meta',$uri);
 9394: 	    undef(%metaentry);
 9395: 	}
 9396:         my %metathesekeys=();
 9397:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 9398: 	my $metastring;
 9399: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
 9400: 	    my $which = &hreflocation('','/'.($liburi || $uri));
 9401: 	    $metastring = 
 9402: 		&Apache::lonnet::ssi_body($which,
 9403: 					  ('grade_target' => 'meta'));
 9404: 	    $cachetime = 1; # only want this cached in the child not long term
 9405: 	} elsif (($uri !~ m -^(editupload)/-) && 
 9406:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
 9407: 	    my $file=&filelocation('',&clutter($filename));
 9408: 	    #push(@{$metaentry{$uri.'.file'}},$file);
 9409: 	    $metastring=&getfile($file);
 9410: 	}
 9411:         my $parser=HTML::LCParser->new(\$metastring);
 9412:         my $token;
 9413:         undef %metathesekeys;
 9414:         while ($token=$parser->get_token) {
 9415: 	    if ($token->[0] eq 'S') {
 9416: 		if (defined($token->[2]->{'package'})) {
 9417: #
 9418: # This is a package - get package info
 9419: #
 9420: 		    my $package=$token->[2]->{'package'};
 9421: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 9422: 		    if (defined($token->[2]->{'id'})) { 
 9423: 			$keyroot.='_'.$token->[2]->{'id'}; 
 9424: 		    }
 9425: 		    if ($metaentry{':packages'}) {
 9426: 			$metaentry{':packages'}.=','.$package.$keyroot;
 9427: 		    } else {
 9428: 			$metaentry{':packages'}=$package.$keyroot;
 9429: 		    }
 9430: 		    foreach my $pack_entry (keys(%packagetab)) {
 9431: 			my $part=$keyroot;
 9432: 			$part=~s/^\_//;
 9433: 			if ($pack_entry=~/^\Q$package\E\&/ || 
 9434: 			    $pack_entry=~/^\Q$package\E_0\&/) {
 9435: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
 9436: 			    # ignore package.tab specified default values
 9437:                             # here &package_tab_default() will fetch those
 9438: 			    if ($subp eq 'default') { next; }
 9439: 			    my $value=$packagetab{$pack_entry};
 9440: 			    my $unikey;
 9441: 			    if ($pack =~ /_0$/) {
 9442: 				$unikey='parameter_0_'.$name;
 9443: 				$part=0;
 9444: 			    } else {
 9445: 				$unikey='parameter'.$keyroot.'_'.$name;
 9446: 			    }
 9447: 			    if ($subp eq 'display') {
 9448: 				$value.=' [Part: '.$part.']';
 9449: 			    }
 9450: 			    $metaentry{':'.$unikey.'.part'}=$part;
 9451: 			    $metathesekeys{$unikey}=1;
 9452: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 9453: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
 9454: 			    }
 9455: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
 9456: 				$metaentry{':'.$unikey}=
 9457: 				    $metaentry{':'.$unikey.'.default'};
 9458: 			    }
 9459: 			}
 9460: 		    }
 9461: 		} else {
 9462: #
 9463: # This is not a package - some other kind of start tag
 9464: #
 9465: 		    my $entry=$token->[1];
 9466: 		    my $unikey='';
 9467: 
 9468: 		    if ($entry eq 'import') {
 9469: #
 9470: # Importing a library here
 9471: #
 9472:                         my $location=$parser->get_text('/import');
 9473:                         my $dir=$filename;
 9474:                         $dir=~s|[^/]*$||;
 9475:                         $location=&filelocation($dir,$location);
 9476:                        
 9477:                         my $importmode=$token->[2]->{'importmode'};
 9478:                         if ($importmode eq 'problem') {
 9479: # Import as problem/response
 9480:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 9481:                         } elsif ($importmode eq 'part') {
 9482: # Import as part(s)
 9483:                            $importedparts=1;
 9484: # We need to get the original file and the imported file to get the part order correct
 9485: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
 9486: # Load and inspect original file
 9487:                            if ($#origfileimportpartids<0) {
 9488:                               undef(%importedpartids);
 9489:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
 9490:                               my $origfile=&getfile($origfilelocation);
 9491:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
 9492:                            }
 9493: 
 9494: # Load and inspect imported file
 9495:                            my $impfile=&getfile($location);
 9496:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
 9497:                            if ($#impfilepartids>=0) {
 9498: # This problem had parts
 9499:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
 9500:                            } else {
 9501: # Importing by turning a single problem into a problem part
 9502: # It gets the import-tags ID as part-ID
 9503:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
 9504:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
 9505:                            }
 9506:                         } else {
 9507: # Normal import
 9508:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 9509:                            if (defined($token->[2]->{'id'})) {
 9510:                               $unikey.='_'.$token->[2]->{'id'};
 9511:                            }
 9512:                         }
 9513: 
 9514: 			if ($depthcount<20) {
 9515: 			    my $metadata = 
 9516: 				&metadata($uri,'keys', $location,$unikey,
 9517: 					  $depthcount+1);
 9518: 			    foreach my $meta (split(',',$metadata)) {
 9519: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
 9520: 				$metathesekeys{$meta}=1;
 9521: 			    }
 9522: 			
 9523:                         }
 9524: 		    } else {
 9525: #
 9526: # Not importing, some other kind of non-package, non-library start tag
 9527: # 
 9528:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
 9529:                         if (defined($token->[2]->{'id'})) {
 9530:                             $unikey.='_'.$token->[2]->{'id'};
 9531:                         }
 9532: 			if (defined($token->[2]->{'name'})) { 
 9533: 			    $unikey.='_'.$token->[2]->{'name'}; 
 9534: 			}
 9535: 			$metathesekeys{$unikey}=1;
 9536: 			foreach my $param (@{$token->[3]}) {
 9537: 			    $metaentry{':'.$unikey.'.'.$param} =
 9538: 				$token->[2]->{$param};
 9539: 			}
 9540: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
 9541: 			my $default=$metaentry{':'.$unikey.'.default'};
 9542: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
 9543: 		 # only ws inside the tag, and not in default, so use default
 9544: 		 # as value
 9545: 			    $metaentry{':'.$unikey}=$default;
 9546: 			} elsif ( $internaltext =~ /\S/ ) {
 9547: 		  # something interesting inside the tag
 9548: 			    $metaentry{':'.$unikey}=$internaltext;
 9549: 			} else {
 9550: 		  # no interesting values, don't set a default
 9551: 			}
 9552: # end of not-a-package not-a-library import
 9553: 		    }
 9554: # end of not-a-package start tag
 9555: 		}
 9556: # the next is the end of "start tag"
 9557: 	    }
 9558: 	}
 9559: 	my ($extension) = ($uri =~ /\.(\w+)$/);
 9560: 	$extension = lc($extension);
 9561: 	if ($extension eq 'htm') { $extension='html'; }
 9562: 
 9563: 	foreach my $key (keys(%packagetab)) {
 9564: 	    #no specific packages #how's our extension
 9565: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
 9566: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
 9567: 					 \%metathesekeys);
 9568: 	}
 9569: 
 9570: 	if (!exists($metaentry{':packages'})
 9571: 	    || $packagetab{"import_defaults&extension_$extension"}) {
 9572: 	    foreach my $key (keys(%packagetab)) {
 9573: 		#no specific packages well let's get default then
 9574: 		if ($key!~/^default&/) { next; }
 9575: 		&metadata_create_package_def($uri,$key,'default',
 9576: 					     \%metathesekeys);
 9577: 	    }
 9578: 	}
 9579: # are there custom rights to evaluate
 9580: 	if ($metaentry{':copyright'} eq 'custom') {
 9581: 
 9582:     #
 9583:     # Importing a rights file here
 9584:     #
 9585: 	    unless ($depthcount) {
 9586: 		my $location=$metaentry{':customdistributionfile'};
 9587: 		my $dir=$filename;
 9588: 		$dir=~s|[^/]*$||;
 9589: 		$location=&filelocation($dir,$location);
 9590: 		my $rights_metadata =
 9591: 		    &metadata($uri,'keys',$location,'_rights',
 9592: 			      $depthcount+1);
 9593: 		foreach my $rights (split(',',$rights_metadata)) {
 9594: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
 9595: 		    $metathesekeys{$rights}=1;
 9596: 		}
 9597: 	    }
 9598: 	}
 9599: 	# uniqifiy package listing
 9600: 	my %seen;
 9601: 	my @uniq_packages =
 9602: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
 9603: 	$metaentry{':packages'} = join(',',@uniq_packages);
 9604: 
 9605:         if ($importedparts) {
 9606: # We had imported parts and need to rebuild partorder
 9607:            $metaentry{':partorder'}='';
 9608:            $metathesekeys{'partorder'}=1;
 9609:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
 9610:                if ($origfileimportpartids[$index] eq 'part') {
 9611: # original part, part of the problem
 9612:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
 9613:                } else {
 9614: # we have imported parts at this position
 9615:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
 9616:                }
 9617:            }
 9618:            $metaentry{':partorder'}=~s/^\,//;
 9619:         }
 9620: 
 9621: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
 9622: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
 9623: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
 9624: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
 9625: # this is the end of "was not already recently cached
 9626:     }
 9627:     return $metaentry{':'.$what};
 9628: }
 9629: 
 9630: sub metadata_create_package_def {
 9631:     my ($uri,$key,$package,$metathesekeys)=@_;
 9632:     my ($pack,$name,$subp)=split(/\&/,$key);
 9633:     if ($subp eq 'default') { next; }
 9634:     
 9635:     if (defined($metaentry{':packages'})) {
 9636: 	$metaentry{':packages'}.=','.$package;
 9637:     } else {
 9638: 	$metaentry{':packages'}=$package;
 9639:     }
 9640:     my $value=$packagetab{$key};
 9641:     my $unikey;
 9642:     $unikey='parameter_0_'.$name;
 9643:     $metaentry{':'.$unikey.'.part'}=0;
 9644:     $$metathesekeys{$unikey}=1;
 9645:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 9646: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
 9647:     }
 9648:     if (defined($metaentry{':'.$unikey.'.default'})) {
 9649: 	$metaentry{':'.$unikey}=
 9650: 	    $metaentry{':'.$unikey.'.default'};
 9651:     }
 9652: }
 9653: 
 9654: sub metadata_generate_part0 {
 9655:     my ($metadata,$metacache,$uri) = @_;
 9656:     my %allnames;
 9657:     foreach my $metakey (keys(%$metadata)) {
 9658: 	if ($metakey=~/^parameter\_(.*)/) {
 9659: 	  my $part=$$metacache{':'.$metakey.'.part'};
 9660: 	  my $name=$$metacache{':'.$metakey.'.name'};
 9661: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
 9662: 	    $allnames{$name}=$part;
 9663: 	  }
 9664: 	}
 9665:     }
 9666:     foreach my $name (keys(%allnames)) {
 9667:       $$metadata{"parameter_0_$name"}=1;
 9668:       my $key=":parameter_0_$name";
 9669:       $$metacache{"$key.part"}='0';
 9670:       $$metacache{"$key.name"}=$name;
 9671:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
 9672: 					   $allnames{$name}.'_'.$name.
 9673: 					   '.type'};
 9674:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
 9675: 			     '.display'};
 9676:       my $expr='[Part: '.$allnames{$name}.']';
 9677:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
 9678:       $$metacache{"$key.display"}=$olddis;
 9679:     }
 9680: }
 9681: 
 9682: # ------------------------------------------------------ Devalidate title cache
 9683: 
 9684: sub devalidate_title_cache {
 9685:     my ($url)=@_;
 9686:     if (!$env{'request.course.id'}) { return; }
 9687:     my $symb=&symbread($url);
 9688:     if (!$symb) { return; }
 9689:     my $key=$env{'request.course.id'}."\0".$symb;
 9690:     &devalidate_cache_new('title',$key);
 9691: }
 9692: 
 9693: # ------------------------------------------------- Get the title of a course
 9694: 
 9695: sub current_course_title {
 9696:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
 9697: }
 9698: # ------------------------------------------------- Get the title of a resource
 9699: 
 9700: sub gettitle {
 9701:     my $urlsymb=shift;
 9702:     my $symb=&symbread($urlsymb);
 9703:     if ($symb) {
 9704: 	my $key=$env{'request.course.id'}."\0".$symb;
 9705: 	my ($result,$cached)=&is_cached_new('title',$key);
 9706: 	if (defined($cached)) { 
 9707: 	    return $result;
 9708: 	}
 9709: 	my ($map,$resid,$url)=&decode_symb($symb);
 9710: 	my $title='';
 9711: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
 9712: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
 9713: 	} else {
 9714: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9715: 		    &GDBM_READER(),0640)) {
 9716: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
 9717: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
 9718: 		untie(%bighash);
 9719: 	    }
 9720: 	}
 9721: 	$title=~s/\&colon\;/\:/gs;
 9722: 	if ($title) {
 9723: # Remember both $symb and $title for dynamic metadata
 9724:             $accesshash{$symb.'___crstitle'}=$title;
 9725:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
 9726: # Cache this title and then return it
 9727: 	    return &do_cache_new('title',$key,$title,600);
 9728: 	}
 9729: 	$urlsymb=$url;
 9730:     }
 9731:     my $title=&metadata($urlsymb,'title');
 9732:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
 9733:     return $title;
 9734: }
 9735: 
 9736: sub get_slot {
 9737:     my ($which,$cnum,$cdom)=@_;
 9738:     if (!$cnum || !$cdom) {
 9739: 	(undef,my $courseid)=&whichuser();
 9740: 	$cdom=$env{'course.'.$courseid.'.domain'};
 9741: 	$cnum=$env{'course.'.$courseid.'.num'};
 9742:     }
 9743:     my $key=join("\0",'slots',$cdom,$cnum,$which);
 9744:     my %slotinfo;
 9745:     if (exists($remembered{$key})) {
 9746: 	$slotinfo{$which} = $remembered{$key};
 9747:     } else {
 9748: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
 9749: 	&Apache::lonhomework::showhash(%slotinfo);
 9750: 	my ($tmp)=keys(%slotinfo);
 9751: 	if ($tmp=~/^error:/) { return (); }
 9752: 	$remembered{$key} = $slotinfo{$which};
 9753:     }
 9754:     if (ref($slotinfo{$which}) eq 'HASH') {
 9755: 	return %{$slotinfo{$which}};
 9756:     }
 9757:     return $slotinfo{$which};
 9758: }
 9759: 
 9760: sub get_reservable_slots {
 9761:     my ($cnum,$cdom,$uname,$udom) = @_;
 9762:     my $now = time;
 9763:     my $reservable_info;
 9764:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
 9765:     if (exists($remembered{$key})) {
 9766:         $reservable_info = $remembered{$key};
 9767:     } else {
 9768:         my %resv;
 9769:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
 9770:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
 9771:         $reservable_info = \%resv;
 9772:         $remembered{$key} = $reservable_info;
 9773:     }
 9774:     return $reservable_info;
 9775: }
 9776: 
 9777: sub get_course_slots {
 9778:     my ($cnum,$cdom) = @_;
 9779:     my $hashid=$cnum.':'.$cdom;
 9780:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
 9781:     if (defined($cached)) {
 9782:         if (ref($result) eq 'HASH') {
 9783:             return %{$result};
 9784:         }
 9785:     } else {
 9786:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
 9787:         my ($tmp) = keys(%slots);
 9788:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 9789:             &Apache::lonnet::do_cache_new('allslots',$hashid,\%slots,600);
 9790:             return %slots;
 9791:         }
 9792:     }
 9793:     return;
 9794: }
 9795: 
 9796: sub devalidate_slots_cache {
 9797:     my ($cnum,$cdom)=@_;
 9798:     my $hashid=$cnum.':'.$cdom;
 9799:     &devalidate_cache_new('allslots',$hashid);
 9800: }
 9801: 
 9802: # ------------------------------------------------- Update symbolic store links
 9803: 
 9804: sub symblist {
 9805:     my ($mapname,%newhash)=@_;
 9806:     $mapname=&deversion(&declutter($mapname));
 9807:     my %hash;
 9808:     if (($env{'request.course.fn'}) && (%newhash)) {
 9809:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 9810:                       &GDBM_WRCREAT(),0640)) {
 9811: 	    foreach my $url (keys(%newhash)) {
 9812: 		next if ($url eq 'last_known'
 9813: 			 && $env{'form.no_update_last_known'});
 9814: 		$hash{declutter($url)}=&encode_symb($mapname,
 9815: 						    $newhash{$url}->[1],
 9816: 						    $newhash{$url}->[0]);
 9817:             }
 9818:             if (untie(%hash)) {
 9819: 		return 'ok';
 9820:             }
 9821:         }
 9822:     }
 9823:     return 'error';
 9824: }
 9825: 
 9826: # --------------------------------------------------------------- Verify a symb
 9827: 
 9828: sub symbverify {
 9829:     my ($symb,$thisurl)=@_;
 9830:     my $thisfn=$thisurl;
 9831:     $thisfn=&declutter($thisfn);
 9832: # direct jump to resource in page or to a sequence - will construct own symbs
 9833:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
 9834: # check URL part
 9835:     my ($map,$resid,$url)=&decode_symb($symb);
 9836: 
 9837:     unless ($url eq $thisfn) { return 0; }
 9838: 
 9839:     $symb=&symbclean($symb);
 9840:     $thisurl=&deversion($thisurl);
 9841:     $thisfn=&deversion($thisfn);
 9842: 
 9843:     my %bighash;
 9844:     my $okay=0;
 9845: 
 9846:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9847:                             &GDBM_READER(),0640)) {
 9848:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
 9849:             $thisurl =~ s/\?.+$//;
 9850:         }
 9851:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
 9852:         unless ($ids) {
 9853:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
 9854:             $ids=$bighash{$idkey};
 9855:         }
 9856:         if ($ids) {
 9857: # ------------------------------------------------------------------- Has ID(s)
 9858: 	    foreach my $id (split(/\,/,$ids)) {
 9859: 	       my ($mapid,$resid)=split(/\./,$id);
 9860:                if ($thisfn =~ m{^/adm/wrapper/ext/}) {
 9861:                    $symb =~ s/\?.+$//;
 9862:                }
 9863:                if (
 9864:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
 9865:    eq $symb) { 
 9866: 		   if (($env{'request.role.adv'}) ||
 9867: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
 9868:                        ($thisurl eq '/adm/navmaps')) {
 9869: 		       $okay=1; 
 9870: 		   }
 9871: 	       }
 9872: 	   }
 9873:         }
 9874: 	untie(%bighash);
 9875:     }
 9876:     return $okay;
 9877: }
 9878: 
 9879: # --------------------------------------------------------------- Clean-up symb
 9880: 
 9881: sub symbclean {
 9882:     my $symb=shift;
 9883:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 9884: # remove version from map
 9885:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
 9886: 
 9887: # remove version from URL
 9888:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
 9889: 
 9890: # remove wrapper
 9891: 
 9892:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
 9893:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
 9894:     return $symb;
 9895: }
 9896: 
 9897: # ---------------------------------------------- Split symb to find map and url
 9898: 
 9899: sub encode_symb {
 9900:     my ($map,$resid,$url)=@_;
 9901:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
 9902: }
 9903: 
 9904: sub decode_symb {
 9905:     my $symb=shift;
 9906:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 9907:     my ($map,$resid,$url)=split(/___/,$symb);
 9908:     return (&fixversion($map),$resid,&fixversion($url));
 9909: }
 9910: 
 9911: sub fixversion {
 9912:     my $fn=shift;
 9913:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
 9914:     my %bighash;
 9915:     my $uri=&clutter($fn);
 9916:     my $key=$env{'request.course.id'}.'_'.$uri;
 9917: # is this cached?
 9918:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
 9919:     if (defined($cached)) { return $result; }
 9920: # unfortunately not cached, or expired
 9921:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9922: 	    &GDBM_READER(),0640)) {
 9923:  	if ($bighash{'version_'.$uri}) {
 9924:  	    my $version=$bighash{'version_'.$uri};
 9925:  	    unless (($version eq 'mostrecent') || 
 9926: 		    ($version==&getversion($uri))) {
 9927:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
 9928:  	    }
 9929:  	}
 9930:  	untie %bighash;
 9931:     }
 9932:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
 9933: }
 9934: 
 9935: sub deversion {
 9936:     my $url=shift;
 9937:     $url=~s/\.\d+\.(\w+)$/\.$1/;
 9938:     return $url;
 9939: }
 9940: 
 9941: # ------------------------------------------------------ Return symb list entry
 9942: 
 9943: sub symbread {
 9944:     my ($thisfn,$donotrecurse)=@_;
 9945:     my $cache_str='request.symbread.cached.'.$thisfn;
 9946:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
 9947: # no filename provided? try from environment
 9948:     unless ($thisfn) {
 9949:         if ($env{'request.symb'}) {
 9950: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
 9951: 	}
 9952: 	$thisfn=$env{'request.filename'};
 9953:     }
 9954:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 9955: # is that filename actually a symb? Verify, clean, and return
 9956:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
 9957: 	if (&symbverify($thisfn,$1)) {
 9958: 	    return $env{$cache_str}=&symbclean($thisfn);
 9959: 	}
 9960:     }
 9961:     $thisfn=declutter($thisfn);
 9962:     my %hash;
 9963:     my %bighash;
 9964:     my $syval='';
 9965:     if (($env{'request.course.fn'}) && ($thisfn)) {
 9966:         my $targetfn = $thisfn;
 9967:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
 9968:             $targetfn = 'adm/wrapper/'.$thisfn;
 9969:         }
 9970: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
 9971: 	    $targetfn=$1;
 9972: 	}
 9973:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 9974:                       &GDBM_READER(),0640)) {
 9975: 	    $syval=$hash{$targetfn};
 9976:             untie(%hash);
 9977:         }
 9978: # ---------------------------------------------------------- There was an entry
 9979:         if ($syval) {
 9980: 	    #unless ($syval=~/\_\d+$/) {
 9981: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
 9982: 		    #&appenv({'request.ambiguous' => $thisfn});
 9983: 		    #return $env{$cache_str}='';
 9984: 		#}    
 9985: 		#$syval.=$1;
 9986: 	    #}
 9987:         } else {
 9988: # ------------------------------------------------------- Was not in symb table
 9989:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9990:                             &GDBM_READER(),0640)) {
 9991: # ---------------------------------------------- Get ID(s) for current resource
 9992:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
 9993:               unless ($ids) { 
 9994:                  $ids=$bighash{'ids_/'.$thisfn};
 9995:               }
 9996:               unless ($ids) {
 9997: # alias?
 9998: 		  $ids=$bighash{'mapalias_'.$thisfn};
 9999:               }
10000:               if ($ids) {
10001: # ------------------------------------------------------------------- Has ID(s)
10002:                  my @possibilities=split(/\,/,$ids);
10003:                  if ($#possibilities==0) {
10004: # ----------------------------------------------- There is only one possibility
10005: 		     my ($mapid,$resid)=split(/\./,$ids);
10006: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
10007: 						    $resid,$thisfn);
10008:                  } elsif (!$donotrecurse) {
10009: # ------------------------------------------ There is more than one possibility
10010:                      my $realpossible=0;
10011:                      foreach my $id (@possibilities) {
10012: 			 my $file=$bighash{'src_'.$id};
10013:                          if (&allowed('bre',$file)) {
10014:          		    my ($mapid,$resid)=split(/\./,$id);
10015:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
10016: 				$realpossible++;
10017:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
10018: 						    $resid,$thisfn);
10019:                             }
10020: 			 }
10021:                      }
10022: 		     if ($realpossible!=1) { $syval=''; }
10023:                  } else {
10024:                      $syval='';
10025:                  }
10026: 	      }
10027:               untie(%bighash)
10028:            }
10029:         }
10030:         if ($syval) {
10031: 	    return $env{$cache_str}=$syval;
10032:         }
10033:     }
10034:     &appenv({'request.ambiguous' => $thisfn});
10035:     return $env{$cache_str}='';
10036: }
10037: 
10038: # ---------------------------------------------------------- Return random seed
10039: 
10040: sub numval {
10041:     my $txt=shift;
10042:     $txt=~tr/A-J/0-9/;
10043:     $txt=~tr/a-j/0-9/;
10044:     $txt=~tr/K-T/0-9/;
10045:     $txt=~tr/k-t/0-9/;
10046:     $txt=~tr/U-Z/0-5/;
10047:     $txt=~tr/u-z/0-5/;
10048:     $txt=~s/\D//g;
10049:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
10050:     return int($txt);
10051: }
10052: 
10053: sub numval2 {
10054:     my $txt=shift;
10055:     $txt=~tr/A-J/0-9/;
10056:     $txt=~tr/a-j/0-9/;
10057:     $txt=~tr/K-T/0-9/;
10058:     $txt=~tr/k-t/0-9/;
10059:     $txt=~tr/U-Z/0-5/;
10060:     $txt=~tr/u-z/0-5/;
10061:     $txt=~s/\D//g;
10062:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10063:     my $total;
10064:     foreach my $val (@txts) { $total+=$val; }
10065:     if ($_64bit) { if ($total > 2**32) { return -1; } }
10066:     return int($total);
10067: }
10068: 
10069: sub numval3 {
10070:     use integer;
10071:     my $txt=shift;
10072:     $txt=~tr/A-J/0-9/;
10073:     $txt=~tr/a-j/0-9/;
10074:     $txt=~tr/K-T/0-9/;
10075:     $txt=~tr/k-t/0-9/;
10076:     $txt=~tr/U-Z/0-5/;
10077:     $txt=~tr/u-z/0-5/;
10078:     $txt=~s/\D//g;
10079:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10080:     my $total;
10081:     foreach my $val (@txts) { $total+=$val; }
10082:     if ($_64bit) { $total=(($total<<32)>>32); }
10083:     return $total;
10084: }
10085: 
10086: sub digest {
10087:     my ($data)=@_;
10088:     my $digest=&Digest::MD5::md5($data);
10089:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
10090:     my ($e,$f);
10091:     {
10092:         use integer;
10093:         $e=($a+$b);
10094:         $f=($c+$d);
10095:         if ($_64bit) {
10096:             $e=(($e<<32)>>32);
10097:             $f=(($f<<32)>>32);
10098:         }
10099:     }
10100:     if (wantarray) {
10101: 	return ($e,$f);
10102:     } else {
10103: 	my $g;
10104: 	{
10105: 	    use integer;
10106: 	    $g=($e+$f);
10107: 	    if ($_64bit) {
10108: 		$g=(($g<<32)>>32);
10109: 	    }
10110: 	}
10111: 	return $g;
10112:     }
10113: }
10114: 
10115: sub latest_rnd_algorithm_id {
10116:     return '64bit5';
10117: }
10118: 
10119: sub get_rand_alg {
10120:     my ($courseid)=@_;
10121:     if (!$courseid) { $courseid=(&whichuser())[1]; }
10122:     if ($courseid) {
10123: 	return $env{"course.$courseid.rndseed"};
10124:     }
10125:     return &latest_rnd_algorithm_id();
10126: }
10127: 
10128: sub validCODE {
10129:     my ($CODE)=@_;
10130:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
10131:     return 0;
10132: }
10133: 
10134: sub getCODE {
10135:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
10136:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
10137: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
10138: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
10139: 	return $Apache::lonhomework::history{'resource.CODE'};
10140:     }
10141:     return undef;
10142: }
10143: #
10144: #  Determines the random seed for a specific context:
10145: #
10146: # parameters:
10147: #   symb      - in course context the symb for the seed.
10148: #   course_id - The course id of the form domain_coursenum.
10149: #   domain    - Domain for the user.
10150: #   course    - Course for the user.
10151: #   cenv      - environment of the course.
10152: #
10153: # NOTE:
10154: #   All parameters are picked out of the environment if missing
10155: #   or not defined.
10156: #   If a symb cannot be determined the current time is used instead.
10157: #
10158: #  For a given well defined symb, courside, domain, username,
10159: #  and course environment, the seed is reproducible.
10160: #
10161: sub rndseed {
10162:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
10163:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
10164:     if (!defined($symb)) {
10165: 	unless ($symb=$wsymb) { return time; }
10166:     }
10167:     if (!defined $courseid) { 
10168: 	$courseid=$wcourseid; 
10169:     }
10170:     if (!defined $domain) { $domain=$wdomain; }
10171:     if (!defined $username) { $username=$wusername }
10172: 
10173:     my $which;
10174:     if (defined($cenv->{'rndseed'})) {
10175: 	$which = $cenv->{'rndseed'};
10176:     } else {
10177: 	$which =&get_rand_alg($courseid);
10178:     }
10179:     if (defined(&getCODE())) {
10180: 
10181: 	if ($which eq '64bit5') {
10182: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
10183: 	} elsif ($which eq '64bit4') {
10184: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
10185: 	} else {
10186: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
10187: 	}
10188:     } elsif ($which eq '64bit5') {
10189: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
10190:     } elsif ($which eq '64bit4') {
10191: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
10192:     } elsif ($which eq '64bit3') {
10193: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
10194:     } elsif ($which eq '64bit2') {
10195: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
10196:     } elsif ($which eq '64bit') {
10197: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
10198:     }
10199:     return &rndseed_32bit($symb,$courseid,$domain,$username);
10200: }
10201: 
10202: sub rndseed_32bit {
10203:     my ($symb,$courseid,$domain,$username)=@_;
10204:     {
10205: 	use integer;
10206: 	my $symbchck=unpack("%32C*",$symb) << 27;
10207: 	my $symbseed=numval($symb) << 22;
10208: 	my $namechck=unpack("%32C*",$username) << 17;
10209: 	my $nameseed=numval($username) << 12;
10210: 	my $domainseed=unpack("%32C*",$domain) << 7;
10211: 	my $courseseed=unpack("%32C*",$courseid);
10212: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
10213: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10214: 	#&logthis("rndseed :$num:$symb");
10215: 	if ($_64bit) { $num=(($num<<32)>>32); }
10216: 	return $num;
10217:     }
10218: }
10219: 
10220: sub rndseed_64bit {
10221:     my ($symb,$courseid,$domain,$username)=@_;
10222:     {
10223: 	use integer;
10224: 	my $symbchck=unpack("%32S*",$symb) << 21;
10225: 	my $symbseed=numval($symb) << 10;
10226: 	my $namechck=unpack("%32S*",$username);
10227: 	
10228: 	my $nameseed=numval($username) << 21;
10229: 	my $domainseed=unpack("%32S*",$domain) << 10;
10230: 	my $courseseed=unpack("%32S*",$courseid);
10231: 	
10232: 	my $num1=$symbchck+$symbseed+$namechck;
10233: 	my $num2=$nameseed+$domainseed+$courseseed;
10234: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10235: 	#&logthis("rndseed :$num:$symb");
10236: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10237: 	return "$num1,$num2";
10238:     }
10239: }
10240: 
10241: sub rndseed_64bit2 {
10242:     my ($symb,$courseid,$domain,$username)=@_;
10243:     {
10244: 	use integer;
10245: 	# strings need to be an even # of cahracters long, it it is odd the
10246:         # last characters gets thrown away
10247: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
10248: 	my $symbseed=numval($symb) << 10;
10249: 	my $namechck=unpack("%32S*",$username.' ');
10250: 	
10251: 	my $nameseed=numval($username) << 21;
10252: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
10253: 	my $courseseed=unpack("%32S*",$courseid.' ');
10254: 	
10255: 	my $num1=$symbchck+$symbseed+$namechck;
10256: 	my $num2=$nameseed+$domainseed+$courseseed;
10257: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10258: 	#&logthis("rndseed :$num:$symb");
10259: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10260: 	return "$num1,$num2";
10261:     }
10262: }
10263: 
10264: sub rndseed_64bit3 {
10265:     my ($symb,$courseid,$domain,$username)=@_;
10266:     {
10267: 	use integer;
10268: 	# strings need to be an even # of cahracters long, it it is odd the
10269:         # last characters gets thrown away
10270: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
10271: 	my $symbseed=numval2($symb) << 10;
10272: 	my $namechck=unpack("%32S*",$username.' ');
10273: 	
10274: 	my $nameseed=numval2($username) << 21;
10275: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
10276: 	my $courseseed=unpack("%32S*",$courseid.' ');
10277: 	
10278: 	my $num1=$symbchck+$symbseed+$namechck;
10279: 	my $num2=$nameseed+$domainseed+$courseseed;
10280: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10281: 	#&logthis("rndseed :$num1:$num2:$_64bit");
10282: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10283: 	
10284: 	return "$num1:$num2";
10285:     }
10286: }
10287: 
10288: sub rndseed_64bit4 {
10289:     my ($symb,$courseid,$domain,$username)=@_;
10290:     {
10291: 	use integer;
10292: 	# strings need to be an even # of cahracters long, it it is odd the
10293:         # last characters gets thrown away
10294: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
10295: 	my $symbseed=numval3($symb) << 10;
10296: 	my $namechck=unpack("%32S*",$username.' ');
10297: 	
10298: 	my $nameseed=numval3($username) << 21;
10299: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
10300: 	my $courseseed=unpack("%32S*",$courseid.' ');
10301: 	
10302: 	my $num1=$symbchck+$symbseed+$namechck;
10303: 	my $num2=$nameseed+$domainseed+$courseseed;
10304: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10305: 	#&logthis("rndseed :$num1:$num2:$_64bit");
10306: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10307: 	
10308: 	return "$num1:$num2";
10309:     }
10310: }
10311: 
10312: sub rndseed_64bit5 {
10313:     my ($symb,$courseid,$domain,$username)=@_;
10314:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
10315:     return "$num1:$num2";
10316: }
10317: 
10318: sub rndseed_CODE_64bit {
10319:     my ($symb,$courseid,$domain,$username)=@_;
10320:     {
10321: 	use integer;
10322: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
10323: 	my $symbseed=numval2($symb);
10324: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
10325: 	my $CODEseed=numval(&getCODE());
10326: 	my $courseseed=unpack("%32S*",$courseid.' ');
10327: 	my $num1=$symbseed+$CODEchck;
10328: 	my $num2=$CODEseed+$courseseed+$symbchck;
10329: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
10330: 	#&logthis("rndseed :$num1:$num2:$symb");
10331: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
10332: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
10333: 	return "$num1:$num2";
10334:     }
10335: }
10336: 
10337: sub rndseed_CODE_64bit4 {
10338:     my ($symb,$courseid,$domain,$username)=@_;
10339:     {
10340: 	use integer;
10341: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
10342: 	my $symbseed=numval3($symb);
10343: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
10344: 	my $CODEseed=numval3(&getCODE());
10345: 	my $courseseed=unpack("%32S*",$courseid.' ');
10346: 	my $num1=$symbseed+$CODEchck;
10347: 	my $num2=$CODEseed+$courseseed+$symbchck;
10348: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
10349: 	#&logthis("rndseed :$num1:$num2:$symb");
10350: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
10351: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
10352: 	return "$num1:$num2";
10353:     }
10354: }
10355: 
10356: sub rndseed_CODE_64bit5 {
10357:     my ($symb,$courseid,$domain,$username)=@_;
10358:     my $code = &getCODE();
10359:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
10360:     return "$num1:$num2";
10361: }
10362: 
10363: sub setup_random_from_rndseed {
10364:     my ($rndseed)=@_;
10365:     if ($rndseed =~/([,:])/) {
10366: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
10367: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
10368:     } else {
10369: 	&Math::Random::random_set_seed_from_phrase($rndseed);
10370:     }
10371: }
10372: 
10373: sub latest_receipt_algorithm_id {
10374:     return 'receipt3';
10375: }
10376: 
10377: sub recunique {
10378:     my $fucourseid=shift;
10379:     my $unique;
10380:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
10381: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
10382: 	$unique=$env{"course.$fucourseid.internal.encseed"};
10383:     } else {
10384: 	$unique=$perlvar{'lonReceipt'};
10385:     }
10386:     return unpack("%32C*",$unique);
10387: }
10388: 
10389: sub recprefix {
10390:     my $fucourseid=shift;
10391:     my $prefix;
10392:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
10393: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
10394: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
10395:     } else {
10396: 	$prefix=$perlvar{'lonHostID'};
10397:     }
10398:     return unpack("%32C*",$prefix);
10399: }
10400: 
10401: sub ireceipt {
10402:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
10403: 
10404:     my $return =&recprefix($fucourseid).'-';
10405: 
10406:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
10407: 	$env{'request.state'} eq 'construct') {
10408: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
10409: 	return $return;
10410:     }
10411: 
10412:     my $cuname=unpack("%32C*",$funame);
10413:     my $cudom=unpack("%32C*",$fudom);
10414:     my $cucourseid=unpack("%32C*",$fucourseid);
10415:     my $cusymb=unpack("%32C*",$fusymb);
10416:     my $cunique=&recunique($fucourseid);
10417:     my $cpart=unpack("%32S*",$part);
10418:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
10419: 
10420: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
10421: 			       
10422: 	$return.= ($cunique%$cuname+
10423: 		   $cunique%$cudom+
10424: 		   $cusymb%$cuname+
10425: 		   $cusymb%$cudom+
10426: 		   $cucourseid%$cuname+
10427: 		   $cucourseid%$cudom+
10428: 		   $cpart%$cuname+
10429: 		   $cpart%$cudom);
10430:     } else {
10431: 	$return.= ($cunique%$cuname+
10432: 		   $cunique%$cudom+
10433: 		   $cusymb%$cuname+
10434: 		   $cusymb%$cudom+
10435: 		   $cucourseid%$cuname+
10436: 		   $cucourseid%$cudom);
10437:     }
10438:     return $return;
10439: }
10440: 
10441: sub receipt {
10442:     my ($part)=@_;
10443:     my ($symb,$courseid,$domain,$name) = &whichuser();
10444:     return &ireceipt($name,$domain,$courseid,$symb,$part);
10445: }
10446: 
10447: sub whichuser {
10448:     my ($passedsymb)=@_;
10449:     my ($symb,$courseid,$domain,$name,$publicuser);
10450:     if (defined($env{'form.grade_symb'})) {
10451: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
10452: 	my $allowed=&allowed('vgr',$tmp_courseid);
10453: 	if (!$allowed &&
10454: 	    exists($env{'request.course.sec'}) &&
10455: 	    $env{'request.course.sec'} !~ /^\s*$/) {
10456: 	    $allowed=&allowed('vgr',$tmp_courseid.
10457: 			      '/'.$env{'request.course.sec'});
10458: 	}
10459: 	if ($allowed) {
10460: 	    ($symb)=&get_env_multiple('form.grade_symb');
10461: 	    $courseid=$tmp_courseid;
10462: 	    ($domain)=&get_env_multiple('form.grade_domain');
10463: 	    ($name)=&get_env_multiple('form.grade_username');
10464: 	    return ($symb,$courseid,$domain,$name,$publicuser);
10465: 	}
10466:     }
10467:     if (!$passedsymb) {
10468: 	$symb=&symbread();
10469:     } else {
10470: 	$symb=$passedsymb;
10471:     }
10472:     $courseid=$env{'request.course.id'};
10473:     $domain=$env{'user.domain'};
10474:     $name=$env{'user.name'};
10475:     if ($name eq 'public' && $domain eq 'public') {
10476: 	if (!defined($env{'form.username'})) {
10477: 	    $env{'form.username'}.=time.rand(10000000);
10478: 	}
10479: 	$name.=$env{'form.username'};
10480:     }
10481:     return ($symb,$courseid,$domain,$name,$publicuser);
10482: 
10483: }
10484: 
10485: # ------------------------------------------------------------ Serves up a file
10486: # returns either the contents of the file or 
10487: # -1 if the file doesn't exist
10488: #
10489: # if the target is a file that was uploaded via DOCS, 
10490: # a check will be made to see if a current copy exists on the local server,
10491: # if it does this will be served, otherwise a copy will be retrieved from
10492: # the home server for the course and stored in /home/httpd/html/userfiles on
10493: # the local server.   
10494: 
10495: sub getfile {
10496:     my ($file) = @_;
10497:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
10498:     &repcopy($file);
10499:     return &readfile($file);
10500: }
10501: 
10502: sub repcopy_userfile {
10503:     my ($file)=@_;
10504:     my $londocroot = $perlvar{'lonDocRoot'};
10505:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
10506:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
10507:     my ($cdom,$cnum,$filename) = 
10508: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
10509:     my $uri="/uploaded/$cdom/$cnum/$filename";
10510:     if (-e "$file") {
10511: # we already have a local copy, check it out
10512: 	my @fileinfo = stat($file);
10513: 	my $rtncode;
10514: 	my $info;
10515: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
10516: 	if ($lwpresp ne 'ok') {
10517: # there is no such file anymore, even though we had a local copy
10518: 	    if ($rtncode eq '404') {
10519: 		unlink($file);
10520: 	    }
10521: 	    return -1;
10522: 	}
10523: 	if ($info < $fileinfo[9]) {
10524: # nice, the file we have is up-to-date, just say okay
10525: 	    return 'ok';
10526: 	} else {
10527: # the file is outdated, get rid of it
10528: 	    unlink($file);
10529: 	}
10530:     }
10531: # one way or the other, at this point, we don't have the file
10532: # construct the correct path for the file
10533:     my @parts = ($cdom,$cnum); 
10534:     if ($filename =~ m|^(.+)/[^/]+$|) {
10535: 	push @parts, split(/\//,$1);
10536:     }
10537:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
10538:     foreach my $part (@parts) {
10539: 	$path .= '/'.$part;
10540: 	if (!-e $path) {
10541: 	    mkdir($path,0770);
10542: 	}
10543:     }
10544: # now the path exists for sure
10545: # get a user agent
10546:     my $ua=new LWP::UserAgent;
10547:     my $transferfile=$file.'.in.transfer';
10548: # FIXME: this should flock
10549:     if (-e $transferfile) { return 'ok'; }
10550:     my $request;
10551:     $uri=~s/^\///;
10552:     my $homeserver = &homeserver($cnum,$cdom);
10553:     my $protocol = $protocol{$homeserver};
10554:     $protocol = 'http' if ($protocol ne 'https');
10555:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
10556:     my $response=$ua->request($request,$transferfile);
10557: # did it work?
10558:     if ($response->is_error()) {
10559: 	unlink($transferfile);
10560: 	&logthis("Userfile repcopy failed for $uri");
10561: 	return -1;
10562:     }
10563: # worked, rename the transfer file
10564:     rename($transferfile,$file);
10565:     return 'ok';
10566: }
10567: 
10568: sub tokenwrapper {
10569:     my $uri=shift;
10570:     $uri=~s|^https?\://([^/]+)||;
10571:     $uri=~s|^/||;
10572:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
10573:     my $token=$1;
10574:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
10575:     if ($udom && $uname && $file) {
10576: 	$file=~s|(\?\.*)*$||;
10577:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
10578:         my $homeserver = &homeserver($uname,$udom);
10579:         my $protocol = $protocol{$homeserver};
10580:         $protocol = 'http' if ($protocol ne 'https');
10581:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
10582:                (($uri=~/\?/)?'&':'?').'token='.$token.
10583:                                '&tokenissued='.$perlvar{'lonHostID'};
10584:     } else {
10585:         return '/adm/notfound.html';
10586:     }
10587: }
10588: 
10589: # call with reqtype HEAD: get last modification time
10590: # call with reqtype GET: get the file contents
10591: # Do not call this with reqtype GET for large files! It loads everything into memory
10592: #
10593: sub getuploaded {
10594:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
10595:     $uri=~s/^\///;
10596:     my $homeserver = &homeserver($cnum,$cdom);
10597:     my $protocol = $protocol{$homeserver};
10598:     $protocol = 'http' if ($protocol ne 'https');
10599:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
10600:     my $ua=new LWP::UserAgent;
10601:     my $request=new HTTP::Request($reqtype,$uri);
10602:     my $response=$ua->request($request);
10603:     $$rtncode = $response->code;
10604:     if (! $response->is_success()) {
10605: 	return 'failed';
10606:     }      
10607:     if ($reqtype eq 'HEAD') {
10608: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
10609:     } elsif ($reqtype eq 'GET') {
10610: 	$$info = $response->content;
10611:     }
10612:     return 'ok';
10613: }
10614: 
10615: sub readfile {
10616:     my $file = shift;
10617:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
10618:     my $fh;
10619:     open($fh,"<$file");
10620:     my $a='';
10621:     while (my $line = <$fh>) { $a .= $line; }
10622:     return $a;
10623: }
10624: 
10625: sub filelocation {
10626:     my ($dir,$file) = @_;
10627:     my $location;
10628:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
10629: 
10630:     if ($file =~ m-^/adm/-) {
10631: 	$file=~s-^/adm/wrapper/-/-;
10632: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
10633:     }
10634: 
10635:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
10636:         $location = $file;
10637:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
10638:         my ($udom,$uname,$filename)=
10639:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
10640:         my $home=&homeserver($uname,$udom);
10641:         my $is_me=0;
10642:         my @ids=&current_machine_ids();
10643:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
10644:         if ($is_me) {
10645:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
10646:         } else {
10647:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
10648:   	      $udom.'/'.$uname.'/'.$filename;
10649:         }
10650:     } elsif ($file =~ m-^/adm/-) {
10651: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
10652:     } else {
10653:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
10654:         $file=~s:^/(res|priv)/:/:;
10655:         my $space=$1;
10656:         if ( !( $file =~ m:^/:) ) {
10657:             $location = $dir. '/'.$file;
10658:         } else {
10659:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
10660:         }
10661:     }
10662:     $location=~s://+:/:g; # remove duplicate /
10663:     while ($location=~m{/\.\./}) {
10664: 	if ($location =~ m{/[^/]+/\.\./}) {
10665: 	    $location=~ s{/[^/]+/\.\./}{/}g;
10666: 	} else {
10667: 	    $location=~ s{/\.\./}{/}g;
10668: 	}
10669:     } #remove dir/..
10670:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
10671:     return $location;
10672: }
10673: 
10674: sub hreflocation {
10675:     my ($dir,$file)=@_;
10676:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
10677: 	$file=filelocation($dir,$file);
10678:     } elsif ($file=~m-^/adm/-) {
10679: 	$file=~s-^/adm/wrapper/-/-;
10680: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
10681:     }
10682:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
10683: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
10684:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
10685: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
10686: 	        {/uploaded/$1/$2/}x;
10687:     }
10688:     if ($file=~ m{^/userfiles/}) {
10689: 	$file =~ s{^/userfiles/}{/uploaded/};
10690:     }
10691:     return $file;
10692: }
10693: 
10694: 
10695: 
10696: 
10697: 
10698: sub current_machine_domains {
10699:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
10700: }
10701: 
10702: sub machine_domains {
10703:     my ($hostname) = @_;
10704:     my @domains;
10705:     my %hostname = &all_hostnames();
10706:     while( my($id, $name) = each(%hostname)) {
10707: #	&logthis("-$id-$name-$hostname-");
10708: 	if ($hostname eq $name) {
10709: 	    push(@domains,&host_domain($id));
10710: 	}
10711:     }
10712:     return @domains;
10713: }
10714: 
10715: sub current_machine_ids {
10716:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
10717: }
10718: 
10719: sub machine_ids {
10720:     my ($hostname) = @_;
10721:     $hostname ||= &hostname($perlvar{'lonHostID'});
10722:     my @ids;
10723:     my %name_to_host = &all_names();
10724:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
10725: 	return @{ $name_to_host{$hostname} };
10726:     }
10727:     return;
10728: }
10729: 
10730: sub additional_machine_domains {
10731:     my @domains;
10732:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
10733:     while( my $line = <$fh>) {
10734:         $line =~ s/\s//g;
10735:         push(@domains,$line);
10736:     }
10737:     return @domains;
10738: }
10739: 
10740: sub default_login_domain {
10741:     my $domain = $perlvar{'lonDefDomain'};
10742:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
10743:     foreach my $posdom (&current_machine_domains(),
10744:                         &additional_machine_domains()) {
10745:         if (lc($posdom) eq lc($testdomain)) {
10746:             $domain=$posdom;
10747:             last;
10748:         }
10749:     }
10750:     return $domain;
10751: }
10752: 
10753: # ------------------------------------------------------------- Declutters URLs
10754: 
10755: sub declutter {
10756:     my $thisfn=shift;
10757:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
10758:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
10759:     $thisfn=~s/^\///;
10760:     $thisfn=~s|^adm/wrapper/||;
10761:     $thisfn=~s|^adm/coursedocs/showdoc/||;
10762:     $thisfn=~s/^res\///;
10763:     $thisfn=~s/^priv\///;
10764:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
10765:         $thisfn=~s/\?.+$//;
10766:     }
10767:     return $thisfn;
10768: }
10769: 
10770: # ------------------------------------------------------------- Clutter up URLs
10771: 
10772: sub clutter {
10773:     my $thisfn='/'.&declutter(shift);
10774:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
10775: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
10776:        $thisfn='/res'.$thisfn; 
10777:     }
10778:     if ($thisfn !~m|^/adm|) {
10779: 	if ($thisfn =~ m|^/ext/|) {
10780: 	    $thisfn='/adm/wrapper'.$thisfn;
10781: 	} else {
10782: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
10783: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
10784: 	    if ($embstyle eq 'ssi'
10785: 		|| ($embstyle eq 'hdn')
10786: 		|| ($embstyle eq 'rat')
10787: 		|| ($embstyle eq 'prv')
10788: 		|| ($embstyle eq 'ign')) {
10789: 		#do nothing with these
10790: 	    } elsif (($embstyle eq 'img') 
10791: 		|| ($embstyle eq 'emb')
10792: 		|| ($embstyle eq 'wrp')) {
10793: 		$thisfn='/adm/wrapper'.$thisfn;
10794: 	    } elsif ($embstyle eq 'unk'
10795: 		     && $thisfn!~/\.(sequence|page)$/) {
10796: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
10797: 	    } else {
10798: #		&logthis("Got a blank emb style");
10799: 	    }
10800: 	}
10801:     }
10802:     return $thisfn;
10803: }
10804: 
10805: sub clutter_with_no_wrapper {
10806:     my $uri = &clutter(shift);
10807:     if ($uri =~ m-^/adm/-) {
10808: 	$uri =~ s-^/adm/wrapper/-/-;
10809: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
10810:     }
10811:     return $uri;
10812: }
10813: 
10814: sub freeze_escape {
10815:     my ($value)=@_;
10816:     if (ref($value)) {
10817: 	$value=&nfreeze($value);
10818: 	return '__FROZEN__'.&escape($value);
10819:     }
10820:     return &escape($value);
10821: }
10822: 
10823: 
10824: sub thaw_unescape {
10825:     my ($value)=@_;
10826:     if ($value =~ /^__FROZEN__/) {
10827: 	substr($value,0,10,undef);
10828: 	$value=&unescape($value);
10829: 	return &thaw($value);
10830:     }
10831:     return &unescape($value);
10832: }
10833: 
10834: sub correct_line_ends {
10835:     my ($result)=@_;
10836:     $$result =~s/\r\n/\n/mg;
10837:     $$result =~s/\r/\n/mg;
10838: }
10839: # ================================================================ Main Program
10840: 
10841: sub goodbye {
10842:    &logthis("Starting Shut down");
10843: #not converted to using infrastruture and probably shouldn't be
10844:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
10845: #converted
10846: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
10847:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
10848: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
10849: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
10850: #1.1 only
10851: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
10852: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
10853: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
10854: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
10855:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
10856:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
10857:    &logthis(sprintf("%-20s is %s",'hits',$hits));
10858:    &flushcourselogs();
10859:    &logthis("Shutting down");
10860: }
10861: 
10862: sub get_dns {
10863:     my ($url,$func,$ignore_cache) = @_;
10864:     if (!$ignore_cache) {
10865: 	my ($content,$cached)=
10866: 	    &Apache::lonnet::is_cached_new('dns',$url);
10867: 	if ($cached) {
10868: 	    &$func($content);
10869: 	    return;
10870: 	}
10871:     }
10872: 
10873:     my %alldns;
10874:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
10875:     foreach my $dns (<$config>) {
10876: 	next if ($dns !~ /^\^(\S*)/x);
10877:         my $line = $1;
10878:         my ($host,$protocol) = split(/:/,$line);
10879:         if ($protocol ne 'https') {
10880:             $protocol = 'http';
10881:         }
10882: 	$alldns{$host} = $protocol;
10883:     }
10884:     while (%alldns) {
10885: 	my ($dns) = keys(%alldns);
10886: 	my $ua=new LWP::UserAgent;
10887:         $ua->timeout(30);
10888: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
10889: 	my $response=$ua->request($request);
10890:         delete($alldns{$dns});
10891: 	next if ($response->is_error());
10892: 	my @content = split("\n",$response->content);
10893: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
10894: 	&$func(\@content);
10895: 	return;
10896:     }
10897:     close($config);
10898:     my $which = (split('/',$url))[3];
10899:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
10900:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
10901:     my @content = <$config>;
10902:     &$func(\@content);
10903:     return;
10904: }
10905: # ------------------------------------------------------------ Read domain file
10906: {
10907:     my $loaded;
10908:     my %domain;
10909: 
10910:     sub parse_domain_tab {
10911: 	my ($lines) = @_;
10912: 	foreach my $line (@$lines) {
10913: 	    next if ($line =~ /^(\#|\s*$ )/x);
10914: 
10915: 	    chomp($line);
10916: 	    my ($name,@elements) = split(/:/,$line,9);
10917: 	    my %this_domain;
10918: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
10919: 			       'lang_def', 'city', 'longi', 'lati',
10920: 			       'primary') {
10921: 		$this_domain{$field} = shift(@elements);
10922: 	    }
10923: 	    $domain{$name} = \%this_domain;
10924: 	}
10925:     }
10926: 
10927:     sub reset_domain_info {
10928: 	undef($loaded);
10929: 	undef(%domain);
10930:     }
10931: 
10932:     sub load_domain_tab {
10933: 	my ($ignore_cache) = @_;
10934: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
10935: 	my $fh;
10936: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
10937: 	    my @lines = <$fh>;
10938: 	    &parse_domain_tab(\@lines);
10939: 	}
10940: 	close($fh);
10941: 	$loaded = 1;
10942:     }
10943: 
10944:     sub domain {
10945: 	&load_domain_tab() if (!$loaded);
10946: 
10947: 	my ($name,$what) = @_;
10948: 	return if ( !exists($domain{$name}) );
10949: 
10950: 	if (!$what) {
10951: 	    return $domain{$name}{'description'};
10952: 	}
10953: 	return $domain{$name}{$what};
10954:     }
10955: 
10956:     sub domain_info {
10957:         &load_domain_tab() if (!$loaded);
10958:         return %domain;
10959:     }
10960: 
10961: }
10962: 
10963: 
10964: # ------------------------------------------------------------- Read hosts file
10965: {
10966:     my %hostname;
10967:     my %hostdom;
10968:     my %libserv;
10969:     my $loaded;
10970:     my %name_to_host;
10971:     my %internetdom;
10972:     my %LC_dns_serv;
10973: 
10974:     sub parse_hosts_tab {
10975: 	my ($file) = @_;
10976: 	foreach my $configline (@$file) {
10977: 	    next if ($configline =~ /^(\#|\s*$ )/x);
10978:             chomp($configline);
10979: 	    if ($configline =~ /^\^/) {
10980:                 if ($configline =~ /^\^([\w.\-]+)/) {
10981:                     $LC_dns_serv{$1} = 1;
10982:                 }
10983:                 next;
10984:             }
10985: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
10986: 	    $name=~s/\s//g;
10987: 	    if ($id && $domain && $role && $name) {
10988: 		$hostname{$id}=$name;
10989: 		push(@{$name_to_host{$name}}, $id);
10990: 		$hostdom{$id}=$domain;
10991: 		if ($role eq 'library') { $libserv{$id}=$name; }
10992:                 if (defined($protocol)) {
10993:                     if ($protocol eq 'https') {
10994:                         $protocol{$id} = $protocol;
10995:                     } else {
10996:                         $protocol{$id} = 'http'; 
10997:                     }
10998:                 } else {
10999:                     $protocol{$id} = 'http';
11000:                 }
11001:                 if (defined($intdom)) {
11002:                     $internetdom{$id} = $intdom;
11003:                 }
11004: 	    }
11005: 	}
11006:     }
11007:     
11008:     sub reset_hosts_info {
11009: 	&purge_remembered();
11010: 	&reset_domain_info();
11011: 	&reset_hosts_ip_info();
11012: 	undef(%name_to_host);
11013: 	undef(%hostname);
11014: 	undef(%hostdom);
11015: 	undef(%libserv);
11016: 	undef($loaded);
11017:     }
11018: 
11019:     sub load_hosts_tab {
11020: 	my ($ignore_cache) = @_;
11021: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
11022: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11023: 	my @config = <$config>;
11024: 	&parse_hosts_tab(\@config);
11025: 	close($config);
11026: 	$loaded=1;
11027:     }
11028: 
11029:     sub hostname {
11030: 	&load_hosts_tab() if (!$loaded);
11031: 
11032: 	my ($lonid) = @_;
11033: 	return $hostname{$lonid};
11034:     }
11035: 
11036:     sub all_hostnames {
11037: 	&load_hosts_tab() if (!$loaded);
11038: 
11039: 	return %hostname;
11040:     }
11041: 
11042:     sub all_names {
11043: 	&load_hosts_tab() if (!$loaded);
11044: 
11045: 	return %name_to_host;
11046:     }
11047: 
11048:     sub all_host_domain {
11049:         &load_hosts_tab() if (!$loaded);
11050:         return %hostdom;
11051:     }
11052: 
11053:     sub is_library {
11054: 	&load_hosts_tab() if (!$loaded);
11055: 
11056: 	return exists($libserv{$_[0]});
11057:     }
11058: 
11059:     sub all_library {
11060: 	&load_hosts_tab() if (!$loaded);
11061: 
11062: 	return %libserv;
11063:     }
11064: 
11065:     sub unique_library {
11066: 	#2x reverse removes all hostnames that appear more than once
11067:         my %unique = reverse &all_library();
11068:         return reverse %unique;
11069:     }
11070: 
11071:     sub get_servers {
11072: 	&load_hosts_tab() if (!$loaded);
11073: 
11074: 	my ($domain,$type) = @_;
11075: 	my %possible_hosts = ($type eq 'library') ? %libserv
11076: 	                                          : %hostname;
11077: 	my %result;
11078: 	if (ref($domain) eq 'ARRAY') {
11079: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
11080: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
11081: 		    $result{$host} = $hostname;
11082: 		}
11083: 	    }
11084: 	} else {
11085: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
11086: 		if ($hostdom{$host} eq $domain) {
11087: 		    $result{$host} = $hostname;
11088: 		}
11089: 	    }
11090: 	}
11091: 	return %result;
11092:     }
11093: 
11094:     sub get_unique_servers {
11095:         my %unique = reverse &get_servers(@_);
11096: 	return reverse %unique;
11097:     }
11098: 
11099:     sub host_domain {
11100: 	&load_hosts_tab() if (!$loaded);
11101: 
11102: 	my ($lonid) = @_;
11103: 	return $hostdom{$lonid};
11104:     }
11105: 
11106:     sub all_domains {
11107: 	&load_hosts_tab() if (!$loaded);
11108: 
11109: 	my %seen;
11110: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
11111: 	return @uniq;
11112:     }
11113: 
11114:     sub internet_dom {
11115:         &load_hosts_tab() if (!$loaded);
11116: 
11117:         my ($lonid) = @_;
11118:         return $internetdom{$lonid};
11119:     }
11120: 
11121:     sub is_LC_dns {
11122:         &load_hosts_tab() if (!$loaded);
11123: 
11124:         my ($hostname) = @_;
11125:         return exists($LC_dns_serv{$hostname});
11126:     }
11127: 
11128: }
11129: 
11130: { 
11131:     my %iphost;
11132:     my %name_to_ip;
11133:     my %lonid_to_ip;
11134: 
11135:     sub get_hosts_from_ip {
11136: 	my ($ip) = @_;
11137: 	my %iphosts = &get_iphost();
11138: 	if (ref($iphosts{$ip})) {
11139: 	    return @{$iphosts{$ip}};
11140: 	}
11141: 	return;
11142:     }
11143:     
11144:     sub reset_hosts_ip_info {
11145: 	undef(%iphost);
11146: 	undef(%name_to_ip);
11147: 	undef(%lonid_to_ip);
11148:     }
11149: 
11150:     sub get_host_ip {
11151: 	my ($lonid) = @_;
11152: 	if (exists($lonid_to_ip{$lonid})) {
11153: 	    return $lonid_to_ip{$lonid};
11154: 	}
11155: 	my $name=&hostname($lonid);
11156:    	my $ip = gethostbyname($name);
11157: 	return if (!$ip || length($ip) ne 4);
11158: 	$ip=inet_ntoa($ip);
11159: 	$name_to_ip{$name}   = $ip;
11160: 	$lonid_to_ip{$lonid} = $ip;
11161: 	return $ip;
11162:     }
11163:     
11164:     sub get_iphost {
11165: 	my ($ignore_cache) = @_;
11166: 
11167: 	if (!$ignore_cache) {
11168: 	    if (%iphost) {
11169: 		return %iphost;
11170: 	    }
11171: 	    my ($ip_info,$cached)=
11172: 		&Apache::lonnet::is_cached_new('iphost','iphost');
11173: 	    if ($cached) {
11174: 		%iphost      = %{$ip_info->[0]};
11175: 		%name_to_ip  = %{$ip_info->[1]};
11176: 		%lonid_to_ip = %{$ip_info->[2]};
11177: 		return %iphost;
11178: 	    }
11179: 	}
11180: 
11181: 	# get yesterday's info for fallback
11182: 	my %old_name_to_ip;
11183: 	my ($ip_info,$cached)=
11184: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
11185: 	if ($cached) {
11186: 	    %old_name_to_ip = %{$ip_info->[1]};
11187: 	}
11188: 
11189: 	my %name_to_host = &all_names();
11190: 	foreach my $name (keys(%name_to_host)) {
11191: 	    my $ip;
11192: 	    if (!exists($name_to_ip{$name})) {
11193: 		$ip = gethostbyname($name);
11194: 		if (!$ip || length($ip) ne 4) {
11195: 		    if (defined($old_name_to_ip{$name})) {
11196: 			$ip = $old_name_to_ip{$name};
11197: 			&logthis("Can't find $name defaulting to old $ip");
11198: 		    } else {
11199: 			&logthis("Name $name no IP found");
11200: 			next;
11201: 		    }
11202: 		} else {
11203: 		    $ip=inet_ntoa($ip);
11204: 		}
11205: 		$name_to_ip{$name} = $ip;
11206: 	    } else {
11207: 		$ip = $name_to_ip{$name};
11208: 	    }
11209: 	    foreach my $id (@{ $name_to_host{$name} }) {
11210: 		$lonid_to_ip{$id} = $ip;
11211: 	    }
11212: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
11213: 	}
11214: 	&Apache::lonnet::do_cache_new('iphost','iphost',
11215: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
11216: 				      48*60*60);
11217: 
11218: 	return %iphost;
11219:     }
11220: 
11221:     #
11222:     #  Given a DNS returns the loncapa host name for that DNS 
11223:     # 
11224:     sub host_from_dns {
11225:         my ($dns) = @_;
11226:         my @hosts;
11227:         my $ip;
11228: 
11229:         if (exists($name_to_ip{$dns})) {
11230:             $ip = $name_to_ip{$dns};
11231:         }
11232:         if (!$ip) {
11233:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
11234:             if (length($ip) == 4) { 
11235: 	        $ip   = &IO::Socket::inet_ntoa($ip);
11236:             }
11237:         }
11238:         if ($ip) {
11239: 	    @hosts = get_hosts_from_ip($ip);
11240: 	    return $hosts[0];
11241:         }
11242:         return undef;
11243:     }
11244: 
11245:     sub get_internet_names {
11246:         my ($lonid) = @_;
11247:         return if ($lonid eq '');
11248:         my ($idnref,$cached)=
11249:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
11250:         if ($cached) {
11251:             return $idnref;
11252:         }
11253:         my $ip = &get_host_ip($lonid);
11254:         my @hosts = &get_hosts_from_ip($ip);
11255:         my %iphost = &get_iphost();
11256:         my (@idns,%seen);
11257:         foreach my $id (@hosts) {
11258:             my $dom = &host_domain($id);
11259:             my $prim_id = &domain($dom,'primary');
11260:             my $prim_ip = &get_host_ip($prim_id);
11261:             next if ($seen{$prim_ip});
11262:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
11263:                 foreach my $id (@{$iphost{$prim_ip}}) {
11264:                     my $intdom = &internet_dom($id);
11265:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
11266:                         push(@idns,$intdom);
11267:                     }
11268:                 }
11269:             }
11270:             $seen{$prim_ip} = 1;
11271:         }
11272:         return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
11273:     }
11274: 
11275: }
11276: 
11277: sub all_loncaparevs {
11278:     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);
11279: }
11280: 
11281: BEGIN {
11282: 
11283: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
11284:     unless ($readit) {
11285: {
11286:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
11287:     %perlvar = (%perlvar,%{$configvars});
11288: }
11289: 
11290: 
11291: # ------------------------------------------------------ Read spare server file
11292: {
11293:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
11294: 
11295:     while (my $configline=<$config>) {
11296:        chomp($configline);
11297:        if ($configline) {
11298: 	   my ($host,$type) = split(':',$configline,2);
11299: 	   if (!defined($type) || $type eq '') { $type = 'default' };
11300: 	   push(@{ $spareid{$type} }, $host);
11301:        }
11302:     }
11303:     close($config);
11304: }
11305: # ------------------------------------------------------------ Read permissions
11306: {
11307:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
11308: 
11309:     while (my $configline=<$config>) {
11310: 	chomp($configline);
11311: 	if ($configline) {
11312: 	    my ($role,$perm)=split(/ /,$configline);
11313: 	    if ($perm ne '') { $pr{$role}=$perm; }
11314: 	}
11315:     }
11316:     close($config);
11317: }
11318: 
11319: # -------------------------------------------- Read plain texts for permissions
11320: {
11321:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
11322: 
11323:     while (my $configline=<$config>) {
11324: 	chomp($configline);
11325: 	if ($configline) {
11326: 	    my ($short,@plain)=split(/:/,$configline);
11327:             %{$prp{$short}} = ();
11328: 	    if (@plain > 0) {
11329:                 $prp{$short}{'std'} = $plain[0];
11330:                 for (my $i=1; $i<@plain; $i++) {
11331:                     $prp{$short}{'alt'.$i} = $plain[$i];  
11332:                 }
11333:             }
11334: 	}
11335:     }
11336:     close($config);
11337: }
11338: 
11339: # ---------------------------------------------------------- Read package table
11340: {
11341:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
11342: 
11343:     while (my $configline=<$config>) {
11344: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
11345: 	chomp($configline);
11346: 	my ($short,$plain)=split(/:/,$configline);
11347: 	my ($pack,$name)=split(/\&/,$short);
11348: 	if ($plain ne '') {
11349: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
11350: 	    $packagetab{$short}=$plain; 
11351: 	}
11352:     }
11353:     close($config);
11354: }
11355: 
11356: # ---------------------------------------------------------- Read loncaparev table
11357: {
11358:     if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
11359:         if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
11360:             while (my $configline=<$config>) {
11361:                 chomp($configline);
11362:                 my ($hostid,$loncaparev)=split(/:/,$configline);
11363:                 $loncaparevs{$hostid}=$loncaparev;
11364:             }
11365:             close($config);
11366:         }
11367:     }
11368: }
11369: 
11370: # ---------------------------------------------------------- Read serverhostID table
11371: {
11372:     if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
11373:         if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
11374:             while (my $configline=<$config>) {
11375:                 chomp($configline);
11376:                 my ($name,$id)=split(/:/,$configline);
11377:                 $serverhomeIDs{$name}=$id;
11378:             }
11379:             close($config);
11380:         }
11381:     }
11382: }
11383: 
11384: {
11385:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
11386:     if (-e $file) {
11387:         my $parser = HTML::LCParser->new($file);
11388:         while (my $token = $parser->get_token()) {
11389:             if ($token->[0] eq 'S') {
11390:                 my $item = $token->[1];
11391:                 my $name = $token->[2]{'name'};
11392:                 my $value = $token->[2]{'value'};
11393:                 if ($item ne '' && $name ne '' && $value ne '') {
11394:                     my $release = $parser->get_text();
11395:                     $release =~ s/(^\s*|\s*$ )//gx;
11396:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
11397:                 }
11398:             }
11399:         }
11400:     }
11401: }
11402: 
11403: # ---------------------------------------------------------- Read managers table
11404: {
11405:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
11406:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
11407:             while (my $configline=<$config>) {
11408:                 chomp($configline);
11409:                 next if ($configline =~ /^\#/);
11410:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
11411:                     $managerstab{$configline} = 1;
11412:                 }
11413:             }
11414:             close($config);
11415:         }
11416:     }
11417: }
11418: 
11419: # ------------- set up temporary directory
11420: {
11421:     $tmpdir = LONCAPA::tempdir();
11422: 
11423: }
11424: 
11425: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
11426: 				'compress_threshold'=> 20_000,
11427:  			        });
11428: 
11429: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
11430: $dumpcount=0;
11431: $locknum=0;
11432: 
11433: &logtouch();
11434: &logthis('<font color="yellow">INFO: Read configuration</font>');
11435: $readit=1;
11436:     {
11437: 	use integer;
11438: 	my $test=(2**32)+1;
11439: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
11440: 	&logthis(" Detected 64bit platform ($_64bit)");
11441:     }
11442: }
11443: }
11444: 
11445: 1;
11446: __END__
11447: 
11448: =pod
11449: 
11450: =head1 NAME
11451: 
11452: Apache::lonnet - Subroutines to ask questions about things in the network.
11453: 
11454: =head1 SYNOPSIS
11455: 
11456: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
11457: 
11458:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
11459: 
11460: Common parameters:
11461: 
11462: =over 4
11463: 
11464: =item *
11465: 
11466: $uname : an internal username (if $cname expecting a course Id specifically)
11467: 
11468: =item *
11469: 
11470: $udom : a domain (if $cdom expecting a course's domain specifically)
11471: 
11472: =item *
11473: 
11474: $symb : a resource instance identifier
11475: 
11476: =item *
11477: 
11478: $namespace : the name of a .db file that contains the data needed or
11479: being set.
11480: 
11481: =back
11482: 
11483: =head1 OVERVIEW
11484: 
11485: lonnet provides subroutines which interact with the
11486: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
11487: about classes, users, and resources.
11488: 
11489: For many of these objects you can also use this to store data about
11490: them or modify them in various ways.
11491: 
11492: =head2 Symbs
11493: 
11494: To identify a specific instance of a resource, LON-CAPA uses symbols
11495: or "symbs"X<symb>. These identifiers are built from the URL of the
11496: map, the resource number of the resource in the map, and the URL of
11497: the resource itself. The latter is somewhat redundant, but might help
11498: if maps change.
11499: 
11500: An example is
11501: 
11502:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
11503: 
11504: The respective map entry is
11505: 
11506:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
11507:   title="Problem 2">
11508:  </resource>
11509: 
11510: Symbs are used by the random number generator, as well as to store and
11511: restore data specific to a certain instance of for example a problem.
11512: 
11513: =head2 Storing And Retrieving Data
11514: 
11515: X<store()>X<cstore()>X<restore()>Three of the most important functions
11516: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
11517: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
11518: is is the non-critical message twin of cstore. These functions are for
11519: handlers to store a perl hash to a user's permanent data space in an
11520: easy manner, and to retrieve it again on another call. It is expected
11521: that a handler would use this once at the beginning to retrieve data,
11522: and then again once at the end to send only the new data back.
11523: 
11524: The data is stored in the user's data directory on the user's
11525: homeserver under the ID of the course.
11526: 
11527: The hash that is returned by restore will have all of the previous
11528: value for all of the elements of the hash.
11529: 
11530: Example:
11531: 
11532:  #creating a hash
11533:  my %hash;
11534:  $hash{'foo'}='bar';
11535: 
11536:  #storing it
11537:  &Apache::lonnet::cstore(\%hash);
11538: 
11539:  #changing a value
11540:  $hash{'foo'}='notbar';
11541: 
11542:  #adding a new value
11543:  $hash{'bar'}='foo';
11544:  &Apache::lonnet::cstore(\%hash);
11545: 
11546:  #retrieving the hash
11547:  my %history=&Apache::lonnet::restore();
11548: 
11549:  #print the hash
11550:  foreach my $key (sort(keys(%history))) {
11551:    print("\%history{$key} = $history{$key}");
11552:  }
11553: 
11554: Will print out:
11555: 
11556:  %history{1:foo} = bar
11557:  %history{1:keys} = foo:timestamp
11558:  %history{1:timestamp} = 990455579
11559:  %history{2:bar} = foo
11560:  %history{2:foo} = notbar
11561:  %history{2:keys} = foo:bar:timestamp
11562:  %history{2:timestamp} = 990455580
11563:  %history{bar} = foo
11564:  %history{foo} = notbar
11565:  %history{timestamp} = 990455580
11566:  %history{version} = 2
11567: 
11568: Note that the special hash entries C<keys>, C<version> and
11569: C<timestamp> were added to the hash. C<version> will be equal to the
11570: total number of versions of the data that have been stored. The
11571: C<timestamp> attribute will be the UNIX time the hash was
11572: stored. C<keys> is available in every historical section to list which
11573: keys were added or changed at a specific historical revision of a
11574: hash.
11575: 
11576: B<Warning>: do not store the hash that restore returns directly. This
11577: will cause a mess since it will restore the historical keys as if the
11578: were new keys. I.E. 1:foo will become 1:1:foo etc.
11579: 
11580: Calling convention:
11581: 
11582:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
11583:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
11584: 
11585: For more detailed information, see lonnet specific documentation.
11586: 
11587: =head1 RETURN MESSAGES
11588: 
11589: =over 4
11590: 
11591: =item * B<con_lost>: unable to contact remote host
11592: 
11593: =item * B<con_delayed>: unable to contact remote host, message will be delivered
11594: when the connection is brought back up
11595: 
11596: =item * B<con_failed>: unable to contact remote host and unable to save message
11597: for later delivery
11598: 
11599: =item * B<error:>: an error a occurred, a description of the error follows the :
11600: 
11601: =item * B<no_such_host>: unable to fund a host associated with the user/domain
11602: that was requested
11603: 
11604: =back
11605: 
11606: =head1 PUBLIC SUBROUTINES
11607: 
11608: =head2 Session Environment Functions
11609: 
11610: =over 4
11611: 
11612: =item * 
11613: X<appenv()>
11614: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
11615: the user envirnoment file, and will be restored for each access this
11616: user makes during this session, also modifies the %env for the current
11617: process. Optional rolesarrayref - if defined contains a reference to an array
11618: of roles which are exempt from the restriction on modifying user.role entries 
11619: in the user's environment.db and in %env.    
11620: 
11621: =item *
11622: X<delenv()>
11623: B<delenv($delthis,$regexp)>: removes all items from the session
11624: environment file that begin with $delthis. If the 
11625: optional second arg - $regexp - is true, $delthis is treated as a 
11626: regular expression, otherwise \Q$delthis\E is used. 
11627: The values are also deleted from the current processes %env.
11628: 
11629: =item * get_env_multiple($name) 
11630: 
11631: gets $name from the %env hash, it seemlessly handles the cases where multiple
11632: values may be defined and end up as an array ref.
11633: 
11634: returns an array of values
11635: 
11636: =back
11637: 
11638: =head2 User Information
11639: 
11640: =over 4
11641: 
11642: =item *
11643: X<queryauthenticate()>
11644: B<queryauthenticate($uname,$udom)>: try to determine user's current 
11645: authentication scheme
11646: 
11647: =item *
11648: X<authenticate()>
11649: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
11650: authenticate user from domain's lib servers (first use the current
11651: one). C<$upass> should be the users password.
11652: $checkdefauth is optional (value is 1 if a check should be made to
11653:    authenticate user using default authentication method, and allow
11654:    account creation if username does not have account in the domain).
11655: $clientcancheckhost is optional (value is 1 if checking whether the
11656:    server can host will occur on the client side in lonauth.pm).   
11657: 
11658: =item *
11659: X<homeserver()>
11660: B<homeserver($uname,$udom)>: find the server which has
11661: the user's directory and files (there must be only one), this caches
11662: the answer, and also caches if there is a borken connection.
11663: 
11664: =item *
11665: X<idget()>
11666: B<idget($udom,@ids)>: find the usernames behind a list of IDs
11667: (IDs are a unique resource in a domain, there must be only 1 ID per
11668: username, and only 1 username per ID in a specific domain) (returns
11669: hash: id=>name,id=>name)
11670: 
11671: =item *
11672: X<idrget()>
11673: B<idrget($udom,@unames)>: find the IDs behind a list of
11674: usernames (returns hash: name=>id,name=>id)
11675: 
11676: =item *
11677: X<idput()>
11678: B<idput($udom,%ids)>: store away a list of names and associated IDs
11679: 
11680: =item *
11681: X<rolesinit()>
11682: B<rolesinit($udom,$username)>: get user privileges.
11683: returns user role, first access and timer interval hashes
11684: 
11685: =item *
11686: X<privileged()>
11687: B<privileged($username,$domain)>: returns a true if user has a
11688: privileged and active role (i.e. su or dc), false otherwise.
11689: 
11690: =item *
11691: X<getsection()>
11692: B<getsection($udom,$uname,$cname)>: finds the section of student in the
11693: course $cname, return section name/number or '' for "not in course"
11694: and '-1' for "no section"
11695: 
11696: =item *
11697: X<userenvironment()>
11698: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
11699: passed in @what from the requested user's environment, returns a hash
11700: 
11701: =item * 
11702: X<userlog_query()>
11703: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
11704: activity.log file. %filters defines filters applied when parsing the
11705: log file. These can be start or end timestamps, or the type of action
11706: - log to look for Login or Logout events, check for Checkin or
11707: Checkout, role for role selection. The response is in the form
11708: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
11709: escaped strings of the action recorded in the activity.log file.
11710: 
11711: =back
11712: 
11713: =head2 User Roles
11714: 
11715: =over 4
11716: 
11717: =item *
11718: 
11719: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
11720:  F: full access
11721:  U,I,K: authentication modes (cxx only)
11722:  '': forbidden
11723:  1: user needs to choose course
11724:  2: browse allowed
11725:  A: passphrase authentication needed
11726: 
11727: =item *
11728: 
11729: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
11730: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
11731: and course level
11732: 
11733: =item *
11734: 
11735: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
11736: (rolesplain.tab); plain text explanation of a user role term.
11737: $type is Course (default) or Community.
11738: If $forcedefault evaluates to true, text returned will be default 
11739: text for $type. Otherwise, if this is a course, the text returned 
11740: will be a custom name for the role (if defined in the course's 
11741: environment).  If no custom name is defined the default is returned.
11742:    
11743: =item *
11744: 
11745: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
11746: All arguments are optional. Returns a hash of a roles, either for
11747: co-author/assistant author roles for a user's Construction Space
11748: (default), or if $context is 'userroles', roles for the user himself,
11749: In the hash, keys are set to colon-separated $uname,$udom,$role, and
11750: (optionally) if $withsec is true, a fourth colon-separated item - $section.
11751: For each key, value is set to colon-separated start and end times for
11752: the role.  If no username and domain are specified, will default to
11753: current user/domain. Types, roles, and roledoms are references to arrays
11754: of role statuses (active, future or previous), roles 
11755: (e.g., cc,in, st etc.) and domains of the roles which can be used
11756: to restrict the list of roles reported. If no array ref is 
11757: provided for types, will default to return only active roles.
11758: 
11759: =back
11760: 
11761: =head2 User Modification
11762: 
11763: =over 4
11764: 
11765: =item *
11766: 
11767: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
11768: user for the level given by URL.  Optional start and end dates (leave empty
11769: string or zero for "no date")
11770: 
11771: =item *
11772: 
11773: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
11774: change a users, password, possible return values are: ok,
11775: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
11776: refused
11777: 
11778: =item *
11779: 
11780: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
11781: 
11782: =item *
11783: 
11784: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
11785:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
11786: 
11787: will update user information (firstname,middlename,lastname,generation,
11788: permanentemail), and if forceid is true, student/employee ID also.
11789: A user's institutional affiliation(s) can also be updated.
11790: User information fields will not be overwritten with empty entries 
11791: unless the field is included in the $candelete array reference.
11792: This array is included when a single user is modified via "Manage Users",
11793: or when Autoupdate.pl is run by cron in a domain.
11794: 
11795: =item *
11796: 
11797: modifystudent
11798: 
11799: modify a student's enrollment and identification information.
11800: The course id is resolved based on the current users environment.  
11801: This means the envoking user must be a course coordinator or otherwise
11802: associated with a course.
11803: 
11804: This call is essentially a wrapper for lonnet::modifyuser and
11805: lonnet::modify_student_enrollment
11806: 
11807: Inputs: 
11808: 
11809: =over 4
11810: 
11811: =item B<$udom> Student's loncapa domain
11812: 
11813: =item B<$uname> Student's loncapa login name
11814: 
11815: =item B<$uid> Student/Employee ID
11816: 
11817: =item B<$umode> Student's authentication mode
11818: 
11819: =item B<$upass> Student's password
11820: 
11821: =item B<$first> Student's first name
11822: 
11823: =item B<$middle> Student's middle name
11824: 
11825: =item B<$last> Student's last name
11826: 
11827: =item B<$gene> Student's generation
11828: 
11829: =item B<$usec> Student's section in course
11830: 
11831: =item B<$end> Unix time of the roles expiration
11832: 
11833: =item B<$start> Unix time of the roles start date
11834: 
11835: =item B<$forceid> If defined, allow $uid to be changed
11836: 
11837: =item B<$desiredhome> server to use as home server for student
11838: 
11839: =item B<$email> Student's permanent e-mail address
11840: 
11841: =item B<$type> Type of enrollment (auto or manual)
11842: 
11843: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
11844: 
11845: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
11846: 
11847: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
11848: 
11849: =item B<$context> role change context (shown in User Management Logs display in a course)
11850: 
11851: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
11852: 
11853: =back
11854: 
11855: =item *
11856: 
11857: modify_student_enrollment
11858: 
11859: Change a students enrollment status in a class.  The environment variable
11860: 'role.request.course' must be defined for this function to proceed.
11861: 
11862: Inputs:
11863: 
11864: =over 4
11865: 
11866: =item $udom, students domain
11867: 
11868: =item $uname, students name
11869: 
11870: =item $uid, students user id
11871: 
11872: =item $first, students first name
11873: 
11874: =item $middle
11875: 
11876: =item $last
11877: 
11878: =item $gene
11879: 
11880: =item $usec
11881: 
11882: =item $end
11883: 
11884: =item $start
11885: 
11886: =item $type
11887: 
11888: =item $locktype
11889: 
11890: =item $cid
11891: 
11892: =item $selfenroll
11893: 
11894: =item $context
11895: 
11896: =back
11897: 
11898: 
11899: =item *
11900: 
11901: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
11902: custom role; give a custom role to a user for the level given by URL.  Specify
11903: name and domain of role author, and role name
11904: 
11905: =item *
11906: 
11907: revokerole($udom,$uname,$url,$role) : revoke a role for url
11908: 
11909: =item *
11910: 
11911: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
11912: 
11913: =back
11914: 
11915: =head2 Course Infomation
11916: 
11917: =over 4
11918: 
11919: =item *
11920: 
11921: coursedescription($courseid,$options) : returns a hash of information about the
11922: specified course id, including all environment settings for the
11923: course, the description of the course will be in the hash under the
11924: key 'description'
11925: 
11926: $options is an optional parameter that if supplied is a hash reference that controls
11927: what how this function works.  It has the following key/values:
11928: 
11929: =over 4
11930: 
11931: =item freshen_cache
11932: 
11933: If defined, and the environment cache for the course is valid, it is 
11934: returned in the returned hash.
11935: 
11936: =item one_time
11937: 
11938: If defined, the last cache time is set to _now_
11939: 
11940: =item user
11941: 
11942: If defined, the supplied username is used instead of the current user.
11943: 
11944: 
11945: =back
11946: 
11947: =item *
11948: 
11949: resdata($name,$domain,$type,@which) : request for current parameter
11950: setting for a specific $type, where $type is either 'course' or 'user',
11951: @what should be a list of parameters to ask about. This routine caches
11952: answers for 5 minutes.
11953: 
11954: =item *
11955: 
11956: get_courseresdata($courseid, $domain) : dump the entire course resource
11957: data base, returning a hash that is keyed by the resource name and has
11958: values that are the resource value.  I believe that the timestamps and
11959: versions are also returned.
11960: 
11961: 
11962: =back
11963: 
11964: =head2 Course Modification
11965: 
11966: =over 4
11967: 
11968: =item *
11969: 
11970: writecoursepref($courseid,%prefs) : write preferences (environment
11971: database) for a course
11972: 
11973: =item *
11974: 
11975: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
11976: 
11977: =item *
11978: 
11979: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
11980: 
11981: =item *
11982: 
11983: is_course($courseid), is_course($cdom, $cnum)
11984: 
11985: Accepts either a combined $courseid (in the form of domain_courseid) or the
11986: two component version $cdom, $cnum. It checks if the specified course exists.
11987: 
11988: Returns:
11989:     undef if the course doesn't exist, otherwise
11990:     in scalar context the combined courseid.
11991:     in list context the two components of the course identifier, domain and 
11992:     courseid.    
11993: 
11994: =back
11995: 
11996: =head2 Resource Subroutines
11997: 
11998: =over 4
11999: 
12000: =item *
12001: 
12002: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
12003: 
12004: =item *
12005: 
12006: repcopy($filename) : subscribes to the requested file, and attempts to
12007: replicate from the owning library server, Might return
12008: 'unavailable', 'not_found', 'forbidden', 'ok', or
12009: 'bad_request', also attempts to grab the metadata for the
12010: resource. Expects the local filesystem pathname
12011: (/home/httpd/html/res/....)
12012: 
12013: =back
12014: 
12015: =head2 Resource Information
12016: 
12017: =over 4
12018: 
12019: =item *
12020: 
12021: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
12022: a vairety of different possible values, $varname should be a request
12023: string, and the other parameters can be used to specify who and what
12024: one is asking about.
12025: 
12026: Possible values for $varname are environment.lastname (or other item
12027: from the envirnment hash), user.name (or someother aspect about the
12028: user), resource.0.maxtries (or some other part and parameter of a
12029: resource)
12030: 
12031: =item *
12032: 
12033: directcondval($number) : get current value of a condition; reads from a state
12034: string
12035: 
12036: =item *
12037: 
12038: condval($condidx) : value of condition index based on state
12039: 
12040: =item *
12041: 
12042: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
12043: resource's metadata, $what should be either a specific key, or either
12044: 'keys' (to get a list of possible keys) or 'packages' to get a list of
12045: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
12046: 
12047: this function automatically caches all requests
12048: 
12049: =item *
12050: 
12051: metadata_query($query,$custom,$customshow) : make a metadata query against the
12052: network of library servers; returns file handle of where SQL and regex results
12053: will be stored for query
12054: 
12055: =item *
12056: 
12057: symbread($filename) : return symbolic list entry (filename argument optional);
12058: returns the data handle
12059: 
12060: =item *
12061: 
12062: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
12063: a possible symb for the URL in $thisfn, and if is an encryypted
12064: resource that the user accessed using /enc/ returns a 1 on success, 0
12065: on failure, user must be in a course, as it assumes the existance of
12066: the course initial hash, and uses $env('request.course.id'}
12067: 
12068: 
12069: =item *
12070: 
12071: symbclean($symb) : removes versions numbers from a symb, returns the
12072: cleaned symb
12073: 
12074: =item *
12075: 
12076: is_on_map($uri) : checks if the $uri is somewhere on the current
12077: course map, user must be in a course for it to work.
12078: 
12079: =item *
12080: 
12081: numval($salt) : return random seed value (addend for rndseed)
12082: 
12083: =item *
12084: 
12085: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
12086: a random seed, all arguments are optional, if they aren't sent it uses the
12087: environment to derive them. Note: if symb isn't sent and it can't get one
12088: from &symbread it will use the current time as its return value
12089: 
12090: =item *
12091: 
12092: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
12093: unfakeable, receipt
12094: 
12095: =item *
12096: 
12097: receipt() : API to ireceipt working off of env values; given out to users
12098: 
12099: =item *
12100: 
12101: countacc($url) : count the number of accesses to a given URL
12102: 
12103: =item *
12104: 
12105: 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
12106: 
12107: =item *
12108: 
12109: 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)
12110: 
12111: =item *
12112: 
12113: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
12114: 
12115: =item *
12116: 
12117: devalidate($symb) : devalidate temporary spreadsheet calculations,
12118: forcing spreadsheet to reevaluate the resource scores next time.
12119: 
12120: =back
12121: 
12122: =head2 Storing/Retreiving Data
12123: 
12124: =over 4
12125: 
12126: =item *
12127: 
12128: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
12129: for this url; hashref needs to be given and should be a \%hashname; the
12130: remaining args aren't required and if they aren't passed or are '' they will
12131: be derived from the env
12132: 
12133: =item *
12134: 
12135: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
12136: uses critical subroutine
12137: 
12138: =item *
12139: 
12140: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
12141: all args are optional
12142: 
12143: =item *
12144: 
12145: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
12146: dumps the complete (or key matching regexp) namespace into a hash
12147: ($udom, $uname, $regexp, $range are optional) for a namespace that is
12148: normally &store()ed into
12149: 
12150: $range should be either an integer '100' (give me the first 100
12151:                                            matching records)
12152:               or be  two integers sperated by a - with no spaces
12153:                  '30-50' (give me the 30th through the 50th matching
12154:                           records)
12155: 
12156: 
12157: =item *
12158: 
12159: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
12160: replaces a &store() version of data with a replacement set of data
12161: for a particular resource in a namespace passed in the $storehash hash 
12162: reference
12163: 
12164: =item *
12165: 
12166: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
12167: works very similar to store/cstore, but all data is stored in a
12168: temporary location and can be reset using tmpreset, $storehash should
12169: be a hash reference, returns nothing on success
12170: 
12171: =item *
12172: 
12173: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
12174: similar to restore, but all data is stored in a temporary location and
12175: can be reset using tmpreset. Returns a hash of values on success,
12176: error string otherwise.
12177: 
12178: =item *
12179: 
12180: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
12181: deltes all keys for $symb form the temporary storage hash.
12182: 
12183: =item *
12184: 
12185: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
12186: reference filled in from namesp ($udom and $uname are optional)
12187: 
12188: =item *
12189: 
12190: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
12191: namesp ($udom and $uname are optional)
12192: 
12193: =item *
12194: 
12195: dump($namespace,$udom,$uname,$regexp,$range) : 
12196: dumps the complete (or key matching regexp) namespace into a hash
12197: ($udom, $uname, $regexp, $range are optional)
12198: 
12199: $range should be either an integer '100' (give me the first 100
12200:                                            matching records)
12201:               or be  two integers sperated by a - with no spaces
12202:                  '30-50' (give me the 30th through the 50th matching
12203:                           records)
12204: =item *
12205: 
12206: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
12207: $store can be a scalar, an array reference, or if the amount to be 
12208: incremented is > 1, a hash reference.
12209: 
12210: ($udom and $uname are optional)
12211: 
12212: =item *
12213: 
12214: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
12215: ($udom and $uname are optional)
12216: 
12217: =item *
12218: 
12219: cput($namespace,$storehash,$udom,$uname) : critical put
12220: ($udom and $uname are optional)
12221: 
12222: =item *
12223: 
12224: newput($namespace,$storehash,$udom,$uname) :
12225: 
12226: Attempts to store the items in the $storehash, but only if they don't
12227: currently exist, if this succeeds you can be certain that you have 
12228: successfully created a new key value pair in the $namespace db.
12229: 
12230: 
12231: Args:
12232:  $namespace: name of database to store values to
12233:  $storehash: hashref to store to the db
12234:  $udom: (optional) domain of user containing the db
12235:  $uname: (optional) name of user caontaining the db
12236: 
12237: Returns:
12238:  'ok' -> succeeded in storing all keys of $storehash
12239:  'key_exists: <key>' -> failed to anything out of $storehash, as at
12240:                         least <key> already existed in the db (other
12241:                         requested keys may also already exist)
12242:  'error: <msg>' -> unable to tie the DB or other error occurred
12243:  'con_lost' -> unable to contact request server
12244:  'refused' -> action was not allowed by remote machine
12245: 
12246: 
12247: =item *
12248: 
12249: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
12250: reference filled in from namesp (encrypts the return communication)
12251: ($udom and $uname are optional)
12252: 
12253: =item *
12254: 
12255: log($udom,$name,$home,$message) : write to permanent log for user; use
12256: critical subroutine
12257: 
12258: =item *
12259: 
12260: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
12261: array reference filled in from namespace found in domain level on either
12262: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
12263: 
12264: =item *
12265: 
12266: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
12267: domain level either on specified domain server ($uhome) or primary domain 
12268: server ($udom and $uhome are optional)
12269: 
12270: =item * 
12271: 
12272: get_domain_defaults($target_domain) : returns hash with defaults for
12273: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
12274: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
12275: or localauth), initial password or a kerberos realm, language (e.g., en-us).
12276: Values are retrieved from cache (if current), or from domain's configuration.db
12277: (if available), or lastly from values in lonTabs/dns_domain,tab, 
12278: or lonTabs/domain.tab. 
12279: 
12280: %domdefaults = &get_auth_defaults($target_domain);
12281: 
12282: =back
12283: 
12284: =head2 Network Status Functions
12285: 
12286: =over 4
12287: 
12288: =item *
12289: 
12290: dirlist() : return directory list based on URI (first arg).
12291: 
12292: Inputs: 1 required, 5 optional.
12293: 
12294: =over
12295: 
12296: =item 
12297: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
12298: 
12299: =item
12300: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
12301: 
12302: =item
12303: $username -  username of user/course to be listed. Extracted from $uri if absent. 
12304: 
12305: =item
12306: $getpropath - boolean: 1 if prepend path using &propath(). 
12307: 
12308: =item
12309: $getuserdir - boolean: 1 if prepend path for "userfiles".
12310: 
12311: =item 
12312: $alternateRoot - path to prepend in place of path from $uri.
12313: 
12314: =back
12315: 
12316: Returns: Array of up to two items.
12317: 
12318: =over
12319: 
12320: a reference to an array of files/subdirectories
12321: 
12322: =over
12323: 
12324: Each element in the array of files/subdirectories is a & separated list of
12325: item name and the result of running stat on the item.  If dirlist was requested
12326: for a file instead of a directory, the item name will be ''. For a directory 
12327: listing, if the item is a metadata file, the element will end &N&M 
12328: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
12329: default copyright set (1).  
12330: 
12331: =back
12332: 
12333: a scalar containing error condition (if encountered).
12334: 
12335: =over
12336: 
12337: =item 
12338: no_host (no homeserver identified for $username:$domain).
12339: 
12340: =item 
12341: no_such_host (server contacted for listing not identified as valid host).
12342: 
12343: =item 
12344: con_lost (connection to remote server failed).
12345: 
12346: =item 
12347: refused (invalid $username:$domain received on lond side).
12348: 
12349: =item 
12350: no_such_dir (directory at specified path on lond side does not exist). 
12351: 
12352: =item 
12353: empty (directory at specified path on lond side is empty).
12354: 
12355: =over
12356: 
12357: This is currently not encountered because the &ls3, &ls2, 
12358: &ls (_handler) routines on the lond side do not filter out
12359: . and .. from a directory listing. 
12360: 
12361: =back
12362: 
12363: =back
12364: 
12365: =back
12366: 
12367: =item *
12368: 
12369: spareserver() : find server with least workload from spare.tab
12370: 
12371: 
12372: =item *
12373: 
12374: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
12375: if there is no corresponding loncapa host.
12376: 
12377: =back
12378: 
12379: 
12380: =head2 Apache Request
12381: 
12382: =over 4
12383: 
12384: =item *
12385: 
12386: ssi($url,%hash) : server side include, does a complete request cycle on url to
12387: localhost, posts hash
12388: 
12389: =back
12390: 
12391: =head2 Data to String to Data
12392: 
12393: =over 4
12394: 
12395: =item *
12396: 
12397: hash2str(%hash) : convert a hash into a string complete with escaping and '='
12398: and '&' separators, supports elements that are arrayrefs and hashrefs
12399: 
12400: =item *
12401: 
12402: hashref2str($hashref) : convert a hashref into a string complete with
12403: escaping and '=' and '&' separators, supports elements that are
12404: arrayrefs and hashrefs
12405: 
12406: =item *
12407: 
12408: arrayref2str($arrayref) : convert an arrayref into a string complete
12409: with escaping and '&' separators, supports elements that are arrayrefs
12410: and hashrefs
12411: 
12412: =item *
12413: 
12414: str2hash($string) : convert string to hash using unescaping and
12415: splitting on '=' and '&', supports elements that are arrayrefs and
12416: hashrefs
12417: 
12418: =item *
12419: 
12420: str2array($string) : convert string to hash using unescaping and
12421: splitting on '&', supports elements that are arrayrefs and hashrefs
12422: 
12423: =back
12424: 
12425: =head2 Logging Routines
12426: 
12427: 
12428: These routines allow one to make log messages in the lonnet.log and
12429: lonnet.perm logfiles.
12430: 
12431: =over 4
12432: 
12433: =item *
12434: 
12435: logtouch() : make sure the logfile, lonnet.log, exists
12436: 
12437: =item *
12438: 
12439: logthis() : append message to the normal lonnet.log file, it gets
12440: preiodically rolled over and deleted.
12441: 
12442: =item *
12443: 
12444: logperm() : append a permanent message to lonnet.perm.log, this log
12445: file never gets deleted by any automated portion of the system, only
12446: messages of critical importance should go in here.
12447: 
12448: 
12449: =back
12450: 
12451: =head2 General File Helper Routines
12452: 
12453: =over 4
12454: 
12455: =item *
12456: 
12457: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
12458: (a) files in /uploaded
12459:   (i) If a local copy of the file exists - 
12460:       compares modification date of local copy with last-modified date for 
12461:       definitive version stored on home server for course. If local copy is 
12462:       stale, requests a new version from the home server and stores it. 
12463:       If the original has been removed from the home server, then local copy 
12464:       is unlinked.
12465:   (ii) If local copy does not exist -
12466:       requests the file from the home server and stores it. 
12467:   
12468:   If $caller is 'uploadrep':  
12469:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
12470:     for request for files originally uploaded via DOCS. 
12471:      - returns 'ok' if fresh local copy now available, -1 otherwise.
12472:   
12473:   Otherwise:
12474:      This indicates a call from the content generation phase of the request.
12475:      -  returns the entire contents of the file or -1.
12476:      
12477: (b) files in /res
12478:    - returns the entire contents of a file or -1; 
12479:    it properly subscribes to and replicates the file if neccessary.
12480: 
12481: 
12482: =item *
12483: 
12484: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
12485:                   reference
12486: 
12487: returns either a stat() list of data about the file or an empty list
12488: if the file doesn't exist or couldn't find out about it (connection
12489: problems or user unknown)
12490: 
12491: =item *
12492: 
12493: filelocation($dir,$file) : returns file system location of a file
12494: based on URI; meant to be "fairly clean" absolute reference, $dir is a
12495: directory that relative $file lookups are to looked in ($dir of /a/dir
12496: and a file of ../bob will become /a/bob)
12497: 
12498: =item *
12499: 
12500: hreflocation($dir,$file) : returns file system location or a URL; same as
12501: filelocation except for hrefs
12502: 
12503: =item *
12504: 
12505: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
12506: 
12507: =back
12508: 
12509: =head2 Usererfile file routines (/uploaded*)
12510: 
12511: =over 4
12512: 
12513: =item *
12514: 
12515: userfileupload(): main rotine for putting a file in a user or course's
12516:                   filespace, arguments are,
12517: 
12518:  formname - required - this is the name of the element in $env where the
12519:            filename, and the contents of the file to create/modifed exist
12520:            the filename is in $env{'form.'.$formname.'.filename'} and the
12521:            contents of the file is located in $env{'form.'.$formname}
12522:  context - if coursedoc, store the file in the course of the active role
12523:              of the current user; 
12524:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
12525:            if 'canceloverwrite': delete file in tmp/overwrites directory
12526:  subdir - required - subdirectory to put the file in under ../userfiles/
12527:          if undefined, it will be placed in "unknown"
12528: 
12529:  (This routine calls clean_filename() to remove any dangerous
12530:  characters from the filename, and then calls finuserfileupload() to
12531:  complete the transaction)
12532: 
12533:  returns either the url of the uploaded file (/uploaded/....) if successful
12534:  and /adm/notfound.html if unsuccessful
12535: 
12536: =item *
12537: 
12538: clean_filename(): routine for cleaing a filename up for storage in
12539:                  userfile space, argument is:
12540: 
12541:  filename - proposed filename
12542: 
12543: returns: the new clean filename
12544: 
12545: =item *
12546: 
12547: finishuserfileupload(): routine that creates and sends the file to
12548: userspace, probably shouldn't be called directly
12549: 
12550:   docuname: username or courseid of destination for the file
12551:   docudom: domain of user/course of destination for the file
12552:   formname: same as for userfileupload()
12553:   fname: filename (including subdirectories) for the file
12554:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
12555:   allfiles: reference to hash used to store objects found by parser
12556:   codebase: reference to hash used for codebases of java objects found by parser
12557:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
12558:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
12559:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
12560:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
12561:   context: if 'overwrite', will move the uploaded file from its temporary location to
12562:             userfiles to facilitate overwriting a previously uploaded file with same name.
12563:   mimetype: reference to scalar to accommodate mime type determined
12564:             from File::MMagic if $parser = parse.
12565: 
12566:  returns either the url of the uploaded file (/uploaded/....) if successful
12567:  and /adm/notfound.html if unsuccessful (or an error message if context 
12568:  was 'overwrite').
12569:  
12570: 
12571: =item *
12572: 
12573: renameuserfile(): renames an existing userfile to a new name
12574: 
12575:   Args:
12576:    docuname: username or courseid of destination for the file
12577:    docudom: domain of user/course of destination for the file
12578:    old: current file name (including any subdirs under userfiles)
12579:    new: desired file name (including any subdirs under userfiles)
12580: 
12581: =item *
12582: 
12583: mkdiruserfile(): creates a directory is a userfiles dir
12584: 
12585:   Args:
12586:    docuname: username or courseid of destination for the file
12587:    docudom: domain of user/course of destination for the file
12588:    dir: dir to create (including any subdirs under userfiles)
12589: 
12590: =item *
12591: 
12592: removeuserfile(): removes a file that exists in userfiles
12593: 
12594:   Args:
12595:    docuname: username or courseid of destination for the file
12596:    docudom: domain of user/course of destination for the file
12597:    fname: filname to delete (including any subdirs under userfiles)
12598: 
12599: =item *
12600: 
12601: removeuploadedurl(): convience function for removeuserfile()
12602: 
12603:   Args:
12604:    url:  a full /uploaded/... url to delete
12605: 
12606: =item * 
12607: 
12608: get_portfile_permissions():
12609:   Args:
12610:     domain: domain of user or course contain the portfolio files
12611:     user: name of user or num of course contain the portfolio files
12612:   Returns:
12613:     hashref of a dump of the proper file_permissions.db
12614:    
12615: 
12616: =item * 
12617: 
12618: get_access_controls():
12619: 
12620: Args:
12621:   current_permissions: the hash ref returned from get_portfile_permissions()
12622:   group: (optional) the group you want the files associated with
12623:   file: (optional) the file you want access info on
12624: 
12625: Returns:
12626:     a hash (keys are file names) of hashes containing
12627:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
12628:         values are XML containing access control settings (see below) 
12629: 
12630: Internal notes:
12631: 
12632:  access controls are stored in file_permissions.db as key=value pairs.
12633:     key -> path to file/file_name\0uniqueID:scope_end_start
12634:         where scope -> public,guest,course,group,domains or users.
12635:               end -> UNIX time for end of access (0 -> no end date)
12636:               start -> UNIX time for start of access
12637: 
12638:     value -> XML description of access control
12639:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
12640:             <start></start>
12641:             <end></end>
12642: 
12643:             <password></password>  for scope type = guest
12644: 
12645:             <domain></domain>     for scope type = course or group
12646:             <number></number>
12647:             <roles id="">
12648:              <role></role>
12649:              <access></access>
12650:              <section></section>
12651:              <group></group>
12652:             </roles>
12653: 
12654:             <dom></dom>         for scope type = domains
12655: 
12656:             <users>             for scope type = users
12657:              <user>
12658:               <uname></uname>
12659:               <udom></udom>
12660:              </user>
12661:             </users>
12662:            </scope> 
12663:               
12664:  Access data is also aggregated for each file in an additional key=value pair:
12665:  key -> path to file/file_name\0accesscontrol 
12666:  value -> reference to hash
12667:           hash contains key = value pairs
12668:           where key = uniqueID:scope_end_start
12669:                 value = UNIX time record was last updated
12670: 
12671:           Used to improve speed of look-ups of access controls for each file.  
12672:  
12673:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
12674: 
12675: modify_access_controls():
12676: 
12677: Modifies access controls for a portfolio file
12678: Args
12679: 1. file name
12680: 2. reference to hash of required changes,
12681: 3. domain
12682: 4. username
12683:   where domain,username are the domain of the portfolio owner 
12684:   (either a user or a course) 
12685: 
12686: Returns:
12687: 1. result of additions or updates ('ok' or 'error', with error message). 
12688: 2. result of deletions ('ok' or 'error', with error message).
12689: 3. reference to hash of any new or updated access controls.
12690: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
12691:    key = integer (inbound ID)
12692:    value = uniqueID  
12693: 
12694: =back
12695: 
12696: =head2 HTTP Helper Routines
12697: 
12698: =over 4
12699: 
12700: =item *
12701: 
12702: escape() : unpack non-word characters into CGI-compatible hex codes
12703: 
12704: =item *
12705: 
12706: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
12707: 
12708: =back
12709: 
12710: =head1 PRIVATE SUBROUTINES
12711: 
12712: =head2 Underlying communication routines (Shouldn't call)
12713: 
12714: =over 4
12715: 
12716: =item *
12717: 
12718: subreply() : tries to pass a message to lonc, returns con_lost if incapable
12719: 
12720: =item *
12721: 
12722: reply() : uses subreply to send a message to remote machine, logs all failures
12723: 
12724: =item *
12725: 
12726: critical() : passes a critical message to another server; if cannot
12727: get through then place message in connection buffer directory and
12728: returns con_delayed, if incapable of saving message, returns
12729: con_failed
12730: 
12731: =item *
12732: 
12733: reconlonc() : tries to reconnect lonc client processes.
12734: 
12735: =back
12736: 
12737: =head2 Resource Access Logging
12738: 
12739: =over 4
12740: 
12741: =item *
12742: 
12743: flushcourselogs() : flush (save) buffer logs and access logs
12744: 
12745: =item *
12746: 
12747: courselog($what) : save message for course in hash
12748: 
12749: =item *
12750: 
12751: courseacclog($what) : save message for course using &courselog().  Perform
12752: special processing for specific resource types (problems, exams, quizzes, etc).
12753: 
12754: =item *
12755: 
12756: goodbye() : flush course logs and log shutting down; it is called in srm.conf
12757: as a PerlChildExitHandler
12758: 
12759: =back
12760: 
12761: =head2 Other
12762: 
12763: =over 4
12764: 
12765: =item *
12766: 
12767: symblist($mapname,%newhash) : update symbolic storage links
12768: 
12769: =back
12770: 
12771: =cut
12772: 

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