File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1156: download - view: text, annotated - select for diffs
Tue Feb 28 14:27:55 2012 UTC (12 years, 4 months ago) by www
Branches: MAIN
CVS tags: HEAD
Internal Server Error -
Remove spurious $courseid introduced alongside formatting changes in 1.1154

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1156 2012/02/28 14:27:55 www 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: 
  100: use File::Copy;
  101: 
  102: my $readit;
  103: my $max_connection_retries = 10;     # Or some such value.
  104: 
  105: require Exporter;
  106: 
  107: our @ISA = qw (Exporter);
  108: our @EXPORT = qw(%env);
  109: 
  110: 
  111: # --------------------------------------------------------------------- Logging
  112: {
  113:     my $logid;
  114:     sub instructor_log {
  115: 	my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
  116:         if (($cnum eq '') || ($cdom eq '')) {
  117:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  118:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  119:         }
  120: 	$logid++;
  121:         my $now = time();
  122: 	my $id=$now.'00000'.$$.'00000'.$logid;
  123: 	return &Apache::lonnet::put('nohist_'.$hash_name,
  124: 				    { $id => {
  125: 					'exe_uname' => $env{'user.name'},
  126: 					'exe_udom'  => $env{'user.domain'},
  127: 					'exe_time'  => $now,
  128: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
  129: 					'delflag'   => $delflag,
  130: 					'logentry'  => $storehash,
  131: 					'uname'     => $uname,
  132: 					'udom'      => $udom,
  133: 				    }
  134: 				  },$cdom,$cnum);
  135:     }
  136: }
  137: 
  138: sub logtouch {
  139:     my $execdir=$perlvar{'lonDaemons'};
  140:     unless (-e "$execdir/logs/lonnet.log") {	
  141: 	open(my $fh,">>$execdir/logs/lonnet.log");
  142: 	close $fh;
  143:     }
  144:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  145:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  146: }
  147: 
  148: sub logthis {
  149:     my $message=shift;
  150:     my $execdir=$perlvar{'lonDaemons'};
  151:     my $now=time;
  152:     my $local=localtime($now);
  153:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
  154: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
  155: 	print $fh $logstring;
  156: 	close($fh);
  157:     }
  158:     return 1;
  159: }
  160: 
  161: sub logperm {
  162:     my $message=shift;
  163:     my $execdir=$perlvar{'lonDaemons'};
  164:     my $now=time;
  165:     my $local=localtime($now);
  166:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
  167: 	print $fh "$now:$message:$local\n";
  168: 	close($fh);
  169:     }
  170:     return 1;
  171: }
  172: 
  173: sub create_connection {
  174:     my ($hostname,$lonid) = @_;
  175:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  176: 				     Type    => SOCK_STREAM,
  177: 				     Timeout => 10);
  178:     return 0 if (!$client);
  179:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
  180:     my $result = <$client>;
  181:     chomp($result);
  182:     return 1 if ($result eq 'done');
  183:     return 0;
  184: }
  185: 
  186: sub get_server_timezone {
  187:     my ($cnum,$cdom) = @_;
  188:     my $home=&homeserver($cnum,$cdom);
  189:     if ($home ne 'no_host') {
  190:         my $cachetime = 24*3600;
  191:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
  192:         if (defined($cached)) {
  193:             return $timezone;
  194:         } else {
  195:             my $timezone = &reply('servertimezone',$home);
  196:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
  197:         }
  198:     }
  199: }
  200: 
  201: sub get_server_distarch {
  202:     my ($lonhost,$ignore_cache) = @_;
  203:     if (defined($lonhost)) {
  204:         if (!defined(&hostname($lonhost))) {
  205:             return;
  206:         }
  207:         my $cachetime = 12*3600;
  208:         if (!$ignore_cache) {
  209:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
  210:             if (defined($cached)) {
  211:                 return $distarch;
  212:             }
  213:         }
  214:         my $rep = &reply('serverdistarch',$lonhost);
  215:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
  216:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
  217:                 $rep eq '') {
  218:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
  219:         }
  220:     }
  221:     return;
  222: }
  223: 
  224: sub get_server_loncaparev {
  225:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
  226:     if (defined($lonhost)) {
  227:         if (!defined(&hostname($lonhost))) {
  228:             undef($lonhost);
  229:         }
  230:     }
  231:     if (!defined($lonhost)) {
  232:         if (defined(&domain($dom,'primary'))) {
  233:             $lonhost=&domain($dom,'primary');
  234:             if ($lonhost eq 'no_host') {
  235:                 undef($lonhost);
  236:             }
  237:         }
  238:     }
  239:     if (defined($lonhost)) {
  240:         my $cachetime = 12*3600;
  241:         if (!$ignore_cache) {
  242:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
  243:             if (defined($cached)) {
  244:                 return $loncaparev;
  245:             }
  246:         }
  247:         my ($answer,$loncaparev);
  248:         my @ids=&current_machine_ids();
  249:         if (grep(/^\Q$lonhost\E$/,@ids)) {
  250:             $answer = $perlvar{'lonVersion'};
  251:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  252:                 $loncaparev = $1;
  253:             }
  254:         } else {
  255:             $answer = &reply('serverloncaparev',$lonhost);
  256:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
  257:                 if ($caller eq 'loncron') {
  258:                     my $ua=new LWP::UserAgent;
  259:                     $ua->timeout(4);
  260:                     my $protocol = $protocol{$lonhost};
  261:                     $protocol = 'http' if ($protocol ne 'https');
  262:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
  263:                     my $request=new HTTP::Request('GET',$url);
  264:                     my $response=$ua->request($request);
  265:                     unless ($response->is_error()) {
  266:                         my $content = $response->content;
  267:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
  268:                             $loncaparev = $1;
  269:                         }
  270:                     }
  271:                 } else {
  272:                     $loncaparev = $loncaparevs{$lonhost};
  273:                 }
  274:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  275:                 $loncaparev = $1;
  276:             }
  277:         }
  278:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
  279:     }
  280: }
  281: 
  282: sub get_server_homeID {
  283:     my ($hostname,$ignore_cache,$caller) = @_;
  284:     unless ($ignore_cache) {
  285:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
  286:         if (defined($cached)) {
  287:             return $serverhomeID;
  288:         }
  289:     }
  290:     my $cachetime = 12*3600;
  291:     my $serverhomeID;
  292:     if ($caller eq 'loncron') { 
  293:         my @machine_ids = &machine_ids($hostname);
  294:         foreach my $id (@machine_ids) {
  295:             my $response = &reply('serverhomeID',$id);
  296:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
  297:                 $serverhomeID = $response;
  298:                 last;
  299:             }
  300:         }
  301:         if ($serverhomeID eq '') {
  302:             $serverhomeID = $machine_ids[-1];
  303:         }
  304:     } else {
  305:         $serverhomeID = $serverhomeIDs{$hostname};
  306:     }
  307:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
  308: }
  309: 
  310: sub get_remote_globals {
  311:     my ($lonhost,$whathash,$ignore_cache) = @_;
  312:     my ($result,%returnhash,%whatneeded);
  313:     if (ref($whathash) eq 'HASH') {
  314:         foreach my $what (sort(keys(%{$whathash}))) {
  315:             my $hashid = $lonhost.'-'.$what;
  316:             my ($response,$cached);
  317:             unless ($ignore_cache) {
  318:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
  319:             }
  320:             if (defined($cached)) {
  321:                 $returnhash{$what} = $response;
  322:             } else {
  323:                 $whatneeded{$what} = 1;
  324:             }
  325:         }
  326:         if (keys(%whatneeded) == 0) {
  327:             $result = 'ok';
  328:         } else {
  329:             my $requested = &freeze_escape(\%whatneeded);
  330:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
  331:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  332:                 ($rep eq 'unknown_cmd')) {
  333:                 $result = $rep;
  334:             } else {
  335:                 $result = 'ok';
  336:                 my @pairs=split(/\&/,$rep);
  337:                 foreach my $item (@pairs) {
  338:                     my ($key,$value)=split(/=/,$item,2);
  339:                     my $what = &unescape($key);
  340:                     my $hashid = $lonhost.'-'.$what;
  341:                     $returnhash{$what}=&thaw_unescape($value);
  342:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
  343:                 }
  344:             }
  345:         }
  346:     }
  347:     return ($result,\%returnhash);
  348: }
  349: 
  350: sub remote_devalidate_cache {
  351:     my ($lonhost,$name,$id) = @_;
  352:     my $response = &reply('devalidatecache:'.&escape($name).':'.&escape($id),$lonhost);
  353:     return $response;
  354: }
  355: 
  356: # -------------------------------------------------- Non-critical communication
  357: sub subreply {
  358:     my ($cmd,$server)=@_;
  359:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  360:     #
  361:     #  With loncnew process trimming, there's a timing hole between lonc server
  362:     #  process exit and the master server picking up the listen on the AF_UNIX
  363:     #  socket.  In that time interval, a lock file will exist:
  364: 
  365:     my $lockfile=$peerfile.".lock";
  366:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  367: 	sleep(1);
  368:     }
  369:     # At this point, either a loncnew parent is listening or an old lonc
  370:     # or loncnew child is listening so we can connect or everything's dead.
  371:     #
  372:     #   We'll give the connection a few tries before abandoning it.  If
  373:     #   connection is not possible, we'll con_lost back to the client.
  374:     #   
  375:     my $client;
  376:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  377: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  378: 				      Type    => SOCK_STREAM,
  379: 				      Timeout => 10);
  380: 	if ($client) {
  381: 	    last;		# Connected!
  382: 	} else {
  383: 	    &create_connection(&hostname($server),$server);
  384: 	}
  385:         sleep(1);		# Try again later if failed connection.
  386:     }
  387:     my $answer;
  388:     if ($client) {
  389: 	print $client "sethost:$server:$cmd\n";
  390: 	$answer=<$client>;
  391: 	if (!$answer) { $answer="con_lost"; }
  392: 	chomp($answer);
  393:     } else {
  394: 	$answer = 'con_lost';	# Failed connection.
  395:     }
  396:     return $answer;
  397: }
  398: 
  399: sub reply {
  400:     my ($cmd,$server)=@_;
  401:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  402:     my $answer=subreply($cmd,$server);
  403:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  404:        &logthis("<font color=\"blue\">WARNING:".
  405:                 " $cmd to $server returned $answer</font>");
  406:     }
  407:     return $answer;
  408: }
  409: 
  410: # ----------------------------------------------------------- Send USR1 to lonc
  411: 
  412: sub reconlonc {
  413:     my ($lonid) = @_;
  414:     my $hostname = &hostname($lonid);
  415:     if ($lonid) {
  416: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  417: 	if ($hostname && -e $peerfile) {
  418: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  419: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  420: 					     Type    => SOCK_STREAM,
  421: 					     Timeout => 10);
  422: 	    if ($client) {
  423: 		print $client ("reset_retries\n");
  424: 		my $answer=<$client>;
  425: 		#reset just this one.
  426: 	    }
  427: 	}
  428: 	return;
  429:     }
  430: 
  431:     &logthis("Trying to reconnect lonc");
  432:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  433:     if (open(my $fh,"<$loncfile")) {
  434: 	my $loncpid=<$fh>;
  435:         chomp($loncpid);
  436:         if (kill 0 => $loncpid) {
  437: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  438:             kill USR1 => $loncpid;
  439:             sleep 1;
  440:          } else {
  441: 	    &logthis(
  442:                "<font color=\"blue\">WARNING:".
  443:                " lonc at pid $loncpid not responding, giving up</font>");
  444:         }
  445:     } else {
  446: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  447:     }
  448: }
  449: 
  450: # ------------------------------------------------------ Critical communication
  451: 
  452: sub critical {
  453:     my ($cmd,$server)=@_;
  454:     unless (&hostname($server)) {
  455:         &logthis("<font color=\"blue\">WARNING:".
  456:                " Critical message to unknown server ($server)</font>");
  457:         return 'no_such_host';
  458:     }
  459:     my $answer=reply($cmd,$server);
  460:     if ($answer eq 'con_lost') {
  461: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
  462: 	my $answer=reply($cmd,$server);
  463:         if ($answer eq 'con_lost') {
  464:             my $now=time;
  465:             my $middlename=$cmd;
  466:             $middlename=substr($middlename,0,16);
  467:             $middlename=~s/\W//g;
  468:             my $dfilename=
  469:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  470:             $dumpcount++;
  471:             {
  472: 		my $dfh;
  473: 		if (open($dfh,">$dfilename")) {
  474: 		    print $dfh "$cmd\n"; 
  475: 		    close($dfh);
  476: 		}
  477:             }
  478:             sleep 2;
  479:             my $wcmd='';
  480:             {
  481: 		my $dfh;
  482: 		if (open($dfh,"<$dfilename")) {
  483: 		    $wcmd=<$dfh>; 
  484: 		    close($dfh);
  485: 		}
  486:             }
  487:             chomp($wcmd);
  488:             if ($wcmd eq $cmd) {
  489: 		&logthis("<font color=\"blue\">WARNING: ".
  490:                          "Connection buffer $dfilename: $cmd</font>");
  491:                 &logperm("D:$server:$cmd");
  492: 	        return 'con_delayed';
  493:             } else {
  494:                 &logthis("<font color=\"red\">CRITICAL:"
  495:                         ." Critical connection failed: $server $cmd</font>");
  496:                 &logperm("F:$server:$cmd");
  497:                 return 'con_failed';
  498:             }
  499:         }
  500:     }
  501:     return $answer;
  502: }
  503: 
  504: # ------------------------------------------- check if return value is an error
  505: 
  506: sub error {
  507:     my ($result) = @_;
  508:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  509: 	if ($2 == 2) { return undef; }
  510: 	return $1;
  511:     }
  512:     return undef;
  513: }
  514: 
  515: sub convert_and_load_session_env {
  516:     my ($lonidsdir,$handle)=@_;
  517:     my @profile;
  518:     {
  519: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  520: 	if (!$opened) {
  521: 	    return 0;
  522: 	}
  523: 	flock($idf,LOCK_SH);
  524: 	@profile=<$idf>;
  525: 	close($idf);
  526:     }
  527:     my %temp_env;
  528:     foreach my $line (@profile) {
  529: 	if ($line !~ m/=/) {
  530: 	    return 0;
  531: 	}
  532: 	chomp($line);
  533: 	my ($envname,$envvalue)=split(/=/,$line,2);
  534: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  535:     }
  536:     unlink("$lonidsdir/$handle.id");
  537:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  538: 	    0640)) {
  539: 	%disk_env = %temp_env;
  540: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  541: 	untie(%disk_env);
  542:     }
  543:     return 1;
  544: }
  545: 
  546: # ------------------------------------------- Transfer profile into environment
  547: my $env_loaded;
  548: sub transfer_profile_to_env {
  549:     my ($lonidsdir,$handle,$force_transfer) = @_;
  550:     if (!$force_transfer && $env_loaded) { return; } 
  551: 
  552:     if (!defined($lonidsdir)) {
  553: 	$lonidsdir = $perlvar{'lonIDsDir'};
  554:     }
  555:     if (!defined($handle)) {
  556:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  557:     }
  558: 
  559:     my $convert;
  560:     {
  561:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  562: 	if (!$opened) {
  563: 	    return;
  564: 	}
  565: 	flock($idf,LOCK_SH);
  566: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  567: 		&GDBM_READER(),0640)) {
  568: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  569: 	    untie(%disk_env);
  570: 	} else {
  571: 	    $convert = 1;
  572: 	}
  573:     }
  574:     if ($convert) {
  575: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  576: 	    &logthis("Failed to load session, or convert session.");
  577: 	}
  578:     }
  579: 
  580:     my %remove;
  581:     while ( my $envname = each(%env) ) {
  582:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  583:             if ($time < time-300) {
  584:                 $remove{$key}++;
  585:             }
  586:         }
  587:     }
  588: 
  589:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  590:     $env_loaded=1;
  591:     foreach my $expired_key (keys(%remove)) {
  592:         &delenv($expired_key);
  593:     }
  594: }
  595: 
  596: # ---------------------------------------------------- Check for valid session 
  597: sub check_for_valid_session {
  598:     my ($r,$name) = @_;
  599:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  600:     if ($name eq '') {
  601:         $name = 'lonID';
  602:     }
  603:     my $lonid=$cookies{$name};
  604:     return undef if (!$lonid);
  605: 
  606:     my $handle=&LONCAPA::clean_handle($lonid->value);
  607:     my $lonidsdir;
  608:     if ($name eq 'lonDAV') {
  609:         $lonidsdir=$r->dir_config('lonDAVsessDir');
  610:     } else {
  611:         $lonidsdir=$r->dir_config('lonIDsDir');
  612:     }
  613:     return undef if (!-e "$lonidsdir/$handle.id");
  614: 
  615:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  616:     return undef if (!$opened);
  617: 
  618:     flock($idf,LOCK_SH);
  619:     my %disk_env;
  620:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  621: 	    &GDBM_READER(),0640)) {
  622: 	return undef;	
  623:     }
  624: 
  625:     if (!defined($disk_env{'user.name'})
  626: 	|| !defined($disk_env{'user.domain'})) {
  627: 	return undef;
  628:     }
  629:     return $handle;
  630: }
  631: 
  632: sub timed_flock {
  633:     my ($file,$lock_type) = @_;
  634:     my $failed=0;
  635:     eval {
  636: 	local $SIG{__DIE__}='DEFAULT';
  637: 	local $SIG{ALRM}=sub {
  638: 	    $failed=1;
  639: 	    die("failed lock");
  640: 	};
  641: 	alarm(13);
  642: 	flock($file,$lock_type);
  643: 	alarm(0);
  644:     };
  645:     if ($failed) {
  646: 	return undef;
  647:     } else {
  648: 	return 1;
  649:     }
  650: }
  651: 
  652: # ---------------------------------------------------------- Append Environment
  653: 
  654: sub appenv {
  655:     my ($newenv,$roles) = @_;
  656:     if (ref($newenv) eq 'HASH') {
  657:         foreach my $key (keys(%{$newenv})) {
  658:             my $refused = 0;
  659: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  660:                 $refused = 1;
  661:                 if (ref($roles) eq 'ARRAY') {
  662:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
  663:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  664:                         $refused = 0;
  665:                     }
  666:                 }
  667:             }
  668:             if ($refused) {
  669:                 &logthis("<font color=\"blue\">WARNING: ".
  670:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  671:                          .'</font>');
  672: 	        delete($newenv->{$key});
  673:             } else {
  674:                 $env{$key}=$newenv->{$key};
  675:             }
  676:         }
  677:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
  678:         if ($opened
  679: 	    && &timed_flock($env_file,LOCK_EX)
  680: 	    &&
  681: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  682: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  683: 	    while (my ($key,$value) = each(%{$newenv})) {
  684: 	        $disk_env{$key} = $value;
  685: 	    }
  686: 	    untie(%disk_env);
  687:         }
  688:     }
  689:     return 'ok';
  690: }
  691: # ----------------------------------------------------- Delete from Environment
  692: 
  693: sub delenv {
  694:     my ($delthis,$regexp,$roles) = @_;
  695:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
  696:         my $refused = 1;
  697:         if (ref($roles) eq 'ARRAY') {
  698:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
  699:             if (grep(/^\Q$role\E$/,@{$roles})) {
  700:                 $refused = 0;
  701:             }
  702:         }
  703:         if ($refused) {
  704:             &logthis("<font color=\"blue\">WARNING: ".
  705:                      "Attempt to delete from environment ".$delthis);
  706:             return 'error';
  707:         }
  708:     }
  709:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  710:     if ($opened
  711: 	&& &timed_flock($env_file,LOCK_EX)
  712: 	&&
  713: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  714: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  715: 	foreach my $key (keys(%disk_env)) {
  716: 	    if ($regexp) {
  717:                 if ($key=~/^$delthis/) {
  718:                     delete($env{$key});
  719:                     delete($disk_env{$key});
  720:                 } 
  721:             } else {
  722:                 if ($key=~/^\Q$delthis\E/) {
  723: 		    delete($env{$key});
  724: 		    delete($disk_env{$key});
  725: 	        }
  726:             }
  727: 	}
  728: 	untie(%disk_env);
  729:     }
  730:     return 'ok';
  731: }
  732: 
  733: sub get_env_multiple {
  734:     my ($name) = @_;
  735:     my @values;
  736:     if (defined($env{$name})) {
  737:         # exists is it an array
  738:         if (ref($env{$name})) {
  739:             @values=@{ $env{$name} };
  740:         } else {
  741:             $values[0]=$env{$name};
  742:         }
  743:     }
  744:     return(@values);
  745: }
  746: 
  747: # ------------------------------------------------------------------- Locking
  748: 
  749: sub set_lock {
  750:     my ($text)=@_;
  751:     $locknum++;
  752:     my $id=$$.'-'.$locknum;
  753:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  754:              'session.lock.'.$id => $text});
  755:     return $id;
  756: }
  757: 
  758: sub get_locks {
  759:     my $num=0;
  760:     my %texts=();
  761:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  762:        if ($lock=~/\w/) {
  763:           $num++;
  764:           $texts{$lock}=$env{'session.lock.'.$lock};
  765:        }
  766:    }
  767:    return ($num,%texts);
  768: }
  769: 
  770: sub remove_lock {
  771:     my ($id)=@_;
  772:     my $newlocks='';
  773:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  774:        if (($lock=~/\w/) && ($lock ne $id)) {
  775:           $newlocks.=','.$lock;
  776:        }
  777:     }
  778:     &appenv({'session.locks' => $newlocks});
  779:     &delenv('session.lock.'.$id);
  780: }
  781: 
  782: sub remove_all_locks {
  783:     my $activelocks=$env{'session.locks'};
  784:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  785:        if ($lock=~/\w/) {
  786:           &remove_lock($lock);
  787:        }
  788:     }
  789: }
  790: 
  791: 
  792: # ------------------------------------------ Find out current server userload
  793: sub userload {
  794:     my $numusers=0;
  795:     {
  796: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  797: 	my $filename;
  798: 	my $curtime=time;
  799: 	while ($filename=readdir(LONIDS)) {
  800: 	    next if ($filename eq '.' || $filename eq '..');
  801: 	    next if ($filename =~ /publicuser_\d+\.id/);
  802: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  803: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  804: 	}
  805: 	closedir(LONIDS);
  806:     }
  807:     my $userloadpercent=0;
  808:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  809:     if ($maxuserload) {
  810: 	$userloadpercent=100*$numusers/$maxuserload;
  811:     }
  812:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  813:     return $userloadpercent;
  814: }
  815: 
  816: # ------------------------------ Find server with least workload from spare.tab
  817: 
  818: sub spareserver {
  819:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
  820:     my $spare_server;
  821:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  822:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  823:                                                      :  $userloadpercent;
  824:     my ($uint_dom,$remotesessions);
  825:     if (($udom ne '') && (&domain($udom) ne '')) {
  826:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
  827:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
  828:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
  829:         $remotesessions = $udomdefaults{'remotesessions'};
  830:     }
  831:     my $spareshash = &this_host_spares($udom);
  832:     if (ref($spareshash) eq 'HASH') {
  833:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  834:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  835:                 if ($uint_dom) {
  836:                     next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
  837:                                                  $try_server));
  838:                 }
  839: 	        ($spare_server, $lowest_load) =
  840: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
  841:             }
  842:         }
  843: 
  844:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
  845: 
  846:         if (!$found_server) {
  847:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
  848: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
  849:                     if ($uint_dom) {
  850:                         next unless (&spare_can_host($udom,$uint_dom,
  851:                                                      $remotesessions,$try_server));
  852:                     }
  853: 	            ($spare_server, $lowest_load) =
  854: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
  855:                 }
  856: 	    }
  857:         }
  858:     }
  859: 
  860:     if (!$want_server_name) {
  861:         my $protocol = 'http';
  862:         if ($protocol{$spare_server} eq 'https') {
  863:             $protocol = $protocol{$spare_server};
  864:         }
  865:         if (defined($spare_server)) {
  866:             my $hostname = &hostname($spare_server);
  867:             if (defined($hostname)) {
  868: 	        $spare_server = $protocol.'://'.$hostname;
  869:             }
  870:         }
  871:     }
  872:     return $spare_server;
  873: }
  874: 
  875: sub compare_server_load {
  876:     my ($try_server, $spare_server, $lowest_load) = @_;
  877: 
  878:     my $loadans     = &reply('load',    $try_server);
  879:     my $userloadans = &reply('userload',$try_server);
  880: 
  881:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  882: 	return ($spare_server, $lowest_load); #didn't get a number from the server
  883:     }
  884: 
  885:     my $load;
  886:     if ($loadans =~ /\d/) {
  887: 	if ($userloadans =~ /\d/) {
  888: 	    #both are numbers, pick the bigger one
  889: 	    $load = ($loadans > $userloadans) ? $loadans 
  890: 		                              : $userloadans;
  891: 	} else {
  892: 	    $load = $loadans;
  893: 	}
  894:     } else {
  895: 	$load = $userloadans;
  896:     }
  897: 
  898:     if (($load =~ /\d/) && ($load < $lowest_load)) {
  899: 	$spare_server = $try_server;
  900: 	$lowest_load  = $load;
  901:     }
  902:     return ($spare_server,$lowest_load);
  903: }
  904: 
  905: # --------------------------- ask offload servers if user already has a session
  906: sub find_existing_session {
  907:     my ($udom,$uname) = @_;
  908:     my $spareshash = &this_host_spares($udom);
  909:     if (ref($spareshash) eq 'HASH') {
  910:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  911:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  912:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
  913:             }
  914:         }
  915:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
  916:             foreach my $try_server (@{ $spareshash->{'default'} }) {
  917:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
  918:             }
  919:         }
  920:     }
  921:     return;
  922: }
  923: 
  924: # -------------------------------- ask if server already has a session for user
  925: sub has_user_session {
  926:     my ($lonid,$udom,$uname) = @_;
  927:     my $result = &reply(join(':','userhassession',
  928: 			     map {&escape($_)} ($udom,$uname)),$lonid);
  929:     return 1 if ($result eq 'ok');
  930: 
  931:     return 0;
  932: }
  933: 
  934: # --------- determine least loaded server in a user's domain which allows login
  935: 
  936: sub choose_server {
  937:     my ($udom,$checkloginvia) = @_;
  938:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
  939:     my %servers = &get_servers($udom);
  940:     my $lowest_load = 30000;
  941:     my ($login_host,$hostname,$portal_path,$isredirect);
  942:     foreach my $lonhost (keys(%servers)) {
  943:         my $loginvia;
  944:         if ($checkloginvia) {
  945:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
  946:             if ($loginvia) {
  947:                 my ($server,$path) = split(/:/,$loginvia);
  948:                 ($login_host, $lowest_load) =
  949:                     &compare_server_load($server, $login_host, $lowest_load);
  950:                 if ($login_host eq $server) {
  951:                     $portal_path = $path;
  952:                     $isredirect = 1;
  953:                 }
  954:             } else {
  955:                 ($login_host, $lowest_load) =
  956:                     &compare_server_load($lonhost, $login_host, $lowest_load);
  957:                 if ($login_host eq $lonhost) {
  958:                     $portal_path = '';
  959:                     $isredirect = ''; 
  960:                 }
  961:             }
  962:         } else {
  963:             ($login_host, $lowest_load) =
  964:                 &compare_server_load($lonhost, $login_host, $lowest_load);
  965:         }
  966:     }
  967:     if ($login_host ne '') {
  968:         $hostname = &hostname($login_host);
  969:     }
  970:     return ($login_host,$hostname,$portal_path,$isredirect);
  971: }
  972: 
  973: # --------------------------------------------- Try to change a user's password
  974: 
  975: sub changepass {
  976:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
  977:     $currentpass = &escape($currentpass);
  978:     $newpass     = &escape($newpass);
  979:     my $lonhost = $perlvar{'lonHostID'};
  980:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
  981: 		       $server);
  982:     if (! $answer) {
  983: 	&logthis("No reply on password change request to $server ".
  984: 		 "by $uname in domain $udom.");
  985:     } elsif ($answer =~ "^ok") {
  986:         &logthis("$uname in $udom successfully changed their password ".
  987: 		 "on $server.");
  988:     } elsif ($answer =~ "^pwchange_failure") {
  989: 	&logthis("$uname in $udom was unable to change their password ".
  990: 		 "on $server.  The action was blocked by either lcpasswd ".
  991: 		 "or pwchange");
  992:     } elsif ($answer =~ "^non_authorized") {
  993:         &logthis("$uname in $udom did not get their password correct when ".
  994: 		 "attempting to change it on $server.");
  995:     } elsif ($answer =~ "^auth_mode_error") {
  996:         &logthis("$uname in $udom attempted to change their password despite ".
  997: 		 "not being locally or internally authenticated on $server.");
  998:     } elsif ($answer =~ "^unknown_user") {
  999:         &logthis("$uname in $udom attempted to change their password ".
 1000: 		 "on $server but were unable to because $server is not ".
 1001: 		 "their home server.");
 1002:     } elsif ($answer =~ "^refused") {
 1003: 	&logthis("$server refused to change $uname in $udom password because ".
 1004: 		 "it was sent an unencrypted request to change the password.");
 1005:     } elsif ($answer =~ "invalid_client") {
 1006:         &logthis("$server refused to change $uname in $udom password because ".
 1007:                  "it was a reset by e-mail originating from an invalid server.");
 1008:     }
 1009:     return $answer;
 1010: }
 1011: 
 1012: # ----------------------- Try to determine user's current authentication scheme
 1013: 
 1014: sub queryauthenticate {
 1015:     my ($uname,$udom)=@_;
 1016:     my $uhome=&homeserver($uname,$udom);
 1017:     if (!$uhome) {
 1018: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
 1019: 	return 'no_host';
 1020:     }
 1021:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
 1022:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
 1023: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1024:     }
 1025:     return $answer;
 1026: }
 1027: 
 1028: # --------- Try to authenticate user from domain's lib servers (first this one)
 1029: 
 1030: sub authenticate {
 1031:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
 1032:     $upass=&escape($upass);
 1033:     $uname= &LONCAPA::clean_username($uname);
 1034:     my $uhome=&homeserver($uname,$udom,1);
 1035:     my $newhome;
 1036:     if ((!$uhome) || ($uhome eq 'no_host')) {
 1037: # Maybe the machine was offline and only re-appeared again recently?
 1038:         &reconlonc();
 1039: # One more
 1040: 	$uhome=&homeserver($uname,$udom,1);
 1041:         if (($uhome eq 'no_host') && $checkdefauth) {
 1042:             if (defined(&domain($udom,'primary'))) {
 1043:                 $newhome=&domain($udom,'primary');
 1044:             }
 1045:             if ($newhome ne '') {
 1046:                 $uhome = $newhome;
 1047:             }
 1048:         }
 1049: 	if ((!$uhome) || ($uhome eq 'no_host')) {
 1050: 	    &logthis("User $uname at $udom is unknown in authenticate");
 1051: 	    return 'no_host';
 1052:         }
 1053:     }
 1054:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
 1055:     if ($answer eq 'authorized') {
 1056:         if ($newhome) {
 1057:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
 1058:             return 'no_account_on_host'; 
 1059:         } else {
 1060:             &logthis("User $uname at $udom authorized by $uhome");
 1061:             return $uhome;
 1062:         }
 1063:     }
 1064:     if ($answer eq 'non_authorized') {
 1065: 	&logthis("User $uname at $udom rejected by $uhome");
 1066: 	return 'no_host'; 
 1067:     }
 1068:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1069:     return 'no_host';
 1070: }
 1071: 
 1072: sub can_host_session {
 1073:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
 1074:     my $canhost = 1;
 1075:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
 1076:     if (ref($remotesessions) eq 'HASH') {
 1077:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
 1078:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
 1079:                 $canhost = 0;
 1080:             } else {
 1081:                 $canhost = 1;
 1082:             }
 1083:         }
 1084:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
 1085:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
 1086:                 $canhost = 1;
 1087:             } else {
 1088:                 $canhost = 0;
 1089:             }
 1090:         }
 1091:         if ($canhost) {
 1092:             if ($remotesessions->{'version'} ne '') {
 1093:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
 1094:                 if ($reqmajor ne '' && $reqminor ne '') {
 1095:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
 1096:                         my $major = $1;
 1097:                         my $minor = $2;
 1098:                         if (($major < $reqmajor ) ||
 1099:                             (($major == $reqmajor) && ($minor < $reqminor))) {
 1100:                             $canhost = 0;
 1101:                         }
 1102:                     } else {
 1103:                         $canhost = 0;
 1104:                     }
 1105:                 }
 1106:             }
 1107:         }
 1108:     }
 1109:     if ($canhost) {
 1110:         if (ref($hostedsessions) eq 'HASH') {
 1111:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1112:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 1113:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
 1114:                 if (($uint_dom ne '') && 
 1115:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
 1116:                     $canhost = 0;
 1117:                 } else {
 1118:                     $canhost = 1;
 1119:                 }
 1120:             }
 1121:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
 1122:                 if (($uint_dom ne '') && 
 1123:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
 1124:                     $canhost = 1;
 1125:                 } else {
 1126:                     $canhost = 0;
 1127:                 }
 1128:             }
 1129:         }
 1130:     }
 1131:     return $canhost;
 1132: }
 1133: 
 1134: sub spare_can_host {
 1135:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
 1136:     my $canhost=1;
 1137:     my @intdoms;
 1138:     my $internet_names = &Apache::lonnet::get_internet_names($try_server);
 1139:     if (ref($internet_names) eq 'ARRAY') {
 1140:         @intdoms = @{$internet_names};
 1141:     }
 1142:     unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1143:         my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
 1144:         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
 1145:         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
 1146:         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
 1147:         $canhost = &can_host_session($udom,$try_server,$remoterev,
 1148:                                      $remotesessions,
 1149:                                      $defdomdefaults{'hostedsessions'});
 1150:     }
 1151:     return $canhost;
 1152: }
 1153: 
 1154: sub this_host_spares {
 1155:     my ($dom) = @_;
 1156:     my ($dom_in_use,$lonhost_in_use,$result);
 1157:     my @hosts = &current_machine_ids();
 1158:     foreach my $lonhost (@hosts) {
 1159:         if (&host_domain($lonhost) eq $dom) {
 1160:             $dom_in_use = $dom;
 1161:             $lonhost_in_use = $lonhost;
 1162:             last;
 1163:         }
 1164:     }
 1165:     if ($dom_in_use ne '') {
 1166:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1167:     }
 1168:     if (ref($result) ne 'HASH') {
 1169:         $lonhost_in_use = $perlvar{'lonHostID'};
 1170:         $dom_in_use = &host_domain($lonhost_in_use);
 1171:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1172:         if (ref($result) ne 'HASH') {
 1173:             $result = \%spareid;
 1174:         }
 1175:     }
 1176:     return $result;
 1177: }
 1178: 
 1179: sub spares_for_offload  {
 1180:     my ($dom_in_use,$lonhost_in_use) = @_;
 1181:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
 1182:     if (defined($cached)) {
 1183:         return $result;
 1184:     } else {
 1185:         my $cachetime = 60*60*24;
 1186:         my %domconfig =
 1187:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
 1188:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1189:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
 1190:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
 1191:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
 1192:                 }
 1193:             }
 1194:         }
 1195:     }
 1196:     return;
 1197: }
 1198: 
 1199: sub get_lonbalancer_config {
 1200:     my ($servers) = @_;
 1201:     my ($currbalancer,$currtargets);
 1202:     if (ref($servers) eq 'HASH') {
 1203:         foreach my $server (keys(%{$servers})) {
 1204:             my %what = (
 1205:                          spareid => 1,
 1206:                          perlvar => 1,
 1207:                        );
 1208:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
 1209:             if ($result eq 'ok') {
 1210:                 if (ref($returnhash) eq 'HASH') {
 1211:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
 1212:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
 1213:                             $currbalancer = $server;
 1214:                             $currtargets = {};
 1215:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
 1216:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
 1217:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
 1218:                                 }
 1219:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
 1220:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
 1221:                                 }
 1222:                             }
 1223:                             last;
 1224:                         }
 1225:                     }
 1226:                 }
 1227:             }
 1228:         }
 1229:     }
 1230:     return ($currbalancer,$currtargets);
 1231: }
 1232: 
 1233: sub check_loadbalancing {
 1234:     my ($uname,$udom) = @_;
 1235:     my ($is_balancer,$dom_in_use,$homeintdom,$rule_in_effect,
 1236:         $offloadto,$otherserver);
 1237:     my $lonhost = $perlvar{'lonHostID'};
 1238:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1239:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
 1240:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
 1241:     my $serverhomedom = &host_domain($lonhost);
 1242: 
 1243:     my $cachetime = 60*60*24;
 1244: 
 1245:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1246:         $dom_in_use = $udom;
 1247:         $homeintdom = 1;
 1248:     } else {
 1249:         $dom_in_use = $serverhomedom;
 1250:     }
 1251:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
 1252:     unless (defined($cached)) {
 1253:         my %domconfig =
 1254:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
 1255:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1256:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1257:         }
 1258:     }
 1259:     if (ref($result) eq 'HASH') {
 1260:         my $currbalancer = $result->{'lonhost'};
 1261:         my $currtargets = $result->{'targets'};
 1262:         my $currrules = $result->{'rules'};
 1263:         if ($currbalancer ne '') {
 1264:             my @hosts = &current_machine_ids();
 1265:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
 1266:                 $is_balancer = 1;
 1267:             }
 1268:         }
 1269:         if ($is_balancer) {
 1270:             if (ref($currrules) eq 'HASH') {
 1271:                 if ($homeintdom) {
 1272:                     if ($uname ne '') {
 1273:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
 1274:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
 1275:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
 1276:                                 $rule_in_effect = $currrules->{'_LC_author'};
 1277:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
 1278:                                 $rule_in_effect = $currrules->{'_LC_adv'}
 1279:                             }
 1280:                         }
 1281:                         if ($rule_in_effect eq '') {
 1282:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
 1283:                             if ($userenv{'inststatus'} ne '') {
 1284:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
 1285:                                 my ($othertitle,$usertypes,$types) =
 1286:                                     &Apache::loncommon::sorted_inst_types($udom);
 1287:                                 if (ref($types) eq 'ARRAY') {
 1288:                                     foreach my $type (@{$types}) {
 1289:                                         if (grep(/^\Q$type\E$/,@statuses)) {
 1290:                                             if (exists($currrules->{$type})) {
 1291:                                                 $rule_in_effect = $currrules->{$type};
 1292:                                             }
 1293:                                         }
 1294:                                     }
 1295:                                 }
 1296:                             } else {
 1297:                                 if (exists($currrules->{'default'})) {
 1298:                                     $rule_in_effect = $currrules->{'default'};
 1299:                                 }
 1300:                             }
 1301:                         }
 1302:                     } else {
 1303:                         if (exists($currrules->{'default'})) {
 1304:                             $rule_in_effect = $currrules->{'default'};
 1305:                         }
 1306:                     }
 1307:                 } else {
 1308:                     if ($currrules->{'_LC_external'} ne '') {
 1309:                         $rule_in_effect = $currrules->{'_LC_external'};
 1310:                     }
 1311:                 }
 1312:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1313:                                                        $uname,$udom);
 1314:             }
 1315:         }
 1316:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
 1317:         my ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
 1318:         unless (defined($cached)) {
 1319:             my %domconfig =
 1320:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
 1321:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1322:                 $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1323:             }
 1324:         }
 1325:         if (ref($result) eq 'HASH') {
 1326:             my $currbalancer = $result->{'lonhost'};
 1327:             my $currtargets = $result->{'targets'};
 1328:             my $currrules = $result->{'rules'};
 1329: 
 1330:             if ($currbalancer eq $lonhost) {
 1331:                 $is_balancer = 1;
 1332:                 if (ref($currrules) eq 'HASH') {
 1333:                     if ($currrules->{'_LC_internetdom'} ne '') {
 1334:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
 1335:                     }
 1336:                 }
 1337:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1338:                                                        $uname,$udom);
 1339:             }
 1340:         } else {
 1341:             if ($perlvar{'lonBalancer'} eq 'yes') {
 1342:                 $is_balancer = 1;
 1343:                 $offloadto = &this_host_spares($dom_in_use);
 1344:             }
 1345:         }
 1346:     } else {
 1347:         if ($perlvar{'lonBalancer'} eq 'yes') {
 1348:             $is_balancer = 1;
 1349:             $offloadto = &this_host_spares($dom_in_use);
 1350:         }
 1351:     }
 1352:     my $lowest_load = 30000;
 1353:     if (ref($offloadto) eq 'HASH') {
 1354:         if (ref($offloadto->{'primary'}) eq 'ARRAY') {
 1355:             foreach my $try_server (@{$offloadto->{'primary'}}) {
 1356:                 ($otherserver,$lowest_load) =
 1357:                     &compare_server_load($try_server,$otherserver,$lowest_load);
 1358:             }
 1359:         }
 1360:         my $found_server = ($otherserver ne '' && $lowest_load < 100);
 1361: 
 1362:         if (!$found_server) {
 1363:             if (ref($offloadto->{'default'}) eq 'ARRAY') {
 1364:                 foreach my $try_server (@{$offloadto->{'default'}}) {
 1365:                     ($otherserver,$lowest_load) =
 1366:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1367:                 }
 1368:             }
 1369:         }
 1370:     } elsif (ref($offloadto) eq 'ARRAY') {
 1371:         if (@{$offloadto} == 1) {
 1372:             $otherserver = $offloadto->[0];
 1373:         } elsif (@{$offloadto} > 1) {
 1374:             foreach my $try_server (@{$offloadto}) {
 1375:                 ($otherserver,$lowest_load) =
 1376:                     &compare_server_load($try_server,$otherserver,$lowest_load);
 1377:             }
 1378:         }
 1379:     }
 1380:     return ($is_balancer,$otherserver);
 1381: }
 1382: 
 1383: sub get_loadbalancer_targets {
 1384:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
 1385:     my $offloadto;
 1386:     if ($rule_in_effect eq '') {
 1387:         $offloadto = $currtargets;
 1388:     } else {
 1389:         if ($rule_in_effect eq 'homeserver') {
 1390:             my $homeserver = &homeserver($uname,$udom);
 1391:             if ($homeserver ne 'no_host') {
 1392:                 $offloadto = [$homeserver];
 1393:             }
 1394:         } elsif ($rule_in_effect eq 'externalbalancer') {
 1395:             my %domconfig =
 1396:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1397:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1398:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
 1399:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
 1400:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
 1401:                     }
 1402:                 }
 1403:             } else {
 1404:                 my %servers = &dom_servers($udom);
 1405:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
 1406:                 if (&hostname($remotebalancer) ne '') {
 1407:                     $offloadto = [$remotebalancer];
 1408:                 }
 1409:             }
 1410:         } elsif (&hostname($rule_in_effect) ne '') {
 1411:             $offloadto = [$rule_in_effect];
 1412:         }
 1413:     }
 1414:     return $offloadto;
 1415: }
 1416: 
 1417: sub internet_dom_servers {
 1418:     my ($dom) = @_;
 1419:     my (%uniqservers,%servers);
 1420:     my $primaryserver = &hostname(&domain($dom,'primary'));
 1421:     my @machinedoms = &machine_domains($primaryserver);
 1422:     foreach my $mdom (@machinedoms) {
 1423:         my %currservers = %servers;
 1424:         my %server = &get_servers($mdom);
 1425:         %servers = (%currservers,%server);
 1426:     }
 1427:     my %by_hostname;
 1428:     foreach my $id (keys(%servers)) {
 1429:         push(@{$by_hostname{$servers{$id}}},$id);
 1430:     }
 1431:     foreach my $hostname (sort(keys(%by_hostname))) {
 1432:         if (@{$by_hostname{$hostname}} > 1) {
 1433:             my $match = 0;
 1434:             foreach my $id (@{$by_hostname{$hostname}}) {
 1435:                 if (&host_domain($id) eq $dom) {
 1436:                     $uniqservers{$id} = $hostname;
 1437:                     $match = 1;
 1438:                 }
 1439:             }
 1440:             unless ($match) {
 1441:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1442:             }
 1443:         } else {
 1444:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1445:         }
 1446:     }
 1447:     return %uniqservers;
 1448: }
 1449: 
 1450: # ---------------------- Find the homebase for a user from domain's lib servers
 1451: 
 1452: my %homecache;
 1453: sub homeserver {
 1454:     my ($uname,$udom,$ignoreBadCache)=@_;
 1455:     my $index="$uname:$udom";
 1456: 
 1457:     if (exists($homecache{$index})) { return $homecache{$index}; }
 1458: 
 1459:     my %servers = &get_servers($udom,'library');
 1460:     foreach my $tryserver (keys(%servers)) {
 1461:         next if ($ignoreBadCache ne 'true' && 
 1462: 		 exists($badServerCache{$tryserver}));
 1463: 
 1464: 	my $answer=reply("home:$udom:$uname",$tryserver);
 1465: 	if ($answer eq 'found') {
 1466: 	    delete($badServerCache{$tryserver}); 
 1467: 	    return $homecache{$index}=$tryserver;
 1468: 	} elsif ($answer eq 'no_host') {
 1469: 	    $badServerCache{$tryserver}=1;
 1470: 	}
 1471:     }    
 1472:     return 'no_host';
 1473: }
 1474: 
 1475: # ------------------------------------- Find the usernames behind a list of IDs
 1476: 
 1477: sub idget {
 1478:     my ($udom,@ids)=@_;
 1479:     my %returnhash=();
 1480:     
 1481:     my %servers = &get_servers($udom,'library');
 1482:     foreach my $tryserver (keys(%servers)) {
 1483: 	my $idlist=join('&',@ids);
 1484: 	$idlist=~tr/A-Z/a-z/; 
 1485: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
 1486: 	my @answer=();
 1487: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
 1488: 	    @answer=split(/\&/,$reply);
 1489: 	}                    ;
 1490: 	my $i;
 1491: 	for ($i=0;$i<=$#ids;$i++) {
 1492: 	    if ($answer[$i]) {
 1493: 		$returnhash{$ids[$i]}=$answer[$i];
 1494: 	    } 
 1495: 	}
 1496:     } 
 1497:     return %returnhash;
 1498: }
 1499: 
 1500: # ------------------------------------- Find the IDs behind a list of usernames
 1501: 
 1502: sub idrget {
 1503:     my ($udom,@unames)=@_;
 1504:     my %returnhash=();
 1505:     foreach my $uname (@unames) {
 1506:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
 1507:     }
 1508:     return %returnhash;
 1509: }
 1510: 
 1511: # ------------------------------- Store away a list of names and associated IDs
 1512: 
 1513: sub idput {
 1514:     my ($udom,%ids)=@_;
 1515:     my %servers=();
 1516:     foreach my $uname (keys(%ids)) {
 1517: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
 1518:         my $uhom=&homeserver($uname,$udom);
 1519:         if ($uhom ne 'no_host') {
 1520:             my $id=&escape($ids{$uname});
 1521:             $id=~tr/A-Z/a-z/;
 1522:             my $esc_unam=&escape($uname);
 1523: 	    if ($servers{$uhom}) {
 1524: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
 1525:             } else {
 1526:                 $servers{$uhom}=$id.'='.$esc_unam;
 1527:             }
 1528:         }
 1529:     }
 1530:     foreach my $server (keys(%servers)) {
 1531:         &critical('idput:'.$udom.':'.$servers{$server},$server);
 1532:     }
 1533: }
 1534: 
 1535: # ------------------------------dump from db file owned by domainconfig user
 1536: sub dump_dom {
 1537:     my ($namespace,$udom,$regexp,$range)=@_;
 1538:     if (!$udom) {
 1539:         $udom=$env{'user.domain'};
 1540:     }
 1541:     my %returnhash;
 1542:     if ($udom) {
 1543:         my $uname = &get_domainconfiguser($udom);
 1544:         %returnhash = &dump($namespace,$udom,$uname,$regexp,$range);
 1545:     }
 1546:     return %returnhash;
 1547: }
 1548: 
 1549: # ------------------------------------------ get items from domain db files   
 1550: 
 1551: sub get_dom {
 1552:     my ($namespace,$storearr,$udom,$uhome)=@_;
 1553:     my $items='';
 1554:     foreach my $item (@$storearr) {
 1555:         $items.=&escape($item).'&';
 1556:     }
 1557:     $items=~s/\&$//;
 1558:     if (!$udom) {
 1559:         $udom=$env{'user.domain'};
 1560:         if (defined(&domain($udom,'primary'))) {
 1561:             $uhome=&domain($udom,'primary');
 1562:         } else {
 1563:             undef($uhome);
 1564:         }
 1565:     } else {
 1566:         if (!$uhome) {
 1567:             if (defined(&domain($udom,'primary'))) {
 1568:                 $uhome=&domain($udom,'primary');
 1569:             }
 1570:         }
 1571:     }
 1572:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1573:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 1574:         my %returnhash;
 1575:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 1576:             return %returnhash;
 1577:         }
 1578:         my @pairs=split(/\&/,$rep);
 1579:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 1580:             return @pairs;
 1581:         }
 1582:         my $i=0;
 1583:         foreach my $item (@$storearr) {
 1584:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 1585:             $i++;
 1586:         }
 1587:         return %returnhash;
 1588:     } else {
 1589:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 1590:     }
 1591: }
 1592: 
 1593: # -------------------------------------------- put items in domain db files 
 1594: 
 1595: sub put_dom {
 1596:     my ($namespace,$storehash,$udom,$uhome)=@_;
 1597:     if (!$udom) {
 1598:         $udom=$env{'user.domain'};
 1599:         if (defined(&domain($udom,'primary'))) {
 1600:             $uhome=&domain($udom,'primary');
 1601:         } else {
 1602:             undef($uhome);
 1603:         }
 1604:     } else {
 1605:         if (!$uhome) {
 1606:             if (defined(&domain($udom,'primary'))) {
 1607:                 $uhome=&domain($udom,'primary');
 1608:             }
 1609:         }
 1610:     } 
 1611:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1612:         my $items='';
 1613:         foreach my $item (keys(%$storehash)) {
 1614:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 1615:         }
 1616:         $items=~s/\&$//;
 1617:         return &reply("putdom:$udom:$namespace:$items",$uhome);
 1618:     } else {
 1619:         &logthis("put_dom failed - no homeserver and/or domain");
 1620:     }
 1621: }
 1622: 
 1623: # --------------------- newput for items in db file owned by domainconfig user
 1624: sub newput_dom {
 1625:     my ($namespace,$storehash,$udom) = @_;
 1626:     my $result;
 1627:     if (!$udom) {
 1628:         $udom=$env{'user.domain'};
 1629:     }
 1630:     if ($udom) {
 1631:         my $uname = &get_domainconfiguser($udom);
 1632:         $result = &newput($namespace,$storehash,$udom,$uname);
 1633:     }
 1634:     return $result;
 1635: }
 1636: 
 1637: # --------------------- delete for items in db file owned by domainconfig user
 1638: sub del_dom {
 1639:     my ($namespace,$storearr,$udom)=@_;
 1640:     if (ref($storearr) eq 'ARRAY') {
 1641:         if (!$udom) {
 1642:             $udom=$env{'user.domain'};
 1643:         }
 1644:         if ($udom) {
 1645:             my $uname = &get_domainconfiguser($udom); 
 1646:             return &del($namespace,$storearr,$udom,$uname);
 1647:         }
 1648:     }
 1649: }
 1650: 
 1651: # ----------------------------------construct domainconfig user for a domain 
 1652: sub get_domainconfiguser {
 1653:     my ($udom) = @_;
 1654:     return $udom.'-domainconfig';
 1655: }
 1656: 
 1657: sub retrieve_inst_usertypes {
 1658:     my ($udom) = @_;
 1659:     my (%returnhash,@order);
 1660:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 1661:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 1662:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 1663:         %returnhash = %{$domdefs{'inststatustypes'}};
 1664:         @order = @{$domdefs{'inststatusorder'}};
 1665:     } else {
 1666:         if (defined(&domain($udom,'primary'))) {
 1667:             my $uhome=&domain($udom,'primary');
 1668:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 1669:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 1670:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
 1671:                 return (\%returnhash,\@order);
 1672:             }
 1673:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 1674:             my @pairs=split(/\&/,$hashitems);
 1675:             foreach my $item (@pairs) {
 1676:                 my ($key,$value)=split(/=/,$item,2);
 1677:                 $key = &unescape($key);
 1678:                 next if ($key =~ /^error: 2 /);
 1679:                 $returnhash{$key}=&thaw_unescape($value);
 1680:             }
 1681:             my @esc_order = split(/\&/,$orderitems);
 1682:             foreach my $item (@esc_order) {
 1683:                 push(@order,&unescape($item));
 1684:             }
 1685:         } else {
 1686:             &logthis("get_dom failed - no primary domain server for $udom");
 1687:         }
 1688:     }
 1689:     return (\%returnhash,\@order);
 1690: }
 1691: 
 1692: sub is_domainimage {
 1693:     my ($url) = @_;
 1694:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
 1695:         if (&domain($1) ne '') {
 1696:             return '1';
 1697:         }
 1698:     }
 1699:     return;
 1700: }
 1701: 
 1702: sub inst_directory_query {
 1703:     my ($srch) = @_;
 1704:     my $udom = $srch->{'srchdomain'};
 1705:     my %results;
 1706:     my $homeserver = &domain($udom,'primary');
 1707:     my $outcome;
 1708:     if ($homeserver ne '') {
 1709: 	my $queryid=&reply("querysend:instdirsearch:".
 1710: 			   &escape($srch->{'srchby'}).':'.
 1711: 			   &escape($srch->{'srchterm'}).':'.
 1712: 			   &escape($srch->{'srchtype'}),$homeserver);
 1713: 	my $host=&hostname($homeserver);
 1714: 	if ($queryid !~/^\Q$host\E\_/) {
 1715: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1716: 	    return;
 1717: 	}
 1718: 	my $response = &get_query_reply($queryid);
 1719: 	my $maxtries = 5;
 1720: 	my $tries = 1;
 1721: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1722: 	    $response = &get_query_reply($queryid);
 1723: 	    $tries ++;
 1724: 	}
 1725: 
 1726:         if (!&error($response) && $response ne 'refused') {
 1727:             if ($response eq 'unavailable') {
 1728:                 $outcome = $response;
 1729:             } else {
 1730:                 $outcome = 'ok';
 1731:                 my @matches = split(/\n/,$response);
 1732:                 foreach my $match (@matches) {
 1733:                     my ($key,$value) = split(/=/,$match);
 1734:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 1735:                 }
 1736:             }
 1737:         }
 1738:     }
 1739:     return ($outcome,%results);
 1740: }
 1741: 
 1742: sub usersearch {
 1743:     my ($srch) = @_;
 1744:     my $dom = $srch->{'srchdomain'};
 1745:     my %results;
 1746:     my %libserv = &all_library();
 1747:     my $query = 'usersearch';
 1748:     foreach my $tryserver (keys(%libserv)) {
 1749:         if (&host_domain($tryserver) eq $dom) {
 1750:             my $host=&hostname($tryserver);
 1751:             my $queryid=
 1752:                 &reply("querysend:".&escape($query).':'.
 1753:                        &escape($srch->{'srchby'}).':'.
 1754:                        &escape($srch->{'srchtype'}).':'.
 1755:                        &escape($srch->{'srchterm'}),$tryserver);
 1756:             if ($queryid !~/^\Q$host\E\_/) {
 1757:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 1758:                 next;
 1759:             }
 1760:             my $reply = &get_query_reply($queryid);
 1761:             my $maxtries = 1;
 1762:             my $tries = 1;
 1763:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 1764:                 $reply = &get_query_reply($queryid);
 1765:                 $tries ++;
 1766:             }
 1767:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 1768:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 1769:             } else {
 1770:                 my @matches;
 1771:                 if ($reply =~ /\n/) {
 1772:                     @matches = split(/\n/,$reply);
 1773:                 } else {
 1774:                     @matches = split(/\&/,$reply);
 1775:                 }
 1776:                 foreach my $match (@matches) {
 1777:                     my ($uname,$udom,%userhash);
 1778:                     foreach my $entry (split(/:/,$match)) {
 1779:                         my ($key,$value) =
 1780:                             map {&unescape($_);} split(/=/,$entry);
 1781:                         $userhash{$key} = $value;
 1782:                         if ($key eq 'username') {
 1783:                             $uname = $value;
 1784:                         } elsif ($key eq 'domain') {
 1785:                             $udom = $value;
 1786:                         }
 1787:                     }
 1788:                     $results{$uname.':'.$udom} = \%userhash;
 1789:                 }
 1790:             }
 1791:         }
 1792:     }
 1793:     return %results;
 1794: }
 1795: 
 1796: sub get_instuser {
 1797:     my ($udom,$uname,$id) = @_;
 1798:     my $homeserver = &domain($udom,'primary');
 1799:     my ($outcome,%results);
 1800:     if ($homeserver ne '') {
 1801:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 1802:                            &escape($id).':'.&escape($udom),$homeserver);
 1803:         my $host=&hostname($homeserver);
 1804:         if ($queryid !~/^\Q$host\E\_/) {
 1805:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1806:             return;
 1807:         }
 1808:         my $response = &get_query_reply($queryid);
 1809:         my $maxtries = 5;
 1810:         my $tries = 1;
 1811:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1812:             $response = &get_query_reply($queryid);
 1813:             $tries ++;
 1814:         }
 1815:         if (!&error($response) && $response ne 'refused') {
 1816:             if ($response eq 'unavailable') {
 1817:                 $outcome = $response;
 1818:             } else {
 1819:                 $outcome = 'ok';
 1820:                 my @matches = split(/\n/,$response);
 1821:                 foreach my $match (@matches) {
 1822:                     my ($key,$value) = split(/=/,$match);
 1823:                     $results{&unescape($key)} = &thaw_unescape($value);
 1824:                 }
 1825:             }
 1826:         }
 1827:     }
 1828:     my %userinfo;
 1829:     if (ref($results{$uname}) eq 'HASH') {
 1830:         %userinfo = %{$results{$uname}};
 1831:     } 
 1832:     return ($outcome,%userinfo);
 1833: }
 1834: 
 1835: sub inst_rulecheck {
 1836:     my ($udom,$uname,$id,$item,$rules) = @_;
 1837:     my %returnhash;
 1838:     if ($udom ne '') {
 1839:         if (ref($rules) eq 'ARRAY') {
 1840:             @{$rules} = map {&escape($_);} (@{$rules});
 1841:             my $rulestr = join(':',@{$rules});
 1842:             my $homeserver=&domain($udom,'primary');
 1843:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1844:                 my $response;
 1845:                 if ($item eq 'username') {                
 1846:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 1847:                                               ':'.&escape($uname).':'.$rulestr,
 1848:                                               $homeserver));
 1849:                 } elsif ($item eq 'id') {
 1850:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 1851:                                               ':'.&escape($id).':'.$rulestr,
 1852:                                               $homeserver));
 1853:                 } elsif ($item eq 'selfcreate') {
 1854:                     $response=&unescape(&reply('instselfcreatecheck:'.
 1855:                                                &escape($udom).':'.&escape($uname).
 1856:                                               ':'.$rulestr,$homeserver));
 1857:                 }
 1858:                 if ($response ne 'refused') {
 1859:                     my @pairs=split(/\&/,$response);
 1860:                     foreach my $item (@pairs) {
 1861:                         my ($key,$value)=split(/=/,$item,2);
 1862:                         $key = &unescape($key);
 1863:                         next if ($key =~ /^error: 2 /);
 1864:                         $returnhash{$key}=&thaw_unescape($value);
 1865:                     }
 1866:                 }
 1867:             }
 1868:         }
 1869:     }
 1870:     return %returnhash;
 1871: }
 1872: 
 1873: sub inst_userrules {
 1874:     my ($udom,$check) = @_;
 1875:     my (%ruleshash,@ruleorder);
 1876:     if ($udom ne '') {
 1877:         my $homeserver=&domain($udom,'primary');
 1878:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1879:             my $response;
 1880:             if ($check eq 'id') {
 1881:                 $response=&reply('instidrules:'.&escape($udom),
 1882:                                  $homeserver);
 1883:             } elsif ($check eq 'email') {
 1884:                 $response=&reply('instemailrules:'.&escape($udom),
 1885:                                  $homeserver);
 1886:             } else {
 1887:                 $response=&reply('instuserrules:'.&escape($udom),
 1888:                                  $homeserver);
 1889:             }
 1890:             if (($response ne 'refused') && ($response ne 'error') && 
 1891:                 ($response ne 'unknown_cmd') && 
 1892:                 ($response ne 'no_such_host')) {
 1893:                 my ($hashitems,$orderitems) = split(/:/,$response);
 1894:                 my @pairs=split(/\&/,$hashitems);
 1895:                 foreach my $item (@pairs) {
 1896:                     my ($key,$value)=split(/=/,$item,2);
 1897:                     $key = &unescape($key);
 1898:                     next if ($key =~ /^error: 2 /);
 1899:                     $ruleshash{$key}=&thaw_unescape($value);
 1900:                 }
 1901:                 my @esc_order = split(/\&/,$orderitems);
 1902:                 foreach my $item (@esc_order) {
 1903:                     push(@ruleorder,&unescape($item));
 1904:                 }
 1905:             }
 1906:         }
 1907:     }
 1908:     return (\%ruleshash,\@ruleorder);
 1909: }
 1910: 
 1911: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 1912: 
 1913: sub get_domain_defaults {
 1914:     my ($domain) = @_;
 1915:     my $cachetime = 60*60*24;
 1916:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 1917:     if (defined($cached)) {
 1918:         if (ref($result) eq 'HASH') {
 1919:             return %{$result};
 1920:         }
 1921:     }
 1922:     my %domdefaults;
 1923:     my %domconfig =
 1924:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 1925:                                   'requestcourses','inststatus',
 1926:                                   'coursedefaults','usersessions'],$domain);
 1927:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 1928:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 1929:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 1930:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 1931:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 1932:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 1933:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
 1934:     } else {
 1935:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 1936:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 1937:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 1938:     }
 1939:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 1940:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 1941:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 1942:         } else {
 1943:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 1944:         } 
 1945:         my @usertools = ('aboutme','blog','portfolio');
 1946:         foreach my $item (@usertools) {
 1947:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 1948:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 1949:             }
 1950:         }
 1951:     }
 1952:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 1953:         foreach my $item ('official','unofficial','community') {
 1954:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 1955:         }
 1956:     }
 1957:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 1958:         foreach my $item ('inststatustypes','inststatusorder') {
 1959:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 1960:         }
 1961:     }
 1962:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 1963:         foreach my $item ('canuse_pdfforms') {
 1964:             $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
 1965:         }
 1966:     }
 1967:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1968:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 1969:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 1970:         }
 1971:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 1972:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 1973:         }
 1974:     }
 1975:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
 1976:                                   $cachetime);
 1977:     return %domdefaults;
 1978: }
 1979: 
 1980: # --------------------------------------------------- Assign a key to a student
 1981: 
 1982: sub assign_access_key {
 1983: #
 1984: # a valid key looks like uname:udom#comments
 1985: # comments are being appended
 1986: #
 1987:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 1988:     $kdom=
 1989:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 1990:     $knum=
 1991:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 1992:     $cdom=
 1993:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1994:     $cnum=
 1995:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1996:     $udom=$env{'user.name'} unless (defined($udom));
 1997:     $uname=$env{'user.domain'} unless (defined($uname));
 1998:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 1999:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 2000:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 2001:                                                   # assigned to this person
 2002:                                                   # - this should not happen,
 2003:                                                   # unless something went wrong
 2004:                                                   # the first time around
 2005: # ready to assign
 2006:         $logentry=$1.'; '.$logentry;
 2007:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 2008:                                                  $kdom,$knum) eq 'ok') {
 2009: # key now belongs to user
 2010: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 2011:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 2012:                 &appenv({'environment.'.$envkey => $ckey});
 2013:                 return 'ok';
 2014:             } else {
 2015:                 return 
 2016:   'error: Count not permanently assign key, will need to be re-entered later.';
 2017: 	    }
 2018:         } else {
 2019:             return 'error: Could not assign key, try again later.';
 2020:         }
 2021:     } elsif (!$existing{$ckey}) {
 2022: # the key does not exist
 2023: 	return 'error: The key does not exist';
 2024:     } else {
 2025: # the key is somebody else's
 2026: 	return 'error: The key is already in use';
 2027:     }
 2028: }
 2029: 
 2030: # ------------------------------------------ put an additional comment on a key
 2031: 
 2032: sub comment_access_key {
 2033: #
 2034: # a valid key looks like uname:udom#comments
 2035: # comments are being appended
 2036: #
 2037:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 2038:     $cdom=
 2039:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2040:     $cnum=
 2041:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2042:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2043:     if ($existing{$ckey}) {
 2044:         $existing{$ckey}.='; '.$logentry;
 2045: # ready to assign
 2046:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 2047:                                                  $cdom,$cnum) eq 'ok') {
 2048: 	    return 'ok';
 2049:         } else {
 2050: 	    return 'error: Count not store comment.';
 2051:         }
 2052:     } else {
 2053: # the key does not exist
 2054: 	return 'error: The key does not exist';
 2055:     }
 2056: }
 2057: 
 2058: # ------------------------------------------------------ Generate a set of keys
 2059: 
 2060: sub generate_access_keys {
 2061:     my ($number,$cdom,$cnum,$logentry)=@_;
 2062:     $cdom=
 2063:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2064:     $cnum=
 2065:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2066:     unless (&allowed('mky',$cdom)) { return 0; }
 2067:     unless (($cdom) && ($cnum)) { return 0; }
 2068:     if ($number>10000) { return 0; }
 2069:     sleep(2); # make sure don't get same seed twice
 2070:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 2071:     my $total=0;
 2072:     for (my $i=1;$i<=$number;$i++) {
 2073:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 2074:                   sprintf("%lx",int(100000*rand)).'-'.
 2075:                   sprintf("%lx",int(100000*rand));
 2076:        $newkey=~s/1/g/g; # folks mix up 1 and l
 2077:        $newkey=~s/0/h/g; # and also 0 and O
 2078:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 2079:        if ($existing{$newkey}) {
 2080:            $i--;
 2081:        } else {
 2082: 	  if (&put('accesskeys',
 2083:               { $newkey => '# generated '.localtime().
 2084:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 2085:                            '; '.$logentry },
 2086: 		   $cdom,$cnum) eq 'ok') {
 2087:               $total++;
 2088: 	  }
 2089:        }
 2090:     }
 2091:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 2092:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 2093:     return $total;
 2094: }
 2095: 
 2096: # ------------------------------------------------------- Validate an accesskey
 2097: 
 2098: sub validate_access_key {
 2099:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 2100:     $cdom=
 2101:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2102:     $cnum=
 2103:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2104:     $udom=$env{'user.domain'} unless (defined($udom));
 2105:     $uname=$env{'user.name'} unless (defined($uname));
 2106:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2107:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 2108: }
 2109: 
 2110: # ------------------------------------- Find the section of student in a course
 2111: sub devalidate_getsection_cache {
 2112:     my ($udom,$unam,$courseid)=@_;
 2113:     my $hashid="$udom:$unam:$courseid";
 2114:     &devalidate_cache_new('getsection',$hashid);
 2115: }
 2116: 
 2117: sub courseid_to_courseurl {
 2118:     my ($courseid) = @_;
 2119:     #already url style courseid
 2120:     return $courseid if ($courseid =~ m{^/});
 2121: 
 2122:     if (exists($env{'course.'.$courseid.'.num'})) {
 2123: 	my $cnum = $env{'course.'.$courseid.'.num'};
 2124: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 2125: 	return "/$cdom/$cnum";
 2126:     }
 2127: 
 2128:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 2129:     if (exists($courseinfo{'num'})) {
 2130: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 2131:     }
 2132: 
 2133:     return undef;
 2134: }
 2135: 
 2136: sub getsection {
 2137:     my ($udom,$unam,$courseid)=@_;
 2138:     my $cachetime=1800;
 2139: 
 2140:     my $hashid="$udom:$unam:$courseid";
 2141:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 2142:     if (defined($cached)) { return $result; }
 2143: 
 2144:     my %Pending; 
 2145:     my %Expired;
 2146:     #
 2147:     # Each role can either have not started yet (pending), be active, 
 2148:     #    or have expired.
 2149:     #
 2150:     # If there is an active role, we are done.
 2151:     #
 2152:     # If there is more than one role which has not started yet, 
 2153:     #     choose the one which will start sooner
 2154:     # If there is one role which has not started yet, return it.
 2155:     #
 2156:     # If there is more than one expired role, choose the one which ended last.
 2157:     # If there is a role which has expired, return it.
 2158:     #
 2159:     $courseid = &courseid_to_courseurl($courseid);
 2160:     my $extra = &freeze_escape({'skipcheck' => 1});
 2161:     my %roleshash = &dump('roles',$udom,$unam,$courseid,undef,$extra);
 2162:     foreach my $key (keys(%roleshash)) {
 2163:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 2164:         my $section=$1;
 2165:         if ($key eq $courseid.'_st') { $section=''; }
 2166:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 2167:         my $now=time;
 2168:         if (defined($end) && $end && ($now > $end)) {
 2169:             $Expired{$end}=$section;
 2170:             next;
 2171:         }
 2172:         if (defined($start) && $start && ($now < $start)) {
 2173:             $Pending{$start}=$section;
 2174:             next;
 2175:         }
 2176:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 2177:     }
 2178:     #
 2179:     # Presumedly there will be few matching roles from the above
 2180:     # loop and the sorting time will be negligible.
 2181:     if (scalar(keys(%Pending))) {
 2182:         my ($time) = sort {$a <=> $b} keys(%Pending);
 2183:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 2184:     } 
 2185:     if (scalar(keys(%Expired))) {
 2186:         my @sorted = sort {$a <=> $b} keys(%Expired);
 2187:         my $time = pop(@sorted);
 2188:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 2189:     }
 2190:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 2191: }
 2192: 
 2193: sub save_cache {
 2194:     &purge_remembered();
 2195:     #&Apache::loncommon::validate_page();
 2196:     undef(%env);
 2197:     undef($env_loaded);
 2198: }
 2199: 
 2200: my $to_remember=-1;
 2201: my %remembered;
 2202: my %accessed;
 2203: my $kicks=0;
 2204: my $hits=0;
 2205: sub make_key {
 2206:     my ($name,$id) = @_;
 2207:     if (length($id) > 65 
 2208: 	&& length(&escape($id)) > 200) {
 2209: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 2210:     }
 2211:     return &escape($name.':'.$id);
 2212: }
 2213: 
 2214: sub devalidate_cache_new {
 2215:     my ($name,$id,$debug) = @_;
 2216:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 2217:     $id=&make_key($name,$id);
 2218:     $memcache->delete($id);
 2219:     delete($remembered{$id});
 2220:     delete($accessed{$id});
 2221: }
 2222: 
 2223: sub is_cached_new {
 2224:     my ($name,$id,$debug) = @_;
 2225:     $id=&make_key($name,$id);
 2226:     if (exists($remembered{$id})) {
 2227: 	if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
 2228: 	$accessed{$id}=[&gettimeofday()];
 2229: 	$hits++;
 2230: 	return ($remembered{$id},1);
 2231:     }
 2232:     my $value = $memcache->get($id);
 2233:     if (!(defined($value))) {
 2234: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 2235: 	return (undef,undef);
 2236:     }
 2237:     if ($value eq '__undef__') {
 2238: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 2239: 	$value=undef;
 2240:     }
 2241:     &make_room($id,$value,$debug);
 2242:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 2243:     return ($value,1);
 2244: }
 2245: 
 2246: sub do_cache_new {
 2247:     my ($name,$id,$value,$time,$debug) = @_;
 2248:     $id=&make_key($name,$id);
 2249:     my $setvalue=$value;
 2250:     if (!defined($setvalue)) {
 2251: 	$setvalue='__undef__';
 2252:     }
 2253:     if (!defined($time) ) {
 2254: 	$time=600;
 2255:     }
 2256:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 2257:     my $result = $memcache->set($id,$setvalue,$time);
 2258:     if (! $result) {
 2259: 	&logthis("caching of id -> $id  failed");
 2260: 	$memcache->disconnect_all();
 2261:     }
 2262:     # need to make a copy of $value
 2263:     &make_room($id,$value,$debug);
 2264:     return $value;
 2265: }
 2266: 
 2267: sub make_room {
 2268:     my ($id,$value,$debug)=@_;
 2269: 
 2270:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
 2271:                                     : $value;
 2272:     if ($to_remember<0) { return; }
 2273:     $accessed{$id}=[&gettimeofday()];
 2274:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 2275:     my $to_kick;
 2276:     my $max_time=0;
 2277:     foreach my $other (keys(%accessed)) {
 2278: 	if (&tv_interval($accessed{$other}) > $max_time) {
 2279: 	    $to_kick=$other;
 2280: 	    $max_time=&tv_interval($accessed{$other});
 2281: 	}
 2282:     }
 2283:     delete($remembered{$to_kick});
 2284:     delete($accessed{$to_kick});
 2285:     $kicks++;
 2286:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 2287:     return;
 2288: }
 2289: 
 2290: sub purge_remembered {
 2291:     #&logthis("Tossing ".scalar(keys(%remembered)));
 2292:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 2293:     undef(%remembered);
 2294:     undef(%accessed);
 2295: }
 2296: # ------------------------------------- Read an entry from a user's environment
 2297: 
 2298: sub userenvironment {
 2299:     my ($udom,$unam,@what)=@_;
 2300:     my $items;
 2301:     foreach my $item (@what) {
 2302:         $items.=&escape($item).'&';
 2303:     }
 2304:     $items=~s/\&$//;
 2305:     my %returnhash=();
 2306:     my $uhome = &homeserver($unam,$udom);
 2307:     unless ($uhome eq 'no_host') {
 2308:         my @answer=split(/\&/, 
 2309:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 2310:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 2311:             return %returnhash;
 2312:         }
 2313:         my $i;
 2314:         for ($i=0;$i<=$#what;$i++) {
 2315: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 2316:         }
 2317:     }
 2318:     return %returnhash;
 2319: }
 2320: 
 2321: # ---------------------------------------------------------- Get a studentphoto
 2322: sub studentphoto {
 2323:     my ($udom,$unam,$ext) = @_;
 2324:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2325:     if (defined($env{'request.course.id'})) {
 2326:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 2327:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 2328:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 2329:             } else {
 2330:                 my ($result,$perm_reqd)=
 2331: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2332:                 if ($result eq 'ok') {
 2333:                     if (!($perm_reqd eq 'yes')) {
 2334:                         return(&retrievestudentphoto($udom,$unam,$ext));
 2335:                     }
 2336:                 }
 2337:             }
 2338:         }
 2339:     } else {
 2340:         my ($result,$perm_reqd) = 
 2341: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2342:         if ($result eq 'ok') {
 2343:             if (!($perm_reqd eq 'yes')) {
 2344:                 return(&retrievestudentphoto($udom,$unam,$ext));
 2345:             }
 2346:         }
 2347:     }
 2348:     return '/adm/lonKaputt/lonlogo_broken.gif';
 2349: }
 2350: 
 2351: sub retrievestudentphoto {
 2352:     my ($udom,$unam,$ext,$type) = @_;
 2353:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2354:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 2355:     if ($ret eq 'ok') {
 2356:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 2357:         if ($type eq 'thumbnail') {
 2358:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 2359:         }
 2360:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 2361:         return $tokenurl;
 2362:     } else {
 2363:         if ($type eq 'thumbnail') {
 2364:             return '/adm/lonKaputt/genericstudent_tn.gif';
 2365:         } else { 
 2366:             return '/adm/lonKaputt/lonlogo_broken.gif';
 2367:         }
 2368:     }
 2369: }
 2370: 
 2371: # -------------------------------------------------------------------- New chat
 2372: 
 2373: sub chatsend {
 2374:     my ($newentry,$anon,$group)=@_;
 2375:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 2376:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2377:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 2378:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 2379: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 2380: 		   &escape($newentry)).':'.$group,$chome);
 2381: }
 2382: 
 2383: # ------------------------------------------ Find current version of a resource
 2384: 
 2385: sub getversion {
 2386:     my $fname=&clutter(shift);
 2387:     unless ($fname=~/^\/res\//) { return -1; }
 2388:     return &currentversion(&filelocation('',$fname));
 2389: }
 2390: 
 2391: sub currentversion {
 2392:     my $fname=shift;
 2393:     my $author=$fname;
 2394:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2395:     my ($udom,$uname)=split(/\//,$author);
 2396:     my $home=&homeserver($uname,$udom);
 2397:     if ($home eq 'no_host') { 
 2398:         return -1; 
 2399:     }
 2400:     my $answer=&reply("currentversion:$fname",$home);
 2401:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 2402: 	return -1;
 2403:     }
 2404:     return $answer;
 2405: }
 2406: 
 2407: #
 2408: # Return special version number of resource if set by override, empty otherwise
 2409: #
 2410: sub usedversion {
 2411:     my $fname=shift;
 2412:     unless ($fname) { $fname=$env{'request.uri'}; }
 2413:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 2414:     if ($urlversion) { return $urlversion; }
 2415:     return '';
 2416: }
 2417: 
 2418: # ----------------------------- Subscribe to a resource, return URL if possible
 2419: 
 2420: sub subscribe {
 2421:     my $fname=shift;
 2422:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 2423:     $fname=~s/[\n\r]//g;
 2424:     my $author=$fname;
 2425:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2426:     my ($udom,$uname)=split(/\//,$author);
 2427:     my $home=homeserver($uname,$udom);
 2428:     if ($home eq 'no_host') {
 2429:         return 'not_found';
 2430:     }
 2431:     my $answer=reply("sub:$fname",$home);
 2432:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 2433: 	$answer.=' by '.$home;
 2434:     }
 2435:     return $answer;
 2436: }
 2437:     
 2438: # -------------------------------------------------------------- Replicate file
 2439: 
 2440: sub repcopy {
 2441:     my $filename=shift;
 2442:     $filename=~s/\/+/\//g;
 2443:     my $londocroot = $perlvar{'lonDocRoot'};
 2444:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 2445:     if ($filename=~m{^\Q$londocroot/lonUsers/\E}) { return 'ok'; }
 2446:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 2447: 	$filename=~m{^/*(uploaded|editupload)/}) {
 2448: 	return &repcopy_userfile($filename);
 2449:     }
 2450:     $filename=~s/[\n\r]//g;
 2451:     my $transname="$filename.in.transfer";
 2452: # FIXME: this should flock
 2453:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 2454:     my $remoteurl=subscribe($filename);
 2455:     if ($remoteurl =~ /^con_lost by/) {
 2456: 	   &logthis("Subscribe returned $remoteurl: $filename");
 2457:            return 'unavailable';
 2458:     } elsif ($remoteurl eq 'not_found') {
 2459: 	   #&logthis("Subscribe returned not_found: $filename");
 2460: 	   return 'not_found';
 2461:     } elsif ($remoteurl =~ /^rejected by/) {
 2462: 	   &logthis("Subscribe returned $remoteurl: $filename");
 2463:            return 'forbidden';
 2464:     } elsif ($remoteurl eq 'directory') {
 2465:            return 'ok';
 2466:     } else {
 2467:         my $author=$filename;
 2468:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2469:         my ($udom,$uname)=split(/\//,$author);
 2470:         my $home=homeserver($uname,$udom);
 2471:         unless ($home eq $perlvar{'lonHostID'}) {
 2472:            my @parts=split(/\//,$filename);
 2473:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 2474:            if ($path ne "$londocroot/res") {
 2475:                &logthis("Malconfiguration for replication: $filename");
 2476: 	       return 'bad_request';
 2477:            }
 2478:            my $count;
 2479:            for ($count=5;$count<$#parts;$count++) {
 2480:                $path.="/$parts[$count]";
 2481:                if ((-e $path)!=1) {
 2482: 		   mkdir($path,0777);
 2483:                }
 2484:            }
 2485:            my $ua=new LWP::UserAgent;
 2486:            my $request=new HTTP::Request('GET',"$remoteurl");
 2487:            my $response=$ua->request($request,$transname);
 2488:            if ($response->is_error()) {
 2489: 	       unlink($transname);
 2490:                my $message=$response->status_line;
 2491:                &logthis("<font color=\"blue\">WARNING:"
 2492:                        ." LWP get: $message: $filename</font>");
 2493:                return 'unavailable';
 2494:            } else {
 2495: 	       if ($remoteurl!~/\.meta$/) {
 2496:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 2497:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 2498:                   if ($mresponse->is_error()) {
 2499: 		      unlink($filename.'.meta');
 2500:                       &logthis(
 2501:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 2502:                   }
 2503: 	       }
 2504:                rename($transname,$filename);
 2505:                return 'ok';
 2506:            }
 2507:        }
 2508:     }
 2509: }
 2510: 
 2511: # ------------------------------------------------ Get server side include body
 2512: sub ssi_body {
 2513:     my ($filelink,%form)=@_;
 2514:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 2515:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 2516:     }
 2517:     my $output='';
 2518:     my $response;
 2519:     if ($filelink=~/^https?\:/) {
 2520:        ($output,$response)=&externalssi($filelink);
 2521:     } else {
 2522:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 2523:        $filelink .= 'inhibitmenu=yes';
 2524:        ($output,$response)=&ssi($filelink,%form);
 2525:     }
 2526:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 2527:     $output=~s/^.*?\<body[^\>]*\>//si;
 2528:     $output=~s/\<\/body\s*\>.*?$//si;
 2529:     if (wantarray) {
 2530:         return ($output, $response);
 2531:     } else {
 2532:         return $output;
 2533:     }
 2534: }
 2535: 
 2536: # --------------------------------------------------------- Server Side Include
 2537: 
 2538: sub absolute_url {
 2539:     my ($host_name) = @_;
 2540:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 2541:     if ($host_name eq '') {
 2542: 	$host_name = $ENV{'SERVER_NAME'};
 2543:     }
 2544:     return $protocol.$host_name;
 2545: }
 2546: 
 2547: #
 2548: #   Server side include.
 2549: # Parameters:
 2550: #  fn     Possibly encrypted resource name/id.
 2551: #  form   Hash that describes how the rendering should be done
 2552: #         and other things.
 2553: # Returns:
 2554: #   Scalar context: The content of the response.
 2555: #   Array context:  2 element list of the content and the full response object.
 2556: #     
 2557: sub ssi {
 2558: 
 2559:     my ($fn,%form)=@_;
 2560:     my $ua=new LWP::UserAgent;
 2561:     my $request;
 2562: 
 2563:     $form{'no_update_last_known'}=1;
 2564:     &Apache::lonenc::check_encrypt(\$fn);
 2565:     if (%form) {
 2566:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 2567:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
 2568:     } else {
 2569:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 2570:     }
 2571: 
 2572:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 2573:     my $response=$ua->request($request);
 2574: 
 2575:     if (wantarray) {
 2576: 	return ($response->content, $response);
 2577:     } else {
 2578: 	return $response->content;
 2579:     }
 2580: }
 2581: 
 2582: sub externalssi {
 2583:     my ($url)=@_;
 2584:     my $ua=new LWP::UserAgent;
 2585:     my $request=new HTTP::Request('GET',$url);
 2586:     my $response=$ua->request($request);
 2587:     if (wantarray) {
 2588:         return ($response->content, $response);
 2589:     } else {
 2590:         return $response->content;
 2591:     }
 2592: }
 2593: 
 2594: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 2595: 
 2596: sub allowuploaded {
 2597:     my ($srcurl,$url)=@_;
 2598:     $url=&clutter(&declutter($url));
 2599:     my $dir=$url;
 2600:     $dir=~s/\/[^\/]+$//;
 2601:     my %httpref=();
 2602:     my $httpurl=&hreflocation('',$url);
 2603:     $httpref{'httpref.'.$httpurl}=$srcurl;
 2604:     &Apache::lonnet::appenv(\%httpref);
 2605: }
 2606: 
 2607: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 2608: # input: action, courseID, current domain, intended
 2609: #        path to file, source of file, instruction to parse file for objects,
 2610: #        ref to hash for embedded objects,
 2611: #        ref to hash for codebase of java objects.
 2612: #        reference to scalar to accommodate mime type determined
 2613: #          from File::MMagic if $parser = parse.
 2614: #
 2615: # output: url to file (if action was uploaddoc), 
 2616: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 2617: #
 2618: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 2619: # course.
 2620: #
 2621: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2622: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 2623: #          course's home server.
 2624: #
 2625: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 2626: #          be copied from $source (current location) to 
 2627: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2628: #         and will then be copied to
 2629: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 2630: #         course's home server.
 2631: #
 2632: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2633: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 2634: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2635: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 2636: #         in course's home server.
 2637: #
 2638: 
 2639: sub process_coursefile {
 2640:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 2641:         $mimetype)=@_;
 2642:     my $fetchresult;
 2643:     my $home=&homeserver($docuname,$docudom);
 2644:     if ($action eq 'propagate') {
 2645:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2646: 			     $home);
 2647:     } else {
 2648:         my $fpath = '';
 2649:         my $fname = $file;
 2650:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 2651:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 2652:         my $filepath = &build_filepath($fpath);
 2653:         if ($action eq 'copy') {
 2654:             if ($source eq '') {
 2655:                 $fetchresult = 'no source file';
 2656:                 return $fetchresult;
 2657:             } else {
 2658:                 my $destination = $filepath.'/'.$fname;
 2659:                 rename($source,$destination);
 2660:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2661:                                  $home);
 2662:             }
 2663:         } elsif ($action eq 'uploaddoc') {
 2664:             open(my $fh,'>'.$filepath.'/'.$fname);
 2665:             print $fh $env{'form.'.$source};
 2666:             close($fh);
 2667:             if ($parser eq 'parse') {
 2668:                 my $mm = new File::MMagic;
 2669:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 2670:                 if ($type eq 'text/html') {
 2671:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 2672:                     unless ($parse_result eq 'ok') {
 2673:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 2674:                     }
 2675:                 }
 2676:                 if (ref($mimetype)) {
 2677:                     $$mimetype = $type;
 2678:                 } 
 2679:             }
 2680:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2681:                                  $home);
 2682:             if ($fetchresult eq 'ok') {
 2683:                 return '/uploaded/'.$fpath.'/'.$fname;
 2684:             } else {
 2685:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2686:                         ' to host '.$home.': '.$fetchresult);
 2687:                 return '/adm/notfound.html';
 2688:             }
 2689:         }
 2690:     }
 2691:     unless ( $fetchresult eq 'ok') {
 2692:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2693:              ' to host '.$home.': '.$fetchresult);
 2694:     }
 2695:     return $fetchresult;
 2696: }
 2697: 
 2698: sub build_filepath {
 2699:     my ($fpath) = @_;
 2700:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 2701:     unless ($fpath eq '') {
 2702:         my @parts=split('/',$fpath);
 2703:         foreach my $part (@parts) {
 2704:             $filepath.= '/'.$part;
 2705:             if ((-e $filepath)!=1) {
 2706:                 mkdir($filepath,0777);
 2707:             }
 2708:         }
 2709:     }
 2710:     return $filepath;
 2711: }
 2712: 
 2713: sub store_edited_file {
 2714:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 2715:     my $file = $primary_url;
 2716:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 2717:     my $fpath = '';
 2718:     my $fname = $file;
 2719:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 2720:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 2721:     my $filepath = &build_filepath($fpath);
 2722:     open(my $fh,'>'.$filepath.'/'.$fname);
 2723:     print $fh $content;
 2724:     close($fh);
 2725:     my $home=&homeserver($docuname,$docudom);
 2726:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2727: 			  $home);
 2728:     if ($$fetchresult eq 'ok') {
 2729:         return '/uploaded/'.$fpath.'/'.$fname;
 2730:     } else {
 2731:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2732: 		 ' to host '.$home.': '.$$fetchresult);
 2733:         return '/adm/notfound.html';
 2734:     }
 2735: }
 2736: 
 2737: sub clean_filename {
 2738:     my ($fname,$args)=@_;
 2739: # Replace Windows backslashes by forward slashes
 2740:     $fname=~s/\\/\//g;
 2741:     if (!$args->{'keep_path'}) {
 2742:         # Get rid of everything but the actual filename
 2743: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 2744:     }
 2745: # Replace spaces by underscores
 2746:     $fname=~s/\s+/\_/g;
 2747: # Replace all other weird characters by nothing
 2748:     $fname=~s{[^/\w\.\-]}{}g;
 2749: # Replace all .\d. sequences with _\d. so they no longer look like version
 2750: # numbers
 2751:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 2752:     return $fname;
 2753: }
 2754: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 2755: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 2756: # image with the same aspect ratio as the original, but with dimensions which do 
 2757: # not exceed $resizewidth and $resizeheight.
 2758:  
 2759: sub resizeImage {
 2760:     my ($img_path,$resizewidth,$resizeheight) = @_;
 2761:     my $ima = Image::Magick->new;
 2762:     my $resized;
 2763:     if (-e $img_path) {
 2764:         $ima->Read($img_path);
 2765:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 2766:             my $width = $ima->Get('width');
 2767:             my $height = $ima->Get('height');
 2768:             if ($width > $resizewidth) {
 2769: 	        my $factor = $width/$resizewidth;
 2770:                 my $newheight = $height/$factor;
 2771:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 2772:                 $resized = 1;
 2773:             }
 2774:         }
 2775:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 2776:             my $width = $ima->Get('width');
 2777:             my $height = $ima->Get('height');
 2778:             if ($height > $resizeheight) {
 2779:                 my $factor = $height/$resizeheight;
 2780:                 my $newwidth = $width/$factor;
 2781:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 2782:                 $resized = 1;
 2783:             }
 2784:         }
 2785:         if ($resized) {
 2786:             $ima->Write($img_path);
 2787:         }
 2788:     }
 2789:     return;
 2790: }
 2791: 
 2792: # --------------- Take an uploaded file and put it into the userfiles directory
 2793: # input: $formname - the contents of the file are in $env{"form.$formname"}
 2794: #                    the desired filename is in $env{"form.$formname.filename"}
 2795: #        $context - possible values: coursedoc, existingfile, overwrite, 
 2796: #                                    canceloverwrite, or ''. 
 2797: #                   if 'coursedoc': upload to the current course
 2798: #                   if 'existingfile': write file to tmp/overwrites directory 
 2799: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 2800: #                   $context is passed as argument to &finishuserfileupload
 2801: #        $subdir - directory in userfile to store the file into
 2802: #        $parser - instruction to parse file for objects ($parser = parse)    
 2803: #        $allfiles - reference to hash for embedded objects
 2804: #        $codebase - reference to hash for codebase of java objects
 2805: #        $desuname - username for permanent storage of uploaded file
 2806: #        $dsetudom - domain for permanaent storage of uploaded file
 2807: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 2808: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 2809: #        $resizewidth - width (pixels) to which to resize uploaded image
 2810: #        $resizeheight - height (pixels) to which to resize uploaded image
 2811: #        $mimetype - reference to scalar to accommodate mime type determined
 2812: #                    from File::MMagic.
 2813: # 
 2814: # output: url of file in userspace, or error: <message> 
 2815: #             or /adm/notfound.html if failure to upload occurse
 2816: 
 2817: sub userfileupload {
 2818:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 2819:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 2820:     if (!defined($subdir)) { $subdir='unknown'; }
 2821:     my $fname=$env{'form.'.$formname.'.filename'};
 2822:     $fname=&clean_filename($fname);
 2823:     # See if there is anything left
 2824:     unless ($fname) { return 'error: no uploaded file'; }
 2825:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 2826:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 2827:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 2828:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 2829:         my $now = time;
 2830:         my $filepath;
 2831:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 2832:              $filepath = 'tmp/helprequests/'.$now;
 2833:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 2834:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 2835:                          '_'.$env{'user.domain'}.'/pending';
 2836:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 2837:             my ($docuname,$docudom);
 2838:             if ($destudom) {
 2839:                 $docudom = $destudom;
 2840:             } else {
 2841:                 $docudom = $env{'user.domain'};
 2842:             }
 2843:             if ($destuname) {
 2844:                 $docuname = $destuname;
 2845:             } else {
 2846:                 $docuname = $env{'user.name'};
 2847:             }
 2848:             if (exists($env{'form.group'})) {
 2849:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2850:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2851:             }
 2852:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 2853:             if ($context eq 'canceloverwrite') {
 2854:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 2855:                 if (-e  $tempfile) {
 2856:                     my @info = stat($tempfile);
 2857:                     if ($info[9] eq $env{'form.timestamp'}) {
 2858:                         unlink($tempfile);
 2859:                     }
 2860:                 }
 2861:                 return;
 2862:             }
 2863:         }
 2864:         # Create the directory if not present
 2865:         my @parts=split(/\//,$filepath);
 2866:         my $fullpath = $perlvar{'lonDaemons'};
 2867:         for (my $i=0;$i<@parts;$i++) {
 2868:             $fullpath .= '/'.$parts[$i];
 2869:             if ((-e $fullpath)!=1) {
 2870:                 mkdir($fullpath,0777);
 2871:             }
 2872:         }
 2873:         open(my $fh,'>'.$fullpath.'/'.$fname);
 2874:         print $fh $env{'form.'.$formname};
 2875:         close($fh);
 2876:         if ($context eq 'existingfile') {
 2877:             my @info = stat($fullpath.'/'.$fname);
 2878:             return ($fullpath.'/'.$fname,$info[9]);
 2879:         } else {
 2880:             return $fullpath.'/'.$fname;
 2881:         }
 2882:     }
 2883:     if ($subdir eq 'scantron') {
 2884:         $fname = 'scantron_orig_'.$fname;
 2885:     } else {
 2886:         $fname="$subdir/$fname";
 2887:     }
 2888:     if ($context eq 'coursedoc') {
 2889: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2890: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2891:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 2892:             return &finishuserfileupload($docuname,$docudom,
 2893: 					 $formname,$fname,$parser,$allfiles,
 2894: 					 $codebase,$thumbwidth,$thumbheight,
 2895:                                          $resizewidth,$resizeheight,$context,$mimetype);
 2896:         } else {
 2897:             $fname=$env{'form.folder'}.'/'.$fname;
 2898:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 2899: 				       $fname,$formname,$parser,
 2900: 				       $allfiles,$codebase,$mimetype);
 2901:         }
 2902:     } elsif (defined($destuname)) {
 2903:         my $docuname=$destuname;
 2904:         my $docudom=$destudom;
 2905: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 2906: 				     $parser,$allfiles,$codebase,
 2907:                                      $thumbwidth,$thumbheight,
 2908:                                      $resizewidth,$resizeheight,$context,$mimetype);
 2909:     } else {
 2910:         my $docuname=$env{'user.name'};
 2911:         my $docudom=$env{'user.domain'};
 2912:         if (exists($env{'form.group'})) {
 2913:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2914:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2915:         }
 2916: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 2917: 				     $parser,$allfiles,$codebase,
 2918:                                      $thumbwidth,$thumbheight,
 2919:                                      $resizewidth,$resizeheight,$context,$mimetype);
 2920:     }
 2921: }
 2922: 
 2923: sub finishuserfileupload {
 2924:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 2925:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 2926:     my $path=$docudom.'/'.$docuname.'/';
 2927:     my $filepath=$perlvar{'lonDocRoot'};
 2928:   
 2929:     my ($fnamepath,$file,$fetchthumb);
 2930:     $file=$fname;
 2931:     if ($fname=~m|/|) {
 2932:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 2933: 	$path.=$fnamepath.'/';
 2934:     }
 2935:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 2936:     my $count;
 2937:     for ($count=4;$count<=$#parts;$count++) {
 2938:         $filepath.="/$parts[$count]";
 2939:         if ((-e $filepath)!=1) {
 2940: 	    mkdir($filepath,0777);
 2941:         }
 2942:     }
 2943: 
 2944: # Save the file
 2945:     {
 2946: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 2947: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 2948: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 2949: 	    return '/adm/notfound.html';
 2950: 	}
 2951:         if ($context eq 'overwrite') {
 2952:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 2953:             my $target = $filepath.'/'.$file;
 2954:             if (-e $source) {
 2955:                 my @info = stat($source);
 2956:                 if ($info[9] eq $env{'form.timestamp'}) {   
 2957:                     unless (&File::Copy::move($source,$target)) {
 2958:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 2959:                         return "Moving from $source failed";
 2960:                     }
 2961:                 } else {
 2962:                     return "Temporary file: $source had unexpected date/time for last modification";
 2963:                 }
 2964:             } else {
 2965:                 return "Temporary file: $source missing";
 2966:             }
 2967:         } elsif (!print FH ($env{'form.'.$formname})) {
 2968: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 2969: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 2970: 	    return '/adm/notfound.html';
 2971: 	}
 2972: 	close(FH);
 2973:         if ($resizewidth && $resizeheight) {
 2974:             my $mm = new File::MMagic;
 2975:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 2976:             if ($mime_type =~ m{^image/}) {
 2977: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 2978:             }  
 2979: 	}
 2980:     }
 2981:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 2982:         if (ref($mimetype)) {
 2983:             if ($$mimetype eq '') {
 2984:                 my $mm = new File::MMagic;
 2985:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 2986:                 $$mimetype = $type;
 2987:             }
 2988:         }
 2989:     }
 2990:     if ($parser eq 'parse') {
 2991:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 2992:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 2993:                                                        $allfiles,$codebase);
 2994:             unless ($parse_result eq 'ok') {
 2995:                 &logthis('Failed to parse '.$filepath.$file.
 2996: 	   	         ' for embedded media: '.$parse_result); 
 2997:             }
 2998:         }
 2999:     }
 3000:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 3001:         my $input = $filepath.'/'.$file;
 3002:         my $output = $filepath.'/'.'tn-'.$file;
 3003:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 3004:         system("convert -sample $thumbsize $input $output");
 3005:         if (-e $filepath.'/'.'tn-'.$file) {
 3006:             $fetchthumb  = 1; 
 3007:         }
 3008:     }
 3009:  
 3010: # Notify homeserver to grep it
 3011: #
 3012:     my $docuhome=&homeserver($docuname,$docudom);	
 3013:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 3014:     if ($fetchresult eq 'ok') {
 3015:         if ($fetchthumb) {
 3016:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 3017:             if ($thumbresult ne 'ok') {
 3018:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 3019:                          $docuhome.': '.$thumbresult);
 3020:             }
 3021:         }
 3022: #
 3023: # Return the URL to it
 3024:         return '/uploaded/'.$path.$file;
 3025:     } else {
 3026:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 3027: 		 ': '.$fetchresult);
 3028:         return '/adm/notfound.html';
 3029:     }
 3030: }
 3031: 
 3032: sub extract_embedded_items {
 3033:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 3034:     my @state = ();
 3035:     my %javafiles = (
 3036:                       codebase => '',
 3037:                       code => '',
 3038:                       archive => ''
 3039:                     );
 3040:     my %mediafiles = (
 3041:                       src => '',
 3042:                       movie => '',
 3043:                      );
 3044:     my $p;
 3045:     if ($content) {
 3046:         $p = HTML::LCParser->new($content);
 3047:     } else {
 3048:         $p = HTML::LCParser->new($fullpath);
 3049:     }
 3050:     while (my $t=$p->get_token()) {
 3051: 	if ($t->[0] eq 'S') {
 3052: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 3053: 	    push(@state, $tagname);
 3054:             if (lc($tagname) eq 'allow') {
 3055:                 &add_filetype($allfiles,$attr->{'src'},'src');
 3056:             }
 3057: 	    if (lc($tagname) eq 'img') {
 3058: 		&add_filetype($allfiles,$attr->{'src'},'src');
 3059: 	    }
 3060: 	    if (lc($tagname) eq 'a') {
 3061: 		&add_filetype($allfiles,$attr->{'href'},'href');
 3062: 	    }
 3063:             if (lc($tagname) eq 'script') {
 3064:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 3065:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 3066:                 } else {
 3067:                     &add_filetype($allfiles,$attr->{'src'},'src');
 3068:                 }
 3069:             }
 3070:             if (lc($tagname) eq 'link') {
 3071:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 3072:                     &add_filetype($allfiles,$attr->{'href'},'href');
 3073:                 }
 3074:             }
 3075: 	    if (lc($tagname) eq 'object' ||
 3076: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 3077: 		foreach my $item (keys(%javafiles)) {
 3078: 		    $javafiles{$item} = '';
 3079: 		}
 3080: 	    }
 3081: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 3082: 		my $name = lc($attr->{'name'});
 3083: 		foreach my $item (keys(%javafiles)) {
 3084: 		    if ($name eq $item) {
 3085: 			$javafiles{$item} = $attr->{'value'};
 3086: 			last;
 3087: 		    }
 3088: 		}
 3089: 		foreach my $item (keys(%mediafiles)) {
 3090: 		    if ($name eq $item) {
 3091: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
 3092: 			last;
 3093: 		    }
 3094: 		}
 3095: 	    }
 3096: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 3097: 		foreach my $item (keys(%javafiles)) {
 3098: 		    if ($attr->{$item}) {
 3099: 			$javafiles{$item} = $attr->{$item};
 3100: 			last;
 3101: 		    }
 3102: 		}
 3103: 		foreach my $item (keys(%mediafiles)) {
 3104: 		    if ($attr->{$item}) {
 3105: 			&add_filetype($allfiles,$attr->{$item},$item);
 3106: 			last;
 3107: 		    }
 3108: 		}
 3109: 	    }
 3110: 	} elsif ($t->[0] eq 'E') {
 3111: 	    my ($tagname) = ($t->[1]);
 3112: 	    if ($javafiles{'codebase'} ne '') {
 3113: 		$javafiles{'codebase'} .= '/';
 3114: 	    }  
 3115: 	    if (lc($tagname) eq 'applet' ||
 3116: 		lc($tagname) eq 'object' ||
 3117: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 3118: 		) {
 3119: 		foreach my $item (keys(%javafiles)) {
 3120: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 3121: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 3122: 			&add_filetype($allfiles,$file,$item);
 3123: 		    }
 3124: 		}
 3125: 	    } 
 3126: 	    pop @state;
 3127: 	}
 3128:     }
 3129:     return 'ok';
 3130: }
 3131: 
 3132: sub add_filetype {
 3133:     my ($allfiles,$file,$type)=@_;
 3134:     if (exists($allfiles->{$file})) {
 3135: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 3136: 	    push(@{$allfiles->{$file}}, &escape($type));
 3137: 	}
 3138:     } else {
 3139: 	@{$allfiles->{$file}} = (&escape($type));
 3140:     }
 3141: }
 3142: 
 3143: sub removeuploadedurl {
 3144:     my ($url)=@_;	
 3145:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 3146:     return &removeuserfile($uname,$udom,$fname);
 3147: }
 3148: 
 3149: sub removeuserfile {
 3150:     my ($docuname,$docudom,$fname)=@_;
 3151:     my $home=&homeserver($docuname,$docudom);    
 3152:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 3153:     if ($result eq 'ok') {	
 3154:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 3155:             my $metafile = $fname.'.meta';
 3156:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 3157: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 3158:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 3159:             my $sqlresult = 
 3160:                 &update_portfolio_table($docuname,$docudom,$file,
 3161:                                         'portfolio_metadata',$group,
 3162:                                         'delete');
 3163:         }
 3164:     }
 3165:     return $result;
 3166: }
 3167: 
 3168: sub mkdiruserfile {
 3169:     my ($docuname,$docudom,$dir)=@_;
 3170:     my $home=&homeserver($docuname,$docudom);
 3171:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 3172: }
 3173: 
 3174: sub renameuserfile {
 3175:     my ($docuname,$docudom,$old,$new)=@_;
 3176:     my $home=&homeserver($docuname,$docudom);
 3177:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 3178:                         &escape("$old").':'.&escape("$new"),$home);
 3179:     if ($result eq 'ok') {
 3180:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 3181:             my $oldmeta = $old.'.meta';
 3182:             my $newmeta = $new.'.meta';
 3183:             my $metaresult = 
 3184:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 3185: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 3186:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 3187:             my $sqlresult = 
 3188:                 &update_portfolio_table($docuname,$docudom,$file,
 3189:                                         'portfolio_metadata',$group,
 3190:                                         'delete');
 3191:         }
 3192:     }
 3193:     return $result;
 3194: }
 3195: 
 3196: # ------------------------------------------------------------------------- Log
 3197: 
 3198: sub log {
 3199:     my ($dom,$nam,$hom,$what)=@_;
 3200:     return critical("log:$dom:$nam:$what",$hom);
 3201: }
 3202: 
 3203: # ------------------------------------------------------------------ Course Log
 3204: #
 3205: # This routine flushes several buffers of non-mission-critical nature
 3206: #
 3207: 
 3208: sub flushcourselogs {
 3209:     &logthis('Flushing log buffers');
 3210: #
 3211: # course logs
 3212: # This is a log of all transactions in a course, which can be used
 3213: # for data mining purposes
 3214: #
 3215: # It also collects the courseid database, which lists last transaction
 3216: # times and course titles for all courseids
 3217: #
 3218:     my %courseidbuffer=();
 3219:     foreach my $crsid (keys(%courselogs)) {
 3220:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 3221: 		          &escape($courselogs{$crsid}),
 3222: 		          $coursehombuf{$crsid}) eq 'ok') {
 3223: 	    delete $courselogs{$crsid};
 3224:         } else {
 3225:             &logthis('Failed to flush log buffer for '.$crsid);
 3226:             if (length($courselogs{$crsid})>40000) {
 3227:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 3228:                         " exceeded maximum size, deleting.</font>");
 3229:                delete $courselogs{$crsid};
 3230:             }
 3231:         }
 3232:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 3233:             'description' => $coursedescrbuf{$crsid},
 3234:             'inst_code'    => $courseinstcodebuf{$crsid},
 3235:             'type'        => $coursetypebuf{$crsid},
 3236:             'owner'       => $courseownerbuf{$crsid},
 3237:         };
 3238:     }
 3239: #
 3240: # Write course id database (reverse lookup) to homeserver of courses 
 3241: # Is used in pickcourse
 3242: #
 3243:     foreach my $crs_home (keys(%courseidbuffer)) {
 3244:         my $response = &courseidput(&host_domain($crs_home),
 3245:                                     $courseidbuffer{$crs_home},
 3246:                                     $crs_home,'timeonly');
 3247:     }
 3248: #
 3249: # File accesses
 3250: # Writes to the dynamic metadata of resources to get hit counts, etc.
 3251: #
 3252:     foreach my $entry (keys(%accesshash)) {
 3253:         if ($entry =~ /___count$/) {
 3254:             my ($dom,$name);
 3255:             ($dom,$name,undef)=
 3256: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 3257:             if (! defined($dom) || $dom eq '' || 
 3258:                 ! defined($name) || $name eq '') {
 3259:                 my $cid = $env{'request.course.id'};
 3260:                 $dom  = $env{'request.'.$cid.'.domain'};
 3261:                 $name = $env{'request.'.$cid.'.num'};
 3262:             }
 3263:             my $value = $accesshash{$entry};
 3264:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 3265:             my %temphash=($url => $value);
 3266:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 3267:             if ($result eq 'ok') {
 3268:                 delete $accesshash{$entry};
 3269:             } elsif ($result eq 'unknown_cmd') {
 3270:                 # Target server has old code running on it.
 3271:                 my %temphash=($entry => $value);
 3272:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 3273:                     delete $accesshash{$entry};
 3274:                 }
 3275:             }
 3276:         } else {
 3277:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 3278:             my %temphash=($entry => $accesshash{$entry});
 3279:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 3280:                 delete $accesshash{$entry};
 3281:             }
 3282:         }
 3283:     }
 3284: #
 3285: # Roles
 3286: # Reverse lookup of user roles for course faculty/staff and co-authorship
 3287: #
 3288:     foreach my $entry (keys(%userrolehash)) {
 3289:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 3290: 	    split(/\:/,$entry);
 3291:         if (&Apache::lonnet::put('nohist_userroles',
 3292:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 3293:                 $rudom,$runame) eq 'ok') {
 3294: 	    delete $userrolehash{$entry};
 3295:         }
 3296:     }
 3297: #
 3298: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 3299: #
 3300:     my %domrolebuffer = ();
 3301:     foreach my $entry (keys(%domainrolehash)) {
 3302:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 3303:         if ($domrolebuffer{$rudom}) {
 3304:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 3305:                       '='.&escape($domainrolehash{$entry});
 3306:         } else {
 3307:             $domrolebuffer{$rudom}.=&escape($entry).
 3308:                       '='.&escape($domainrolehash{$entry});
 3309:         }
 3310:         delete $domainrolehash{$entry};
 3311:     }
 3312:     foreach my $dom (keys(%domrolebuffer)) {
 3313: 	my %servers = &get_servers($dom,'library');
 3314: 	foreach my $tryserver (keys(%servers)) {
 3315: 	    unless (&reply('domroleput:'.$dom.':'.
 3316: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 3317: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 3318: 	    }
 3319:         }
 3320:     }
 3321:     $dumpcount++;
 3322: }
 3323: 
 3324: sub courselog {
 3325:     my $what=shift;
 3326:     $what=time.':'.$what;
 3327:     unless ($env{'request.course.id'}) { return ''; }
 3328:     $coursedombuf{$env{'request.course.id'}}=
 3329:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 3330:     $coursenumbuf{$env{'request.course.id'}}=
 3331:        $env{'course.'.$env{'request.course.id'}.'.num'};
 3332:     $coursehombuf{$env{'request.course.id'}}=
 3333:        $env{'course.'.$env{'request.course.id'}.'.home'};
 3334:     $coursedescrbuf{$env{'request.course.id'}}=
 3335:        $env{'course.'.$env{'request.course.id'}.'.description'};
 3336:     $courseinstcodebuf{$env{'request.course.id'}}=
 3337:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 3338:     $courseownerbuf{$env{'request.course.id'}}=
 3339:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 3340:     $coursetypebuf{$env{'request.course.id'}}=
 3341:        $env{'course.'.$env{'request.course.id'}.'.type'};
 3342:     if (defined $courselogs{$env{'request.course.id'}}) {
 3343: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 3344:     } else {
 3345: 	$courselogs{$env{'request.course.id'}}.=$what;
 3346:     }
 3347:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 3348: 	&flushcourselogs();
 3349:     }
 3350: }
 3351: 
 3352: sub courseacclog {
 3353:     my $fnsymb=shift;
 3354:     unless ($env{'request.course.id'}) { return ''; }
 3355:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 3356:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 3357:         $what.=':POST';
 3358:         # FIXME: Probably ought to escape things....
 3359: 	foreach my $key (keys(%env)) {
 3360:             if ($key=~/^form\.(.*)/) {
 3361:                 my $formitem = $1;
 3362:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 3363:                     $what.=':'.$formitem.'='.$env{$key};
 3364:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 3365:                     $what.=':'.$formitem.'='.$env{$key};
 3366:                 }
 3367:             }
 3368:         }
 3369:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 3370:         # FIXME: We should not be depending on a form parameter that someone
 3371:         # editing lonsearchcat.pm might change in the future.
 3372:         if ($env{'form.phase'} eq 'course_search') {
 3373:             $what.= ':POST';
 3374:             # FIXME: Probably ought to escape things....
 3375:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 3376:                                  'crsdiscuss') {
 3377:                 $what.=':'.$element.'='.$env{'form.'.$element};
 3378:             }
 3379:         }
 3380:     }
 3381:     &courselog($what);
 3382: }
 3383: 
 3384: sub countacc {
 3385:     my $url=&declutter(shift);
 3386:     return if (! defined($url) || $url eq '');
 3387:     unless ($env{'request.course.id'}) { return ''; }
 3388:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 3389:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 3390:     $accesshash{$key}++;
 3391: }
 3392: 
 3393: sub linklog {
 3394:     my ($from,$to)=@_;
 3395:     $from=&declutter($from);
 3396:     $to=&declutter($to);
 3397:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 3398:     $accesshash{$to.'___'.$from.'___goto'}=1;
 3399: }
 3400:   
 3401: sub userrolelog {
 3402:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 3403:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
 3404:         ($trole=~/^in/) || ($trole=~/^cc/) ||
 3405:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
 3406:         ($trole=~/^ta/) || ($trole=~/^co/)) {
 3407:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 3408:        $userrolehash
 3409:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 3410:                     =$tend.':'.$tstart;
 3411:     }
 3412:     if (($env{'request.role'} =~ /dc\./) &&
 3413: 	(($trole=~/^au/) || ($trole=~/^in/) ||
 3414: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
 3415: 	 ($trole=~/^cr/) || ($trole=~/^ta/) ||
 3416:          ($trole=~/^co/))) {
 3417:        $userrolehash
 3418:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 3419:                     =$tend.':'.$tstart;
 3420:     }
 3421:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
 3422:         ($trole=~/^li/) || ($trole=~/^li/) ||
 3423:         ($trole=~/^au/) || ($trole=~/^dg/) ||
 3424:         ($trole=~/^sc/)) {
 3425:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 3426:        $domainrolehash
 3427:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 3428:                     = $tend.':'.$tstart;
 3429:     }
 3430: }
 3431: 
 3432: sub courserolelog {
 3433:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 3434:     if (($trole eq 'cc') || ($trole eq 'in') ||
 3435:         ($trole eq 'ep') || ($trole eq 'ad') ||
 3436:         ($trole eq 'ta') || ($trole eq 'st') ||
 3437:         ($trole=~/^cr/) || ($trole eq 'gr') ||
 3438:         ($trole eq 'co')) {
 3439:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 3440:             my $cdom = $1;
 3441:             my $cnum = $2;
 3442:             my $sec = $3;
 3443:             my $namespace = 'rolelog';
 3444:             my %storehash = (
 3445:                                role    => $trole,
 3446:                                start   => $tstart,
 3447:                                end     => $tend,
 3448:                                selfenroll => $selfenroll,
 3449:                                context    => $context,
 3450:                             );
 3451:             if ($trole eq 'gr') {
 3452:                 $namespace = 'groupslog';
 3453:                 $storehash{'group'} = $sec;
 3454:             } else {
 3455:                 $storehash{'section'} = $sec;
 3456:             }
 3457:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
 3458:             if (($trole ne 'st') || ($sec ne '')) {
 3459:                 &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 3460:             }
 3461:         }
 3462:     }
 3463:     return;
 3464: }
 3465: 
 3466: sub get_course_adv_roles {
 3467:     my ($cid,$codes) = @_;
 3468:     $cid=$env{'request.course.id'} unless (defined($cid));
 3469:     my %coursehash=&coursedescription($cid);
 3470:     my $crstype = &Apache::loncommon::course_type($cid);
 3471:     my %nothide=();
 3472:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3473:         if ($user !~ /:/) {
 3474: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 3475:         } else {
 3476:             $nothide{$user}=1;
 3477:         }
 3478:     }
 3479:     my %returnhash=();
 3480:     my %dumphash=
 3481:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 3482:     my $now=time;
 3483:     my %privileged;
 3484:     foreach my $entry (keys(%dumphash)) {
 3485: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 3486:         if (($tstart) && ($tstart<0)) { next; }
 3487:         if (($tend) && ($tend<$now)) { next; }
 3488:         if (($tstart) && ($now<$tstart)) { next; }
 3489:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 3490: 	if ($username eq '' || $domain eq '') { next; }
 3491:         unless (ref($privileged{$domain}) eq 'HASH') {
 3492:             my %dompersonnel =
 3493:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
 3494:             $privileged{$domain} = {};
 3495:             foreach my $server (keys(%dompersonnel)) {
 3496:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 3497:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
 3498:                         my ($trole,$uname,$udom) = split(/:/,$user);
 3499:                         $privileged{$udom}{$uname} = 1;
 3500:                     }
 3501:                 }
 3502:             }
 3503:         }
 3504:         if ((exists($privileged{$domain}{$username})) && 
 3505:             (!$nothide{$username.':'.$domain})) { next; }
 3506: 	if ($role eq 'cr') { next; }
 3507:         if ($codes) {
 3508:             if ($section) { $role .= ':'.$section; }
 3509:             if ($returnhash{$role}) {
 3510:                 $returnhash{$role}.=','.$username.':'.$domain;
 3511:             } else {
 3512:                 $returnhash{$role}=$username.':'.$domain;
 3513:             }
 3514:         } else {
 3515:             my $key=&plaintext($role,$crstype);
 3516:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 3517:             if ($returnhash{$key}) {
 3518: 	        $returnhash{$key}.=','.$username.':'.$domain;
 3519:             } else {
 3520:                 $returnhash{$key}=$username.':'.$domain;
 3521:             }
 3522:         }
 3523:     }
 3524:     return %returnhash;
 3525: }
 3526: 
 3527: sub get_my_roles {
 3528:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 3529:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 3530:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 3531:     my (%dumphash,%nothide);
 3532:     if ($context eq 'userroles') {
 3533:         my $extra = &freeze_escape({'skipcheck' => 1});
 3534:         %dumphash = &dump('roles',$udom,$uname,'.',undef,$extra);
 3535:     } else {
 3536:         %dumphash=
 3537:             &dump('nohist_userroles',$udom,$uname);
 3538:         if ($hidepriv) {
 3539:             my %coursehash=&coursedescription($udom.'_'.$uname);
 3540:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3541:                 if ($user !~ /:/) {
 3542:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 3543:                 } else {
 3544:                     $nothide{$user} = 1;
 3545:                 }
 3546:             }
 3547:         }
 3548:     }
 3549:     my %returnhash=();
 3550:     my $now=time;
 3551:     my %privileged;
 3552:     foreach my $entry (keys(%dumphash)) {
 3553:         my ($role,$tend,$tstart);
 3554:         if ($context eq 'userroles') {
 3555:             next if ($entry =~ /^rolesdef/);
 3556: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 3557:         } else {
 3558:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 3559:         }
 3560:         if (($tstart) && ($tstart<0)) { next; }
 3561:         my $status = 'active';
 3562:         if (($tend) && ($tend<=$now)) {
 3563:             $status = 'previous';
 3564:         } 
 3565:         if (($tstart) && ($now<$tstart)) {
 3566:             $status = 'future';
 3567:         }
 3568:         if (ref($types) eq 'ARRAY') {
 3569:             if (!grep(/^\Q$status\E$/,@{$types})) {
 3570:                 next;
 3571:             } 
 3572:         } else {
 3573:             if ($status ne 'active') {
 3574:                 next;
 3575:             }
 3576:         }
 3577:         my ($rolecode,$username,$domain,$section,$area);
 3578:         if ($context eq 'userroles') {
 3579:             ($area,$rolecode) = split(/_/,$entry);
 3580:             (undef,$domain,$username,$section) = split(/\//,$area);
 3581:         } else {
 3582:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 3583:         }
 3584:         if (ref($roledoms) eq 'ARRAY') {
 3585:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 3586:                 next;
 3587:             }
 3588:         }
 3589:         if (ref($roles) eq 'ARRAY') {
 3590:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 3591:                 if ($role =~ /^cr\//) {
 3592:                     if (!grep(/^cr$/,@{$roles})) {
 3593:                         next;
 3594:                     }
 3595:                 } elsif ($role =~ /^gr\//) {
 3596:                     if (!grep(/^gr$/,@{$roles})) {
 3597:                         next;
 3598:                     }
 3599:                 } else {
 3600:                     next;
 3601:                 }
 3602:             }
 3603:         }
 3604:         if ($hidepriv) {
 3605:             if ($context eq 'userroles') {
 3606:                 if ((&privileged($username,$domain)) &&
 3607:                     (!$nothide{$username.':'.$domain})) {
 3608:                     next;
 3609:                 }
 3610:             } else {
 3611:                 unless (ref($privileged{$domain}) eq 'HASH') {
 3612:                     my %dompersonnel =
 3613:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
 3614:                     $privileged{$domain} = {};
 3615:                     if (keys(%dompersonnel)) {
 3616:                         foreach my $server (keys(%dompersonnel)) {
 3617:                             if (ref($dompersonnel{$server}) eq 'HASH') {
 3618:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
 3619:                                     my ($trole,$uname,$udom) = split(/:/,$user);
 3620:                                     $privileged{$udom}{$uname} = $trole;
 3621:                                 }
 3622:                             }
 3623:                         }
 3624:                     }
 3625:                 }
 3626:                 if (exists($privileged{$domain}{$username})) {
 3627:                     if (!$nothide{$username.':'.$domain}) {
 3628:                         next;
 3629:                     }
 3630:                 }
 3631:             }
 3632:         }
 3633:         if ($withsec) {
 3634:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 3635:                 $tstart.':'.$tend;
 3636:         } else {
 3637:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 3638:         }
 3639:     }
 3640:     return %returnhash;
 3641: }
 3642: 
 3643: # ----------------------------------------------------- Frontpage Announcements
 3644: #
 3645: #
 3646: 
 3647: sub postannounce {
 3648:     my ($server,$text)=@_;
 3649:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 3650:     unless ($text=~/\w/) { $text=''; }
 3651:     return &reply('setannounce:'.&escape($text),$server);
 3652: }
 3653: 
 3654: sub getannounce {
 3655: 
 3656:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 3657: 	my $announcement='';
 3658: 	while (my $line = <$fh>) { $announcement .= $line; }
 3659: 	close($fh);
 3660: 	if ($announcement=~/\w/) { 
 3661: 	    return 
 3662:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 3663:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 3664: 	} else {
 3665: 	    return '';
 3666: 	}
 3667:     } else {
 3668: 	return '';
 3669:     }
 3670: }
 3671: 
 3672: # ---------------------------------------------------------- Course ID routines
 3673: # Deal with domain's nohist_courseid.db files
 3674: #
 3675: 
 3676: sub courseidput {
 3677:     my ($domain,$storehash,$coursehome,$caller) = @_;
 3678:     return unless (ref($storehash) eq 'HASH');
 3679:     my $outcome;
 3680:     if ($caller eq 'timeonly') {
 3681:         my $cids = '';
 3682:         foreach my $item (keys(%$storehash)) {
 3683:             $cids.=&escape($item).'&';
 3684:         }
 3685:         $cids=~s/\&$//;
 3686:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 3687:                           $coursehome);       
 3688:     } else {
 3689:         my $items = '';
 3690:         foreach my $item (keys(%$storehash)) {
 3691:             $items.= &escape($item).'='.
 3692:                      &freeze_escape($$storehash{$item}).'&';
 3693:         }
 3694:         $items=~s/\&$//;
 3695:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 3696:                           $coursehome);
 3697:     }
 3698:     if ($outcome eq 'unknown_cmd') {
 3699:         my $what;
 3700:         foreach my $cid (keys(%$storehash)) {
 3701:             $what .= &escape($cid).'=';
 3702:             foreach my $item ('description','inst_code','owner','type') {
 3703:                 $what .= &escape($storehash->{$cid}{$item}).':';
 3704:             }
 3705:             $what =~ s/\:$/&/;
 3706:         }
 3707:         $what =~ s/\&$//;  
 3708:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 3709:     } else {
 3710:         return $outcome;
 3711:     }
 3712: }
 3713: 
 3714: sub courseiddump {
 3715:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 3716:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 3717:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 3718:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
 3719:     my $as_hash = 1;
 3720:     my %returnhash;
 3721:     if (!$domfilter) { $domfilter=''; }
 3722:     my %libserv = &all_library();
 3723:     foreach my $tryserver (keys(%libserv)) {
 3724:         if ( (  $hostidflag == 1 
 3725: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 3726: 	     || (!defined($hostidflag)) ) {
 3727: 
 3728: 	    if (($domfilter eq '') ||
 3729: 		(&host_domain($tryserver) eq $domfilter)) {
 3730:                 my $rep = 
 3731:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
 3732:                          $sincefilter.':'.&escape($descfilter).':'.
 3733:                          &escape($instcodefilter).':'.&escape($ownerfilter).
 3734:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
 3735:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
 3736:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
 3737:                          $showhidden.':'.$caller.':'.&escape($cloner).':'.
 3738:                          &escape($cc_clone).':'.$cloneonly.':'.
 3739:                          &escape($createdbefore).':'.&escape($createdafter).':'.
 3740:                          &escape($creationcontext).':'.$domcloner,
 3741:                          $tryserver);
 3742:                 my @pairs=split(/\&/,$rep);
 3743:                 foreach my $item (@pairs) {
 3744:                     my ($key,$value)=split(/\=/,$item,2);
 3745:                     $key = &unescape($key);
 3746:                     next if ($key =~ /^error: 2 /);
 3747:                     my $result = &thaw_unescape($value);
 3748:                     if (ref($result) eq 'HASH') {
 3749:                         $returnhash{$key}=$result;
 3750:                     } else {
 3751:                         my @responses = split(/:/,$value);
 3752:                         my @items = ('description','inst_code','owner','type');
 3753:                         for (my $i=0; $i<@responses; $i++) {
 3754:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 3755:                         }
 3756:                     }
 3757:                 }
 3758:             }
 3759:         }
 3760:     }
 3761:     return %returnhash;
 3762: }
 3763: 
 3764: sub courselastaccess {
 3765:     my ($cdom,$cnum,$hostidref) = @_;
 3766:     my %returnhash;
 3767:     if ($cdom && $cnum) {
 3768:         my $chome = &homeserver($cnum,$cdom);
 3769:         if ($chome ne 'no_host') {
 3770:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 3771:             &extract_lastaccess(\%returnhash,$rep);
 3772:         }
 3773:     } else {
 3774:         if (!$cdom) { $cdom=''; }
 3775:         my %libserv = &all_library();
 3776:         foreach my $tryserver (keys(%libserv)) {
 3777:             if (ref($hostidref) eq 'ARRAY') {
 3778:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 3779:             } 
 3780:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 3781:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 3782:                 &extract_lastaccess(\%returnhash,$rep);
 3783:             }
 3784:         }
 3785:     }
 3786:     return %returnhash;
 3787: }
 3788: 
 3789: sub extract_lastaccess {
 3790:     my ($returnhash,$rep) = @_;
 3791:     if (ref($returnhash) eq 'HASH') {
 3792:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 3793:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 3794:                  $rep eq '') {
 3795:             my @pairs=split(/\&/,$rep);
 3796:             foreach my $item (@pairs) {
 3797:                 my ($key,$value)=split(/\=/,$item,2);
 3798:                 $key = &unescape($key);
 3799:                 next if ($key =~ /^error: 2 /);
 3800:                 $returnhash->{$key} = &thaw_unescape($value);
 3801:             }
 3802:         }
 3803:     }
 3804:     return;
 3805: }
 3806: 
 3807: # ---------------------------------------------------------- DC e-mail
 3808: 
 3809: sub dcmailput {
 3810:     my ($domain,$msgid,$message,$server)=@_;
 3811:     my $status = &Apache::lonnet::critical(
 3812:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 3813:        &escape($message),$server);
 3814:     return $status;
 3815: }
 3816: 
 3817: sub dcmaildump {
 3818:     my ($dom,$startdate,$enddate,$senders) = @_;
 3819:     my %returnhash=();
 3820: 
 3821:     if (defined(&domain($dom,'primary'))) {
 3822:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 3823:                                                          &escape($enddate).':';
 3824: 	my @esc_senders=map { &escape($_)} @$senders;
 3825: 	$cmd.=&escape(join('&',@esc_senders));
 3826: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 3827:             my ($key,$value) = split(/\=/,$line,2);
 3828:             if (($key) && ($value)) {
 3829:                 $returnhash{&unescape($key)} = &unescape($value);
 3830:             }
 3831:         }
 3832:     }
 3833:     return %returnhash;
 3834: }
 3835: # ---------------------------------------------------------- Domain roles
 3836: 
 3837: sub get_domain_roles {
 3838:     my ($dom,$roles,$startdate,$enddate)=@_;
 3839:     if ((!defined($startdate)) || ($startdate eq '')) {
 3840:         $startdate = '.';
 3841:     }
 3842:     if ((!defined($enddate)) || ($enddate eq '')) {
 3843:         $enddate = '.';
 3844:     }
 3845:     my $rolelist;
 3846:     if (ref($roles) eq 'ARRAY') {
 3847:         $rolelist = join(':',@{$roles});
 3848:     }
 3849:     my %personnel = ();
 3850: 
 3851:     my %servers = &get_servers($dom,'library');
 3852:     foreach my $tryserver (keys(%servers)) {
 3853: 	%{$personnel{$tryserver}}=();
 3854: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 3855: 					    &escape($startdate).':'.
 3856: 					    &escape($enddate).':'.
 3857: 					    &escape($rolelist), $tryserver))) {
 3858: 	    my ($key,$value) = split(/\=/,$line,2);
 3859: 	    if (($key) && ($value)) {
 3860: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 3861: 	    }
 3862: 	}
 3863:     }
 3864:     return %personnel;
 3865: }
 3866: 
 3867: # ----------------------------------------------------------- Interval timing 
 3868: 
 3869: {
 3870: # Caches needed for speedup of navmaps
 3871: # We don't want to cache this for very long at all (5 seconds at most)
 3872: # 
 3873: # The user for whom we cache
 3874: my $cachedkey='';
 3875: # The cached times for this user
 3876: my %cachedtimes=();
 3877: # When this was last done
 3878: my $cachedtime=();
 3879: 
 3880: sub load_all_first_access {
 3881:     my ($uname,$udom)=@_;
 3882:     if (($cachedkey eq $uname.':'.$udom) &&
 3883:         (abs($cachedtime-time)<5)) {
 3884:         return;
 3885:     }
 3886:     $cachedtime=time;
 3887:     $cachedkey=$uname.':'.$udom;
 3888:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 3889: }
 3890: 
 3891: sub get_first_access {
 3892:     my ($type,$argsymb)=@_;
 3893:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 3894:     if ($argsymb) { $symb=$argsymb; }
 3895:     my ($map,$id,$res)=&decode_symb($symb);
 3896:     if ($type eq 'course') {
 3897: 	$res='course';
 3898:     } elsif ($type eq 'map') {
 3899: 	$res=&symbread($map);
 3900:     } else {
 3901: 	$res=$symb;
 3902:     }
 3903:     &load_all_first_access($uname,$udom);
 3904:     return $cachedtimes{"$courseid\0$res"};
 3905: }
 3906: 
 3907: sub set_first_access {
 3908:     my ($type)=@_;
 3909:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 3910:     my ($map,$id,$res)=&decode_symb($symb);
 3911:     if ($type eq 'course') {
 3912: 	$res='course';
 3913:     } elsif ($type eq 'map') {
 3914: 	$res=&symbread($map);
 3915:     } else {
 3916: 	$res=$symb;
 3917:     }
 3918:     $cachedkey='';
 3919:     my $firstaccess=&get_first_access($type,$symb);
 3920:     if (!$firstaccess) {
 3921: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
 3922:     }
 3923:     return 'already_set';
 3924: }
 3925: }
 3926: # --------------------------------------------- Set Expire Date for Spreadsheet
 3927: 
 3928: sub expirespread {
 3929:     my ($uname,$udom,$stype,$usymb)=@_;
 3930:     my $cid=$env{'request.course.id'}; 
 3931:     if ($cid) {
 3932:        my $now=time;
 3933:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 3934:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 3935:                             $env{'course.'.$cid.'.num'}.
 3936: 	        	    ':nohist_expirationdates:'.
 3937:                             &escape($key).'='.$now,
 3938:                             $env{'course.'.$cid.'.home'})
 3939:     }
 3940:     return 'ok';
 3941: }
 3942: 
 3943: # ----------------------------------------------------- Devalidate Spreadsheets
 3944: 
 3945: sub devalidate {
 3946:     my ($symb,$uname,$udom)=@_;
 3947:     my $cid=$env{'request.course.id'}; 
 3948:     if ($cid) {
 3949:         # delete the stored spreadsheets for
 3950:         # - the student level sheet of this user in course's homespace
 3951:         # - the assessment level sheet for this resource 
 3952:         #   for this user in user's homespace
 3953: 	# - current conditional state info
 3954: 	my $key=$uname.':'.$udom.':';
 3955:         my $status=
 3956: 	    &del('nohist_calculatedsheets',
 3957: 		 [$key.'studentcalc:'],
 3958: 		 $env{'course.'.$cid.'.domain'},
 3959: 		 $env{'course.'.$cid.'.num'})
 3960: 		.' '.
 3961: 	    &del('nohist_calculatedsheets_'.$cid,
 3962: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 3963:         unless ($status eq 'ok ok') {
 3964:            &logthis('Could not devalidate spreadsheet '.
 3965:                     $uname.' at '.$udom.' for '.
 3966: 		    $symb.': '.$status);
 3967:         }
 3968: 	&delenv('user.state.'.$cid);
 3969:     }
 3970: }
 3971: 
 3972: sub get_scalar {
 3973:     my ($string,$end) = @_;
 3974:     my $value;
 3975:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 3976: 	$value = $1;
 3977:     } elsif ($$string =~ s/^([^&]*?)&//) {
 3978: 	$value = $1;
 3979:     }
 3980:     return &unescape($value);
 3981: }
 3982: 
 3983: sub array2str {
 3984:   my (@array) = @_;
 3985:   my $result=&arrayref2str(\@array);
 3986:   $result=~s/^__ARRAY_REF__//;
 3987:   $result=~s/__END_ARRAY_REF__$//;
 3988:   return $result;
 3989: }
 3990: 
 3991: sub arrayref2str {
 3992:   my ($arrayref) = @_;
 3993:   my $result='__ARRAY_REF__';
 3994:   foreach my $elem (@$arrayref) {
 3995:     if(ref($elem) eq 'ARRAY') {
 3996:       $result.=&arrayref2str($elem).'&';
 3997:     } elsif(ref($elem) eq 'HASH') {
 3998:       $result.=&hashref2str($elem).'&';
 3999:     } elsif(ref($elem)) {
 4000:       #print("Got a ref of ".(ref($elem))." skipping.");
 4001:     } else {
 4002:       $result.=&escape($elem).'&';
 4003:     }
 4004:   }
 4005:   $result=~s/\&$//;
 4006:   $result .= '__END_ARRAY_REF__';
 4007:   return $result;
 4008: }
 4009: 
 4010: sub hash2str {
 4011:   my (%hash) = @_;
 4012:   my $result=&hashref2str(\%hash);
 4013:   $result=~s/^__HASH_REF__//;
 4014:   $result=~s/__END_HASH_REF__$//;
 4015:   return $result;
 4016: }
 4017: 
 4018: sub hashref2str {
 4019:   my ($hashref)=@_;
 4020:   my $result='__HASH_REF__';
 4021:   foreach my $key (sort(keys(%$hashref))) {
 4022:     if (ref($key) eq 'ARRAY') {
 4023:       $result.=&arrayref2str($key).'=';
 4024:     } elsif (ref($key) eq 'HASH') {
 4025:       $result.=&hashref2str($key).'=';
 4026:     } elsif (ref($key)) {
 4027:       $result.='=';
 4028:       #print("Got a ref of ".(ref($key))." skipping.");
 4029:     } else {
 4030: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 4031:     }
 4032: 
 4033:     if(ref($hashref->{$key}) eq 'ARRAY') {
 4034:       $result.=&arrayref2str($hashref->{$key}).'&';
 4035:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 4036:       $result.=&hashref2str($hashref->{$key}).'&';
 4037:     } elsif(ref($hashref->{$key})) {
 4038:        $result.='&';
 4039:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 4040:     } else {
 4041:       $result.=&escape($hashref->{$key}).'&';
 4042:     }
 4043:   }
 4044:   $result=~s/\&$//;
 4045:   $result .= '__END_HASH_REF__';
 4046:   return $result;
 4047: }
 4048: 
 4049: sub str2hash {
 4050:     my ($string)=@_;
 4051:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 4052:     return %$hash;
 4053: }
 4054: 
 4055: sub str2hashref {
 4056:   my ($string) = @_;
 4057: 
 4058:   my %hash;
 4059: 
 4060:   if($string !~ /^__HASH_REF__/) {
 4061:       if (! ($string eq '' || !defined($string))) {
 4062: 	  $hash{'error'}='Not hash reference';
 4063:       }
 4064:       return (\%hash, $string);
 4065:   }
 4066: 
 4067:   $string =~ s/^__HASH_REF__//;
 4068: 
 4069:   while($string !~ /^__END_HASH_REF__/) {
 4070:       #key
 4071:       my $key='';
 4072:       if($string =~ /^__HASH_REF__/) {
 4073:           ($key, $string)=&str2hashref($string);
 4074:           if(defined($key->{'error'})) {
 4075:               $hash{'error'}='Bad data';
 4076:               return (\%hash, $string);
 4077:           }
 4078:       } elsif($string =~ /^__ARRAY_REF__/) {
 4079:           ($key, $string)=&str2arrayref($string);
 4080:           if($key->[0] eq 'Array reference error') {
 4081:               $hash{'error'}='Bad data';
 4082:               return (\%hash, $string);
 4083:           }
 4084:       } else {
 4085:           $string =~ s/^(.*?)=//;
 4086: 	  $key=&unescape($1);
 4087:       }
 4088:       $string =~ s/^=//;
 4089: 
 4090:       #value
 4091:       my $value='';
 4092:       if($string =~ /^__HASH_REF__/) {
 4093:           ($value, $string)=&str2hashref($string);
 4094:           if(defined($value->{'error'})) {
 4095:               $hash{'error'}='Bad data';
 4096:               return (\%hash, $string);
 4097:           }
 4098:       } elsif($string =~ /^__ARRAY_REF__/) {
 4099:           ($value, $string)=&str2arrayref($string);
 4100:           if($value->[0] eq 'Array reference error') {
 4101:               $hash{'error'}='Bad data';
 4102:               return (\%hash, $string);
 4103:           }
 4104:       } else {
 4105: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 4106:       }
 4107:       $string =~ s/^&//;
 4108: 
 4109:       $hash{$key}=$value;
 4110:   }
 4111: 
 4112:   $string =~ s/^__END_HASH_REF__//;
 4113: 
 4114:   return (\%hash, $string);
 4115: }
 4116: 
 4117: sub str2array {
 4118:     my ($string)=@_;
 4119:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 4120:     return @$array;
 4121: }
 4122: 
 4123: sub str2arrayref {
 4124:   my ($string) = @_;
 4125:   my @array;
 4126: 
 4127:   if($string !~ /^__ARRAY_REF__/) {
 4128:       if (! ($string eq '' || !defined($string))) {
 4129: 	  $array[0]='Array reference error';
 4130:       }
 4131:       return (\@array, $string);
 4132:   }
 4133: 
 4134:   $string =~ s/^__ARRAY_REF__//;
 4135: 
 4136:   while($string !~ /^__END_ARRAY_REF__/) {
 4137:       my $value='';
 4138:       if($string =~ /^__HASH_REF__/) {
 4139:           ($value, $string)=&str2hashref($string);
 4140:           if(defined($value->{'error'})) {
 4141:               $array[0] ='Array reference error';
 4142:               return (\@array, $string);
 4143:           }
 4144:       } elsif($string =~ /^__ARRAY_REF__/) {
 4145:           ($value, $string)=&str2arrayref($string);
 4146:           if($value->[0] eq 'Array reference error') {
 4147:               $array[0] ='Array reference error';
 4148:               return (\@array, $string);
 4149:           }
 4150:       } else {
 4151: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 4152:       }
 4153:       $string =~ s/^&//;
 4154: 
 4155:       push(@array, $value);
 4156:   }
 4157: 
 4158:   $string =~ s/^__END_ARRAY_REF__//;
 4159: 
 4160:   return (\@array, $string);
 4161: }
 4162: 
 4163: # -------------------------------------------------------------------Temp Store
 4164: 
 4165: sub tmpreset {
 4166:   my ($symb,$namespace,$domain,$stuname) = @_;
 4167:   if (!$symb) {
 4168:     $symb=&symbread();
 4169:     if (!$symb) { $symb= $env{'request.url'}; }
 4170:   }
 4171:   $symb=escape($symb);
 4172: 
 4173:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4174:   $namespace=~s/\//\_/g;
 4175:   $namespace=~s/\W//g;
 4176: 
 4177:   if (!$domain) { $domain=$env{'user.domain'}; }
 4178:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4179:   if ($domain eq 'public' && $stuname eq 'public') {
 4180:       $stuname=$ENV{'REMOTE_ADDR'};
 4181:   }
 4182:   my $path=LONCAPA::tempdir();
 4183:   my %hash;
 4184:   if (tie(%hash,'GDBM_File',
 4185: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4186: 	  &GDBM_WRCREAT(),0640)) {
 4187:     foreach my $key (keys(%hash)) {
 4188:       if ($key=~ /:$symb/) {
 4189: 	delete($hash{$key});
 4190:       }
 4191:     }
 4192:   }
 4193: }
 4194: 
 4195: sub tmpstore {
 4196:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4197: 
 4198:   if (!$symb) {
 4199:     $symb=&symbread();
 4200:     if (!$symb) { $symb= $env{'request.url'}; }
 4201:   }
 4202:   $symb=escape($symb);
 4203: 
 4204:   if (!$namespace) {
 4205:     # I don't think we would ever want to store this for a course.
 4206:     # it seems this will only be used if we don't have a course.
 4207:     #$namespace=$env{'request.course.id'};
 4208:     #if (!$namespace) {
 4209:       $namespace=$env{'request.state'};
 4210:     #}
 4211:   }
 4212:   $namespace=~s/\//\_/g;
 4213:   $namespace=~s/\W//g;
 4214:   if (!$domain) { $domain=$env{'user.domain'}; }
 4215:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4216:   if ($domain eq 'public' && $stuname eq 'public') {
 4217:       $stuname=$ENV{'REMOTE_ADDR'};
 4218:   }
 4219:   my $now=time;
 4220:   my %hash;
 4221:   my $path=LONCAPA::tempdir();
 4222:   if (tie(%hash,'GDBM_File',
 4223: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4224: 	  &GDBM_WRCREAT(),0640)) {
 4225:     $hash{"version:$symb"}++;
 4226:     my $version=$hash{"version:$symb"};
 4227:     my $allkeys=''; 
 4228:     foreach my $key (keys(%$storehash)) {
 4229:       $allkeys.=$key.':';
 4230:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 4231:     }
 4232:     $hash{"$version:$symb:timestamp"}=$now;
 4233:     $allkeys.='timestamp';
 4234:     $hash{"$version:keys:$symb"}=$allkeys;
 4235:     if (untie(%hash)) {
 4236:       return 'ok';
 4237:     } else {
 4238:       return "error:$!";
 4239:     }
 4240:   } else {
 4241:     return "error:$!";
 4242:   }
 4243: }
 4244: 
 4245: # -----------------------------------------------------------------Temp Restore
 4246: 
 4247: sub tmprestore {
 4248:   my ($symb,$namespace,$domain,$stuname) = @_;
 4249: 
 4250:   if (!$symb) {
 4251:     $symb=&symbread();
 4252:     if (!$symb) { $symb= $env{'request.url'}; }
 4253:   }
 4254:   $symb=escape($symb);
 4255: 
 4256:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4257: 
 4258:   if (!$domain) { $domain=$env{'user.domain'}; }
 4259:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4260:   if ($domain eq 'public' && $stuname eq 'public') {
 4261:       $stuname=$ENV{'REMOTE_ADDR'};
 4262:   }
 4263:   my %returnhash;
 4264:   $namespace=~s/\//\_/g;
 4265:   $namespace=~s/\W//g;
 4266:   my %hash;
 4267:   my $path=LONCAPA::tempdir();
 4268:   if (tie(%hash,'GDBM_File',
 4269: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4270: 	  &GDBM_READER(),0640)) {
 4271:     my $version=$hash{"version:$symb"};
 4272:     $returnhash{'version'}=$version;
 4273:     my $scope;
 4274:     for ($scope=1;$scope<=$version;$scope++) {
 4275:       my $vkeys=$hash{"$scope:keys:$symb"};
 4276:       my @keys=split(/:/,$vkeys);
 4277:       my $key;
 4278:       $returnhash{"$scope:keys"}=$vkeys;
 4279:       foreach $key (@keys) {
 4280: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4281: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4282:       }
 4283:     }
 4284:     if (!(untie(%hash))) {
 4285:       return "error:$!";
 4286:     }
 4287:   } else {
 4288:     return "error:$!";
 4289:   }
 4290:   return %returnhash;
 4291: }
 4292: 
 4293: # ----------------------------------------------------------------------- Store
 4294: 
 4295: sub store {
 4296:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4297:     my $home='';
 4298: 
 4299:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4300: 
 4301:     $symb=&symbclean($symb);
 4302:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 4303: 
 4304:     if (!$domain) { $domain=$env{'user.domain'}; }
 4305:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4306: 
 4307:     &devalidate($symb,$stuname,$domain);
 4308: 
 4309:     $symb=escape($symb);
 4310:     if (!$namespace) { 
 4311:        unless ($namespace=$env{'request.course.id'}) { 
 4312:           return ''; 
 4313:        } 
 4314:     }
 4315:     if (!$home) { $home=$env{'user.home'}; }
 4316: 
 4317:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 4318:     $$storehash{'host'}=$perlvar{'lonHostID'};
 4319: 
 4320:     my $namevalue='';
 4321:     foreach my $key (keys(%$storehash)) {
 4322:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4323:     }
 4324:     $namevalue=~s/\&$//;
 4325:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 4326:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 4327: }
 4328: 
 4329: # -------------------------------------------------------------- Critical Store
 4330: 
 4331: sub cstore {
 4332:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4333:     my $home='';
 4334: 
 4335:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4336: 
 4337:     $symb=&symbclean($symb);
 4338:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 4339: 
 4340:     if (!$domain) { $domain=$env{'user.domain'}; }
 4341:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4342: 
 4343:     &devalidate($symb,$stuname,$domain);
 4344: 
 4345:     $symb=escape($symb);
 4346:     if (!$namespace) { 
 4347:        unless ($namespace=$env{'request.course.id'}) { 
 4348:           return ''; 
 4349:        } 
 4350:     }
 4351:     if (!$home) { $home=$env{'user.home'}; }
 4352: 
 4353:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 4354:     $$storehash{'host'}=$perlvar{'lonHostID'};
 4355: 
 4356:     my $namevalue='';
 4357:     foreach my $key (keys(%$storehash)) {
 4358:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4359:     }
 4360:     $namevalue=~s/\&$//;
 4361:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 4362:     return critical
 4363:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 4364: }
 4365: 
 4366: # --------------------------------------------------------------------- Restore
 4367: 
 4368: sub restore {
 4369:     my ($symb,$namespace,$domain,$stuname) = @_;
 4370:     my $home='';
 4371: 
 4372:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4373: 
 4374:     if (!$symb) {
 4375:       unless ($symb=escape(&symbread())) { return ''; }
 4376:     } else {
 4377:       $symb=&escape(&symbclean($symb));
 4378:     }
 4379:     if (!$namespace) { 
 4380:        unless ($namespace=$env{'request.course.id'}) { 
 4381:           return ''; 
 4382:        } 
 4383:     }
 4384:     if (!$domain) { $domain=$env{'user.domain'}; }
 4385:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4386:     if (!$home) { $home=$env{'user.home'}; }
 4387:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 4388: 
 4389:     my %returnhash=();
 4390:     foreach my $line (split(/\&/,$answer)) {
 4391: 	my ($name,$value)=split(/\=/,$line);
 4392:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 4393:     }
 4394:     my $version;
 4395:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 4396:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 4397:           $returnhash{$item}=$returnhash{$version.':'.$item};
 4398:        }
 4399:     }
 4400:     return %returnhash;
 4401: }
 4402: 
 4403: # ---------------------------------------------------------- Course Description
 4404: #
 4405: #  
 4406: 
 4407: sub coursedescription {
 4408:     my ($courseid,$args)=@_;
 4409:     $courseid=~s/^\///;
 4410:     $courseid=~s/\_/\//g;
 4411:     my ($cdomain,$cnum)=split(/\//,$courseid);
 4412:     my $chome=&homeserver($cnum,$cdomain);
 4413:     my $normalid=$cdomain.'_'.$cnum;
 4414:     # need to always cache even if we get errors otherwise we keep 
 4415:     # trying and trying and trying to get the course description.
 4416:     my %envhash=();
 4417:     my %returnhash=();
 4418:     
 4419:     my $expiretime=600;
 4420:     if ($env{'request.course.id'} eq $normalid) {
 4421: 	$expiretime=120;
 4422:     }
 4423: 
 4424:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 4425:     if (!$args->{'freshen_cache'}
 4426: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 4427: 	foreach my $key (keys(%env)) {
 4428: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 4429: 	    my ($setting) = $1;
 4430: 	    $returnhash{$setting} = $env{$key};
 4431: 	}
 4432: 	return %returnhash;
 4433:     }
 4434: 
 4435:     # get the data again
 4436: 
 4437:     if (!$args->{'one_time'}) {
 4438: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 4439:     }
 4440: 
 4441:     if ($chome ne 'no_host') {
 4442:        %returnhash=&dump('environment',$cdomain,$cnum);
 4443:        if (!exists($returnhash{'con_lost'})) {
 4444: 	   my $username = $env{'user.name'}; # Defult username
 4445: 	   if(defined $args->{'user'}) {
 4446: 	       $username = $args->{'user'};
 4447: 	   }
 4448:            $returnhash{'home'}= $chome;
 4449: 	   $returnhash{'domain'} = $cdomain;
 4450: 	   $returnhash{'num'} = $cnum;
 4451:            if (!defined($returnhash{'type'})) {
 4452:                $returnhash{'type'} = 'Course';
 4453:            }
 4454:            while (my ($name,$value) = each %returnhash) {
 4455:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 4456:            }
 4457:            $returnhash{'url'}=&clutter($returnhash{'url'});
 4458:            $returnhash{'fn'}=LONCAPA::tempdir() .
 4459: 	       $username.'_'.$cdomain.'_'.$cnum;
 4460:            $envhash{'course.'.$normalid.'.home'}=$chome;
 4461:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 4462:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 4463:        }
 4464:     }
 4465:     if (!$args->{'one_time'}) {
 4466: 	&appenv(\%envhash);
 4467:     }
 4468:     return %returnhash;
 4469: }
 4470: 
 4471: sub update_released_required {
 4472:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 4473:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 4474:         $cid = $env{'request.course.id'};
 4475:         $cdom = $env{'course.'.$cid.'.domain'};
 4476:         $cnum = $env{'course.'.$cid.'.num'};
 4477:         $chome = $env{'course.'.$cid.'.home'};
 4478:     }
 4479:     if ($needsrelease) {
 4480:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 4481:         my $needsupdate;
 4482:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 4483:             $needsupdate = 1;
 4484:         } else {
 4485:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 4486:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 4487:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 4488:                 $needsupdate = 1;
 4489:             }
 4490:         }
 4491:         if ($needsupdate) {
 4492:             my %needshash = (
 4493:                              'internal.releaserequired' => $needsrelease,
 4494:                             );
 4495:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 4496:             if ($putresult eq 'ok') {
 4497:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 4498:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 4499:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 4500:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 4501:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 4502:                 }
 4503:             }
 4504:         }
 4505:     }
 4506:     return;
 4507: }
 4508: 
 4509: # -------------------------------------------------See if a user is privileged
 4510: 
 4511: sub privileged {
 4512:     my ($username,$domain)=@_;
 4513:     my $rolesdump=&reply("dump:$domain:$username:roles",
 4514: 			&homeserver($username,$domain));
 4515:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
 4516:         ($rolesdump =~ /^error:/)) {
 4517:         return 0;
 4518:     }
 4519:     my $now=time;
 4520:     if ($rolesdump ne '') {
 4521:         foreach my $entry (split(/&/,$rolesdump)) {
 4522: 	    if ($entry!~/^rolesdef_/) {
 4523: 		my ($area,$role)=split(/=/,$entry);
 4524: 		$area=~s/\_\w\w$//;
 4525: 		my ($trole,$tend,$tstart)=split(/_/,$role);
 4526: 		if (($trole eq 'dc') || ($trole eq 'su')) {
 4527: 		    my $active=1;
 4528: 		    if ($tend) {
 4529: 			if ($tend<$now) { $active=0; }
 4530: 		    }
 4531: 		    if ($tstart) {
 4532: 			if ($tstart>$now) { $active=0; }
 4533: 		    }
 4534: 		    if ($active) { return 1; }
 4535: 		}
 4536: 	    }
 4537: 	}
 4538:     }
 4539:     return 0;
 4540: }
 4541: 
 4542: # -------------------------------------------------------- Get user privileges
 4543: 
 4544: sub rolesinit {
 4545:     my ($domain,$username,$authhost)=@_;
 4546:     my $now=time;
 4547:     my %userroles = ('user.login.time' => $now);
 4548:     my $extra = &freeze_escape({'skipcheck' => 1});
 4549:     my $rolesdump=reply("dump:$domain:$username:roles:.::$extra",$authhost);
 4550:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
 4551:         ($rolesdump =~ /^error:/)) {
 4552:         return \%userroles;
 4553:     }
 4554:     my %allroles=();
 4555:     my %allgroups=();   
 4556: 
 4557:     if ($rolesdump ne '') {
 4558:         foreach my $entry (split(/&/,$rolesdump)) {
 4559: 	  if ($entry!~/^rolesdef_/) {
 4560:             my ($area,$role)=split(/=/,$entry);
 4561: 	    $area=~s/\_\w\w$//;
 4562:             my ($trole,$tend,$tstart,$group_privs);
 4563: 	    if ($role=~/^cr/) { 
 4564: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 4565: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
 4566: 		    ($tend,$tstart)=split('_',$trest);
 4567: 		} else {
 4568: 		    $trole=$role;
 4569: 		}
 4570:             } elsif ($role =~ m|^gr/|) {
 4571:                 ($trole,$tend,$tstart) = split(/_/,$role);
 4572:                 next if ($tstart eq '-1');
 4573:                 ($trole,$group_privs) = split(/\//,$trole);
 4574:                 $group_privs = &unescape($group_privs);
 4575: 	    } else {
 4576: 		($trole,$tend,$tstart)=split(/_/,$role);
 4577: 	    }
 4578: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 4579: 					 $username);
 4580: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 4581:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
 4582:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
 4583:             if (($area ne '') && ($trole ne '')) {
 4584: 		my $spec=$trole.'.'.$area;
 4585: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
 4586: 		if ($trole =~ /^cr\//) {
 4587:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 4588:                 } elsif ($trole eq 'gr') {
 4589:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 4590: 		} else {
 4591:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 4592: 		}
 4593:             }
 4594:           }
 4595:         }
 4596:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
 4597:         $userroles{'user.adv'}    = $adv;
 4598: 	$userroles{'user.author'} = $author;
 4599:         $env{'user.adv'}=$adv;
 4600:     }
 4601:     return \%userroles;  
 4602: }
 4603: 
 4604: sub set_arearole {
 4605:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
 4606: # log the associated role with the area
 4607:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 4608:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 4609: }
 4610: 
 4611: sub custom_roleprivs {
 4612:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 4613:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 4614:     my $homsvr=homeserver($rauthor,$rdomain);
 4615:     if (&hostname($homsvr) ne '') {
 4616:         my ($rdummy,$roledef)=
 4617:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 4618:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 4619:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 4620:             if (defined($syspriv)) {
 4621:                 if ($trest =~ /^$match_community$/) {
 4622:                     $syspriv =~ s/bre\&S//; 
 4623:                 }
 4624:                 $$allroles{'cm./'}.=':'.$syspriv;
 4625:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 4626:             }
 4627:             if ($tdomain ne '') {
 4628:                 if (defined($dompriv)) {
 4629:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 4630:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 4631:                 }
 4632:                 if (($trest ne '') && (defined($coursepriv))) {
 4633:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 4634:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 4635:                 }
 4636:             }
 4637:         }
 4638:     }
 4639: }
 4640: 
 4641: sub group_roleprivs {
 4642:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 4643:     my $access = 1;
 4644:     my $now = time;
 4645:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 4646:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 4647:     if ($access) {
 4648:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 4649:         $$allgroups{$course}{$group} .=':'.$group_privs;
 4650:     }
 4651: }
 4652: 
 4653: sub standard_roleprivs {
 4654:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 4655:     if (defined($pr{$trole.':s'})) {
 4656:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 4657:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 4658:     }
 4659:     if ($tdomain ne '') {
 4660:         if (defined($pr{$trole.':d'})) {
 4661:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 4662:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 4663:         }
 4664:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 4665:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 4666:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 4667:         }
 4668:     }
 4669: }
 4670: 
 4671: sub set_userprivs {
 4672:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 4673:     my $author=0;
 4674:     my $adv=0;
 4675:     my %grouproles = ();
 4676:     if (keys(%{$allgroups}) > 0) {
 4677:         my @groupkeys; 
 4678:         foreach my $role (keys(%{$allroles})) {
 4679:             push(@groupkeys,$role);
 4680:         }
 4681:         if (ref($groups_roles) eq 'HASH') {
 4682:             foreach my $key (keys(%{$groups_roles})) {
 4683:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 4684:                     push(@groupkeys,$key);
 4685:                 }
 4686:             }
 4687:         }
 4688:         if (@groupkeys > 0) {
 4689:             foreach my $role (@groupkeys) {
 4690:                 my ($trole,$area,$sec,$extendedarea);
 4691:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 4692:                     $trole = $1;
 4693:                     $area = $2;
 4694:                     $sec = $3;
 4695:                     $extendedarea = $area.$sec;
 4696:                     if (exists($$allgroups{$area})) {
 4697:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 4698:                             my $spec = $trole.'.'.$extendedarea;
 4699:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 4700:                                                 $$allgroups{$area}{$group};
 4701:                         }
 4702:                     }
 4703:                 }
 4704:             }
 4705:         }
 4706:     }
 4707:     foreach my $group (keys(%grouproles)) {
 4708:         $$allroles{$group} = $grouproles{$group};
 4709:     }
 4710:     foreach my $role (keys(%{$allroles})) {
 4711:         my %thesepriv;
 4712:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 4713:         foreach my $item (split(/:/,$$allroles{$role})) {
 4714:             if ($item ne '') {
 4715:                 my ($privilege,$restrictions)=split(/&/,$item);
 4716:                 if ($restrictions eq '') {
 4717:                     $thesepriv{$privilege}='F';
 4718:                 } elsif ($thesepriv{$privilege} ne 'F') {
 4719:                     $thesepriv{$privilege}.=$restrictions;
 4720:                 }
 4721:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 4722:             }
 4723:         }
 4724:         my $thesestr='';
 4725:         foreach my $priv (sort(keys(%thesepriv))) {
 4726: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 4727: 	}
 4728:         $userroles->{'user.priv.'.$role} = $thesestr;
 4729:     }
 4730:     return ($author,$adv);
 4731: }
 4732: 
 4733: sub role_status {
 4734:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 4735:     my @pwhere = ();
 4736:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 4737:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
 4738:         unless (!defined($$role) || $$role eq '') {
 4739:             $$where=join('.',@pwhere);
 4740:             $$trolecode=$$role.'.'.$$where;
 4741:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 4742:             $$tstatus='is';
 4743:             if ($$tstart && $$tstart>$update) {
 4744:                 $$tstatus='future';
 4745:                 if ($$tstart<$now) {
 4746:                     if ($$tstart && $$tstart>$refresh) {
 4747:                         if (($$where ne '') && ($$role ne '')) {
 4748:                             my (%allroles,%allgroups,$group_privs,
 4749:                                 %groups_roles,@rolecodes);
 4750:                             my %userroles = (
 4751:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 4752:                             );
 4753:                             @rolecodes = ('cm'); 
 4754:                             my $spec=$$role.'.'.$$where;
 4755:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 4756:                             if ($$role =~ /^cr\//) {
 4757:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 4758:                                 push(@rolecodes,'cr');
 4759:                             } elsif ($$role eq 'gr') {
 4760:                                 push(@rolecodes,$$role);
 4761:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 4762:                                                     $env{'user.name'});
 4763:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 4764:                                 (undef,my $group_privs) = split(/\//,$trole);
 4765:                                 $group_privs = &unescape($group_privs);
 4766:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 4767:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 4768:                                 &get_groups_roles($tdomain,$trest,
 4769:                                                   \%course_roles,\@rolecodes,
 4770:                                                   \%groups_roles);
 4771:                             } else {
 4772:                                 push(@rolecodes,$$role);
 4773:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 4774:                             }
 4775:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
 4776:                             &appenv(\%userroles,\@rolecodes);
 4777:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 4778:                         }
 4779:                     }
 4780:                     $$tstatus = 'is';
 4781:                 }
 4782:             }
 4783:             if ($$tend) {
 4784:                 if ($$tend<$update) {
 4785:                     $$tstatus='expired';
 4786:                 } elsif ($$tend<$now) {
 4787:                     $$tstatus='will_not';
 4788:                 }
 4789:             }
 4790:         }
 4791:     }
 4792: }
 4793: 
 4794: sub get_groups_roles {
 4795:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 4796:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 4797:                   (ref($rolecodes) eq 'ARRAY') && 
 4798:                   (ref($groups_roles) eq 'HASH')); 
 4799:     if (keys(%{$cdom_courseroles}) > 0) {
 4800:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 4801:         if ($cdom ne '' && $cnum ne '') {
 4802:             foreach my $key (keys(%{$cdom_courseroles})) {
 4803:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 4804:                     my $crsrole = $1;
 4805:                     my $crssec = $2;
 4806:                     if ($crsrole =~ /^cr/) {
 4807:                         unless (grep(/^cr$/,@{$rolecodes})) {
 4808:                             push(@{$rolecodes},'cr');
 4809:                         }
 4810:                     } else {
 4811:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 4812:                             push(@{$rolecodes},$crsrole);
 4813:                         }
 4814:                     }
 4815:                     my $rolekey = "$crsrole./$cdom/$cnum";
 4816:                     if ($crssec ne '') {
 4817:                         $rolekey .= "/$crssec";
 4818:                     }
 4819:                     $rolekey .= './';
 4820:                     $groups_roles->{$rolekey} = $rolecodes;
 4821:                 }
 4822:             }
 4823:         }
 4824:     }
 4825:     return;
 4826: }
 4827: 
 4828: sub delete_env_groupprivs {
 4829:     my ($where,$courseroles,$possroles) = @_;
 4830:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 4831:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 4832:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 4833:         %{$courseroles->{$udom}} =
 4834:             &get_my_roles('','','userroles',['active'],
 4835:                           $possroles,[$udom],1);
 4836:     }
 4837:     if (ref($courseroles->{$udom}) eq 'HASH') {
 4838:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 4839:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 4840:             my $area = '/'.$cdom.'/'.$cnum;
 4841:             my $privkey = "user.priv.$crsrole.$area";
 4842:             if ($crssec ne '') {
 4843:                 $privkey .= '/'.$crssec;
 4844:             }
 4845:             $privkey .= ".$area/$group";
 4846:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 4847:         }
 4848:     }
 4849:     return;
 4850: }
 4851: 
 4852: sub check_adhoc_privs {
 4853:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
 4854:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 4855:     if ($env{$cckey}) {
 4856:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 4857:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 4858:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 4859:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 4860:         }
 4861:     } else {
 4862:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 4863:     }
 4864: }
 4865: 
 4866: sub set_adhoc_privileges {
 4867: # role can be cc or ca
 4868:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
 4869:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 4870:     my $spec = $role.'.'.$area;
 4871:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 4872:                                   $env{'user.name'});
 4873:     my %ccrole = ();
 4874:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
 4875:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
 4876:     &appenv(\%userroles,[$role,'cm']);
 4877:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 4878:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
 4879:         &appenv( {'request.role'        => $spec,
 4880:                   'request.role.domain' => $dcdom,
 4881:                   'request.course.sec'  => ''
 4882:                  }
 4883:                );
 4884:         my $tadv=0;
 4885:         if (&allowed('adv') eq 'F') { $tadv=1; }
 4886:         &appenv({'request.role.adv'    => $tadv});
 4887:     }
 4888: }
 4889: 
 4890: # --------------------------------------------------------------- get interface
 4891: 
 4892: sub get {
 4893:    my ($namespace,$storearr,$udomain,$uname)=@_;
 4894:    my $items='';
 4895:    foreach my $item (@$storearr) {
 4896:        $items.=&escape($item).'&';
 4897:    }
 4898:    $items=~s/\&$//;
 4899:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4900:    if (!$uname) { $uname=$env{'user.name'}; }
 4901:    my $uhome=&homeserver($uname,$udomain);
 4902: 
 4903:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 4904:    my @pairs=split(/\&/,$rep);
 4905:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 4906:      return @pairs;
 4907:    }
 4908:    my %returnhash=();
 4909:    my $i=0;
 4910:    foreach my $item (@$storearr) {
 4911:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 4912:       $i++;
 4913:    }
 4914:    return %returnhash;
 4915: }
 4916: 
 4917: # --------------------------------------------------------------- del interface
 4918: 
 4919: sub del {
 4920:    my ($namespace,$storearr,$udomain,$uname)=@_;
 4921:    my $items='';
 4922:    foreach my $item (@$storearr) {
 4923:        $items.=&escape($item).'&';
 4924:    }
 4925: 
 4926:    $items=~s/\&$//;
 4927:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4928:    if (!$uname) { $uname=$env{'user.name'}; }
 4929:    my $uhome=&homeserver($uname,$udomain);
 4930:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 4931: }
 4932: 
 4933: # -------------------------------------------------------------- dump interface
 4934: 
 4935: sub dump {
 4936:     my ($namespace,$udomain,$uname,$regexp,$range,$extra)=@_;
 4937:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 4938:     if (!$uname) { $uname=$env{'user.name'}; }
 4939:     my $uhome=&homeserver($uname,$udomain);
 4940:     if ($regexp) {
 4941: 	$regexp=&escape($regexp);
 4942:     } else {
 4943: 	$regexp='.';
 4944:     }
 4945:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range:$extra",$uhome);
 4946:     my @pairs=split(/\&/,$rep);
 4947:     my %returnhash=();
 4948:     if (!($rep =~ /^error/ )) {
 4949: 	foreach my $item (@pairs) {
 4950: 	    my ($key,$value)=split(/=/,$item,2);
 4951: 	    $key = &unescape($key);
 4952: 	    next if ($key =~ /^error: 2 /);
 4953: 	    $returnhash{$key}=&thaw_unescape($value);
 4954: 	}
 4955:     }
 4956:     return %returnhash;
 4957: }
 4958: 
 4959: 
 4960: # --------------------------------------------------------- dumpstore interface
 4961: 
 4962: sub dumpstore {
 4963:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 4964:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4965:    if (!$uname) { $uname=$env{'user.name'}; }
 4966:    my $uhome=&homeserver($uname,$udomain);
 4967:    if ($regexp) {
 4968:        $regexp=&escape($regexp);
 4969:    } else {
 4970:        $regexp='.';
 4971:    }
 4972:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 4973:    my @pairs=split(/\&/,$rep);
 4974:    my %returnhash=();
 4975:    foreach my $item (@pairs) {
 4976:        my ($key,$value)=split(/=/,$item,2);
 4977:        next if ($key =~ /^error: 2 /);
 4978:        $returnhash{$key}=&thaw_unescape($value);
 4979:    }
 4980:    return %returnhash;
 4981: }
 4982: 
 4983: # -------------------------------------------------------------- keys interface
 4984: 
 4985: sub getkeys {
 4986:    my ($namespace,$udomain,$uname)=@_;
 4987:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4988:    if (!$uname) { $uname=$env{'user.name'}; }
 4989:    my $uhome=&homeserver($uname,$udomain);
 4990:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 4991:    my @keyarray=();
 4992:    foreach my $key (split(/\&/,$rep)) {
 4993:       next if ($key =~ /^error: 2 /);
 4994:       push(@keyarray,&unescape($key));
 4995:    }
 4996:    return @keyarray;
 4997: }
 4998: 
 4999: # --------------------------------------------------------------- currentdump
 5000: sub currentdump {
 5001:    my ($courseid,$sdom,$sname)=@_;
 5002:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 5003:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 5004:    $sname    = $env{'user.name'}         if (! defined($sname));
 5005:    my $uhome = &homeserver($sname,$sdom);
 5006:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 5007:    return if ($rep =~ /^(error:|no_such_host)/);
 5008:    #
 5009:    my %returnhash=();
 5010:    #
 5011:    if ($rep eq "unknown_cmd") { 
 5012:        # an old lond will not know currentdump
 5013:        # Do a dump and make it look like a currentdump
 5014:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 5015:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 5016:        my %hash = @tmp;
 5017:        @tmp=();
 5018:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 5019:    } else {
 5020:        my @pairs=split(/\&/,$rep);
 5021:        foreach my $pair (@pairs) {
 5022:            my ($key,$value)=split(/=/,$pair,2);
 5023:            my ($symb,$param) = split(/:/,$key);
 5024:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 5025:                                                         &thaw_unescape($value);
 5026:        }
 5027:    }
 5028:    return %returnhash;
 5029: }
 5030: 
 5031: sub convert_dump_to_currentdump{
 5032:     my %hash = %{shift()};
 5033:     my %returnhash;
 5034:     # Code ripped from lond, essentially.  The only difference
 5035:     # here is the unescaping done by lonnet::dump().  Conceivably
 5036:     # we might run in to problems with parameter names =~ /^v\./
 5037:     while (my ($key,$value) = each(%hash)) {
 5038:         my ($v,$symb,$param) = split(/:/,$key);
 5039: 	$symb  = &unescape($symb);
 5040: 	$param = &unescape($param);
 5041:         next if ($v eq 'version' || $symb eq 'keys');
 5042:         next if (exists($returnhash{$symb}) &&
 5043:                  exists($returnhash{$symb}->{$param}) &&
 5044:                  $returnhash{$symb}->{'v.'.$param} > $v);
 5045:         $returnhash{$symb}->{$param}=$value;
 5046:         $returnhash{$symb}->{'v.'.$param}=$v;
 5047:     }
 5048:     #
 5049:     # Remove all of the keys in the hashes which keep track of
 5050:     # the version of the parameter.
 5051:     while (my ($symb,$param_hash) = each(%returnhash)) {
 5052:         # use a foreach because we are going to delete from the hash.
 5053:         foreach my $key (keys(%$param_hash)) {
 5054:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 5055:         }
 5056:     }
 5057:     return \%returnhash;
 5058: }
 5059: 
 5060: # ------------------------------------------------------ critical inc interface
 5061: 
 5062: sub cinc {
 5063:     return &inc(@_,'critical');
 5064: }
 5065: 
 5066: # --------------------------------------------------------------- inc interface
 5067: 
 5068: sub inc {
 5069:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 5070:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5071:     if (!$uname) { $uname=$env{'user.name'}; }
 5072:     my $uhome=&homeserver($uname,$udomain);
 5073:     my $items='';
 5074:     if (! ref($store)) {
 5075:         # got a single value, so use that instead
 5076:         $items = &escape($store).'=&';
 5077:     } elsif (ref($store) eq 'SCALAR') {
 5078:         $items = &escape($$store).'=&';        
 5079:     } elsif (ref($store) eq 'ARRAY') {
 5080:         $items = join('=&',map {&escape($_);} @{$store});
 5081:     } elsif (ref($store) eq 'HASH') {
 5082:         while (my($key,$value) = each(%{$store})) {
 5083:             $items.= &escape($key).'='.&escape($value).'&';
 5084:         }
 5085:     }
 5086:     $items=~s/\&$//;
 5087:     if ($critical) {
 5088: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 5089:     } else {
 5090: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 5091:     }
 5092: }
 5093: 
 5094: # --------------------------------------------------------------- put interface
 5095: 
 5096: sub put {
 5097:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5098:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5099:    if (!$uname) { $uname=$env{'user.name'}; }
 5100:    my $uhome=&homeserver($uname,$udomain);
 5101:    my $items='';
 5102:    foreach my $item (keys(%$storehash)) {
 5103:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5104:    }
 5105:    $items=~s/\&$//;
 5106:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5107: }
 5108: 
 5109: # ------------------------------------------------------------ newput interface
 5110: 
 5111: sub newput {
 5112:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5113:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5114:    if (!$uname) { $uname=$env{'user.name'}; }
 5115:    my $uhome=&homeserver($uname,$udomain);
 5116:    my $items='';
 5117:    foreach my $key (keys(%$storehash)) {
 5118:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 5119:    }
 5120:    $items=~s/\&$//;
 5121:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 5122: }
 5123: 
 5124: # ---------------------------------------------------------  putstore interface
 5125: 
 5126: sub putstore {
 5127:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 5128:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5129:    if (!$uname) { $uname=$env{'user.name'}; }
 5130:    my $uhome=&homeserver($uname,$udomain);
 5131:    my $items='';
 5132:    foreach my $key (keys(%$storehash)) {
 5133:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 5134:    }
 5135:    $items=~s/\&$//;
 5136:    my $esc_symb=&escape($symb);
 5137:    my $esc_v=&escape($version);
 5138:    my $reply =
 5139:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 5140: 	      $uhome);
 5141:    if ($reply eq 'unknown_cmd') {
 5142:        # gfall back to way things use to be done
 5143:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 5144: 			    $uname);
 5145:    }
 5146:    return $reply;
 5147: }
 5148: 
 5149: sub old_putstore {
 5150:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 5151:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5152:     if (!$uname) { $uname=$env{'user.name'}; }
 5153:     my $uhome=&homeserver($uname,$udomain);
 5154:     my %newstorehash;
 5155:     foreach my $item (keys(%$storehash)) {
 5156: 	my $key = $version.':'.&escape($symb).':'.$item;
 5157: 	$newstorehash{$key} = $storehash->{$item};
 5158:     }
 5159:     my $items='';
 5160:     my %allitems = ();
 5161:     foreach my $item (keys(%newstorehash)) {
 5162: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 5163: 	    my $key = $1.':keys:'.$2;
 5164: 	    $allitems{$key} .= $3.':';
 5165: 	}
 5166: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 5167:     }
 5168:     foreach my $item (keys(%allitems)) {
 5169: 	$allitems{$item} =~ s/\:$//;
 5170: 	$items.= $item.'='.$allitems{$item}.'&';
 5171:     }
 5172:     $items=~s/\&$//;
 5173:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5174: }
 5175: 
 5176: # ------------------------------------------------------ critical put interface
 5177: 
 5178: sub cput {
 5179:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5180:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5181:    if (!$uname) { $uname=$env{'user.name'}; }
 5182:    my $uhome=&homeserver($uname,$udomain);
 5183:    my $items='';
 5184:    foreach my $item (keys(%$storehash)) {
 5185:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5186:    }
 5187:    $items=~s/\&$//;
 5188:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 5189: }
 5190: 
 5191: # -------------------------------------------------------------- eget interface
 5192: 
 5193: sub eget {
 5194:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5195:    my $items='';
 5196:    foreach my $item (@$storearr) {
 5197:        $items.=&escape($item).'&';
 5198:    }
 5199:    $items=~s/\&$//;
 5200:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5201:    if (!$uname) { $uname=$env{'user.name'}; }
 5202:    my $uhome=&homeserver($uname,$udomain);
 5203:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 5204:    my @pairs=split(/\&/,$rep);
 5205:    my %returnhash=();
 5206:    my $i=0;
 5207:    foreach my $item (@$storearr) {
 5208:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 5209:       $i++;
 5210:    }
 5211:    return %returnhash;
 5212: }
 5213: 
 5214: # ------------------------------------------------------------ tmpput interface
 5215: sub tmpput {
 5216:     my ($storehash,$server,$context)=@_;
 5217:     my $items='';
 5218:     foreach my $item (keys(%$storehash)) {
 5219: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5220:     }
 5221:     $items=~s/\&$//;
 5222:     if (defined($context)) {
 5223:         $items .= ':'.&escape($context);
 5224:     }
 5225:     return &reply("tmpput:$items",$server);
 5226: }
 5227: 
 5228: # ------------------------------------------------------------ tmpget interface
 5229: sub tmpget {
 5230:     my ($token,$server)=@_;
 5231:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 5232:     my $rep=&reply("tmpget:$token",$server);
 5233:     my %returnhash;
 5234:     foreach my $item (split(/\&/,$rep)) {
 5235: 	my ($key,$value)=split(/=/,$item);
 5236:         next if ($key =~ /^error: 2 /);
 5237: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 5238:     }
 5239:     return %returnhash;
 5240: }
 5241: 
 5242: # ------------------------------------------------------------ tmpdel interface
 5243: sub tmpdel {
 5244:     my ($token,$server)=@_;
 5245:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 5246:     return &reply("tmpdel:$token",$server);
 5247: }
 5248: 
 5249: # -------------------------------------------------- portfolio access checking
 5250: 
 5251: sub portfolio_access {
 5252:     my ($requrl) = @_;
 5253:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 5254:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 5255:     if ($result) {
 5256:         my %setters;
 5257:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 5258:             my ($startblock,$endblock) =
 5259:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 5260:             if ($startblock && $endblock) {
 5261:                 return 'B';
 5262:             }
 5263:         } else {
 5264:             my ($startblock,$endblock) =
 5265:                 &Apache::loncommon::blockcheck(\%setters,'port');
 5266:             if ($startblock && $endblock) {
 5267:                 return 'B';
 5268:             }
 5269:         }
 5270:     }
 5271:     if ($result eq 'ok') {
 5272:        return 'F';
 5273:     } elsif ($result =~ /^[^:]+:guest_/) {
 5274:        return 'A';
 5275:     }
 5276:     return '';
 5277: }
 5278: 
 5279: sub get_portfolio_access {
 5280:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 5281: 
 5282:     if (!ref($access_hash)) {
 5283: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 5284: 	my %access_controls = &get_access_controls($current_perms,$group,
 5285: 						   $file_name);
 5286: 	$access_hash = $access_controls{$file_name};
 5287:     }
 5288: 
 5289:     my ($public,$guest,@domains,@users,@courses,@groups);
 5290:     my $now = time;
 5291:     if (ref($access_hash) eq 'HASH') {
 5292:         foreach my $key (keys(%{$access_hash})) {
 5293:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 5294:             if ($start > $now) {
 5295:                 next;
 5296:             }
 5297:             if ($end && $end<$now) {
 5298:                 next;
 5299:             }
 5300:             if ($scope eq 'public') {
 5301:                 $public = $key;
 5302:                 last;
 5303:             } elsif ($scope eq 'guest') {
 5304:                 $guest = $key;
 5305:             } elsif ($scope eq 'domains') {
 5306:                 push(@domains,$key);
 5307:             } elsif ($scope eq 'users') {
 5308:                 push(@users,$key);
 5309:             } elsif ($scope eq 'course') {
 5310:                 push(@courses,$key);
 5311:             } elsif ($scope eq 'group') {
 5312:                 push(@groups,$key);
 5313:             }
 5314:         }
 5315:         if ($public) {
 5316:             return 'ok';
 5317:         }
 5318:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 5319:             if ($guest) {
 5320:                 return $guest;
 5321:             }
 5322:         } else {
 5323:             if (@domains > 0) {
 5324:                 foreach my $domkey (@domains) {
 5325:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 5326:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 5327:                             return 'ok';
 5328:                         }
 5329:                     }
 5330:                 }
 5331:             }
 5332:             if (@users > 0) {
 5333:                 foreach my $userkey (@users) {
 5334:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 5335:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 5336:                             if (ref($item) eq 'HASH') {
 5337:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 5338:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 5339:                                     return 'ok';
 5340:                                 }
 5341:                             }
 5342:                         }
 5343:                     } 
 5344:                 }
 5345:             }
 5346:             my %roleshash;
 5347:             my @courses_and_groups = @courses;
 5348:             push(@courses_and_groups,@groups); 
 5349:             if (@courses_and_groups > 0) {
 5350:                 my (%allgroups,%allroles); 
 5351:                 my ($start,$end,$role,$sec,$group);
 5352:                 foreach my $envkey (%env) {
 5353:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 5354:                         my $cid = $2.'_'.$3; 
 5355:                         if ($1 eq 'gr') {
 5356:                             $group = $4;
 5357:                             $allgroups{$cid}{$group} = $env{$envkey};
 5358:                         } else {
 5359:                             if ($4 eq '') {
 5360:                                 $sec = 'none';
 5361:                             } else {
 5362:                                 $sec = $4;
 5363:                             }
 5364:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 5365:                         }
 5366:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 5367:                         my $cid = $2.'_'.$3;
 5368:                         if ($4 eq '') {
 5369:                             $sec = 'none';
 5370:                         } else {
 5371:                             $sec = $4;
 5372:                         }
 5373:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 5374:                     }
 5375:                 }
 5376:                 if (keys(%allroles) == 0) {
 5377:                     return;
 5378:                 }
 5379:                 foreach my $key (@courses_and_groups) {
 5380:                     my %content = %{$$access_hash{$key}};
 5381:                     my $cnum = $content{'number'};
 5382:                     my $cdom = $content{'domain'};
 5383:                     my $cid = $cdom.'_'.$cnum;
 5384:                     if (!exists($allroles{$cid})) {
 5385:                         next;
 5386:                     }    
 5387:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 5388:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 5389:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 5390:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 5391:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 5392:                         foreach my $role (keys(%{$allroles{$cid}})) {
 5393:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 5394:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 5395:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 5396:                                         if (grep/^all$/,@sections) {
 5397:                                             return 'ok';
 5398:                                         } else {
 5399:                                             if (grep/^$sec$/,@sections) {
 5400:                                                 return 'ok';
 5401:                                             }
 5402:                                         }
 5403:                                     }
 5404:                                 }
 5405:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 5406:                                     if (grep/^none$/,@groups) {
 5407:                                         return 'ok';
 5408:                                     }
 5409:                                 } else {
 5410:                                     if (grep/^all$/,@groups) {
 5411:                                         return 'ok';
 5412:                                     } 
 5413:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 5414:                                         if (grep/^$group$/,@groups) {
 5415:                                             return 'ok';
 5416:                                         }
 5417:                                     }
 5418:                                 } 
 5419:                             }
 5420:                         }
 5421:                     }
 5422:                 }
 5423:             }
 5424:             if ($guest) {
 5425:                 return $guest;
 5426:             }
 5427:         }
 5428:     }
 5429:     return;
 5430: }
 5431: 
 5432: sub course_group_datechecker {
 5433:     my ($dates,$now,$status) = @_;
 5434:     my ($start,$end) = split(/\./,$dates);
 5435:     if (!$start && !$end) {
 5436:         return 'ok';
 5437:     }
 5438:     if (grep/^active$/,@{$status}) {
 5439:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 5440:             return 'ok';
 5441:         }
 5442:     }
 5443:     if (grep/^previous$/,@{$status}) {
 5444:         if ($end > $now ) {
 5445:             return 'ok';
 5446:         }
 5447:     }
 5448:     if (grep/^future$/,@{$status}) {
 5449:         if ($start > $now) {
 5450:             return 'ok';
 5451:         }
 5452:     }
 5453:     return; 
 5454: }
 5455: 
 5456: sub parse_portfolio_url {
 5457:     my ($url) = @_;
 5458: 
 5459:     my ($type,$udom,$unum,$group,$file_name);
 5460:     
 5461:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 5462: 	$type = 1;
 5463:         $udom = $1;
 5464:         $unum = $2;
 5465:         $file_name = $3;
 5466:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 5467: 	$type = 2;
 5468:         $udom = $1;
 5469:         $unum = $2;
 5470:         $group = $3;
 5471:         $file_name = $3.'/'.$4;
 5472:     }
 5473:     if (wantarray) {
 5474: 	return ($type,$udom,$unum,$file_name,$group);
 5475:     }
 5476:     return $type;
 5477: }
 5478: 
 5479: sub is_portfolio_url {
 5480:     my ($url) = @_;
 5481:     return scalar(&parse_portfolio_url($url));
 5482: }
 5483: 
 5484: sub is_portfolio_file {
 5485:     my ($file) = @_;
 5486:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 5487:         return 1;
 5488:     }
 5489:     return;
 5490: }
 5491: 
 5492: sub usertools_access {
 5493:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 5494:     my ($access,%tools);
 5495:     if ($context eq '') {
 5496:         $context = 'tools';
 5497:     }
 5498:     if ($context eq 'requestcourses') {
 5499:         %tools = (
 5500:                       official   => 1,
 5501:                       unofficial => 1,
 5502:                       community  => 1,
 5503:                  );
 5504:     } else {
 5505:         %tools = (
 5506:                       aboutme   => 1,
 5507:                       blog      => 1,
 5508:                       portfolio => 1,
 5509:                  );
 5510:     }
 5511:     return if (!defined($tools{$tool}));
 5512: 
 5513:     if ((!defined($udom)) || (!defined($uname))) {
 5514:         $udom = $env{'user.domain'};
 5515:         $uname = $env{'user.name'};
 5516:     }
 5517: 
 5518:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 5519:         if ($action ne 'reload') {
 5520:             if ($context eq 'requestcourses') {
 5521:                 return $env{'environment.canrequest.'.$tool};
 5522:             } else {
 5523:                 return $env{'environment.availabletools.'.$tool};
 5524:             }
 5525:         }
 5526:     }
 5527: 
 5528:     my ($toolstatus,$inststatus);
 5529: 
 5530:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 5531:          ($action ne 'reload')) {
 5532:         $toolstatus = $env{'environment.'.$context.'.'.$tool};
 5533:         $inststatus = $env{'environment.inststatus'};
 5534:     } else {
 5535:         if (ref($userenvref) eq 'HASH') {
 5536:             $toolstatus = $userenvref->{$context.'.'.$tool};
 5537:             $inststatus = $userenvref->{'inststatus'};
 5538:         } else {
 5539:             my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
 5540:             $toolstatus = $userenv{$context.'.'.$tool};
 5541:             $inststatus = $userenv{'inststatus'};
 5542:         }
 5543:     }
 5544: 
 5545:     if ($toolstatus ne '') {
 5546:         if ($toolstatus) {
 5547:             $access = 1;
 5548:         } else {
 5549:             $access = 0;
 5550:         }
 5551:         return $access;
 5552:     }
 5553: 
 5554:     my ($is_adv,%domdef);
 5555:     if (ref($is_advref) eq 'HASH') {
 5556:         $is_adv = $is_advref->{'is_adv'};
 5557:     } else {
 5558:         $is_adv = &is_advanced_user($udom,$uname);
 5559:     }
 5560:     if (ref($domdefref) eq 'HASH') {
 5561:         %domdef = %{$domdefref};
 5562:     } else {
 5563:         %domdef = &get_domain_defaults($udom);
 5564:     }
 5565:     if (ref($domdef{$tool}) eq 'HASH') {
 5566:         if ($is_adv) {
 5567:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 5568:                 if ($domdef{$tool}{'_LC_adv'}) { 
 5569:                     $access = 1;
 5570:                 } else {
 5571:                     $access = 0;
 5572:                 }
 5573:                 return $access;
 5574:             }
 5575:         }
 5576:         if ($inststatus ne '') {
 5577:             my ($hasaccess,$hasnoaccess);
 5578:             foreach my $affiliation (split(/:/,$inststatus)) {
 5579:                 if ($domdef{$tool}{$affiliation} ne '') { 
 5580:                     if ($domdef{$tool}{$affiliation}) {
 5581:                         $hasaccess = 1;
 5582:                     } else {
 5583:                         $hasnoaccess = 1;
 5584:                     }
 5585:                 }
 5586:             }
 5587:             if ($hasaccess || $hasnoaccess) {
 5588:                 if ($hasaccess) {
 5589:                     $access = 1;
 5590:                 } elsif ($hasnoaccess) {
 5591:                     $access = 0; 
 5592:                 }
 5593:                 return $access;
 5594:             }
 5595:         } else {
 5596:             if ($domdef{$tool}{'default'} ne '') {
 5597:                 if ($domdef{$tool}{'default'}) {
 5598:                     $access = 1;
 5599:                 } elsif ($domdef{$tool}{'default'} == 0) {
 5600:                     $access = 0;
 5601:                 }
 5602:                 return $access;
 5603:             }
 5604:         }
 5605:     } else {
 5606:         if ($context eq 'tools') {
 5607:             $access = 1;
 5608:         } else {
 5609:             $access = 0;
 5610:         }
 5611:         return $access;
 5612:     }
 5613: }
 5614: 
 5615: sub is_course_owner {
 5616:     my ($cdom,$cnum,$udom,$uname) = @_;
 5617:     if (($udom eq '') || ($uname eq '')) {
 5618:         $udom = $env{'user.domain'};
 5619:         $uname = $env{'user.name'};
 5620:     }
 5621:     unless (($udom eq '') || ($uname eq '')) {
 5622:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 5623:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 5624:                 return 1;
 5625:             } else {
 5626:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 5627:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 5628:                     return 1;
 5629:                 }
 5630:             }
 5631:         }
 5632:     }
 5633:     return;
 5634: }
 5635: 
 5636: sub is_advanced_user {
 5637:     my ($udom,$uname) = @_;
 5638:     if ($udom ne '' && $uname ne '') {
 5639:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 5640:             if (wantarray) {
 5641:                 return ($env{'user.adv'},$env{'user.author'});
 5642:             } else {
 5643:                 return $env{'user.adv'};
 5644:             }
 5645:         }
 5646:     }
 5647:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 5648:     my %allroles;
 5649:     my ($is_adv,$is_author);
 5650:     foreach my $role (keys(%roleshash)) {
 5651:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 5652:         my $area = '/'.$tdomain.'/'.$trest;
 5653:         if ($sec ne '') {
 5654:             $area .= '/'.$sec;
 5655:         }
 5656:         if (($area ne '') && ($trole ne '')) {
 5657:             my $spec=$trole.'.'.$area;
 5658:             if ($trole =~ /^cr\//) {
 5659:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 5660:             } elsif ($trole ne 'gr') {
 5661:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 5662:             }
 5663:             if ($trole eq 'au') {
 5664:                 $is_author = 1;
 5665:             }
 5666:         }
 5667:     }
 5668:     foreach my $role (keys(%allroles)) {
 5669:         last if ($is_adv);
 5670:         foreach my $item (split(/:/,$allroles{$role})) {
 5671:             if ($item ne '') {
 5672:                 my ($privilege,$restrictions)=split(/&/,$item);
 5673:                 if ($privilege eq 'adv') {
 5674:                     $is_adv = 1;
 5675:                     last;
 5676:                 }
 5677:             }
 5678:         }
 5679:     }
 5680:     if (wantarray) {
 5681:         return ($is_adv,$is_author);
 5682:     }
 5683:     return $is_adv;
 5684: }
 5685: 
 5686: sub check_can_request {
 5687:     my ($dom,$can_request,$request_domains) = @_;
 5688:     my $canreq = 0;
 5689:     my ($types,$typename) = &Apache::loncommon::course_types();
 5690:     my @options = ('approval','validate','autolimit');
 5691:     my $optregex = join('|',@options);
 5692:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 5693:         foreach my $type (@{$types}) {
 5694:             if (&usertools_access($env{'user.name'},
 5695:                                   $env{'user.domain'},
 5696:                                   $type,undef,'requestcourses')) {
 5697:                 $canreq ++;
 5698:                 if (ref($request_domains) eq 'HASH') {
 5699:                     push(@{$request_domains->{$type}},$env{'user.domain'});
 5700:                 }
 5701:                 if ($dom eq $env{'user.domain'}) {
 5702:                     $can_request->{$type} = 1;
 5703:                 }
 5704:             }
 5705:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
 5706:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 5707:                 if (@curr > 0) {
 5708:                     foreach my $item (@curr) {
 5709:                         if (ref($request_domains) eq 'HASH') {
 5710:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 5711:                             if ($otherdom ne '') {
 5712:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 5713:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 5714:                                         push(@{$request_domains->{$type}},$otherdom);
 5715:                                     }
 5716:                                 } else {
 5717:                                     push(@{$request_domains->{$type}},$otherdom);
 5718:                                 }
 5719:                             }
 5720:                         }
 5721:                     }
 5722:                     unless($dom eq $env{'user.domain'}) {
 5723:                         $canreq ++;
 5724:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 5725:                             $can_request->{$type} = 1;
 5726:                         }
 5727:                     }
 5728:                 }
 5729:             }
 5730:         }
 5731:     }
 5732:     return $canreq;
 5733: }
 5734: 
 5735: # ---------------------------------------------- Custom access rule evaluation
 5736: 
 5737: sub customaccess {
 5738:     my ($priv,$uri)=@_;
 5739:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 5740:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 5741:     $udom = &LONCAPA::clean_domain($udom);
 5742:     $ucrs = &LONCAPA::clean_username($ucrs);
 5743:     my $access=0;
 5744:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 5745: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 5746: 	if ($type eq 'user') {
 5747: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 5748: 		my ($tdom,$tuname)=split(m{/},$scope);
 5749: 		if ($tdom) {
 5750: 		    if ($tdom ne $env{'user.domain'}) { next; }
 5751: 		}
 5752: 		if ($tuname) {
 5753: 		    if ($tuname ne $env{'user.name'}) { next; }
 5754: 		}
 5755: 		$access=($effect eq 'allow');
 5756: 		last;
 5757: 	    }
 5758: 	} else {
 5759: 	    if ($role) {
 5760: 		if ($role ne $urole) { next; }
 5761: 	    }
 5762: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 5763: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 5764: 		if ($tdom) {
 5765: 		    if ($tdom ne $udom) { next; }
 5766: 		}
 5767: 		if ($tcrs) {
 5768: 		    if ($tcrs ne $ucrs) { next; }
 5769: 		}
 5770: 		if ($tsec) {
 5771: 		    if ($tsec ne $usec) { next; }
 5772: 		}
 5773: 		$access=($effect eq 'allow');
 5774: 		last;
 5775: 	    }
 5776: 	    if ($realm eq '' && $role eq '') {
 5777: 		$access=($effect eq 'allow');
 5778: 	    }
 5779: 	}
 5780:     }
 5781:     return $access;
 5782: }
 5783: 
 5784: # ------------------------------------------------- Check for a user privilege
 5785: 
 5786: sub allowed {
 5787:     my ($priv,$uri,$symb,$role)=@_;
 5788:     my $ver_orguri=$uri;
 5789:     $uri=&deversion($uri);
 5790:     my $orguri=$uri;
 5791:     $uri=&declutter($uri);
 5792: 
 5793:     if ($priv eq 'evb') {
 5794: # Evade communication block restrictions for specified role in a course
 5795:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 5796:             return $1;
 5797:         } else {
 5798:             return;
 5799:         }
 5800:     }
 5801: 
 5802:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 5803: # Free bre access to adm and meta resources
 5804:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 5805: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 5806: 	&& ($priv eq 'bre')) {
 5807: 	return 'F';
 5808:     }
 5809: 
 5810: # Free bre access to user's own portfolio contents
 5811:     my ($space,$domain,$name,@dir)=split('/',$uri);
 5812:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 5813: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 5814:         my %setters;
 5815:         my ($startblock,$endblock) = 
 5816:             &Apache::loncommon::blockcheck(\%setters,'port');
 5817:         if ($startblock && $endblock) {
 5818:             return 'B';
 5819:         } else {
 5820:             return 'F';
 5821:         }
 5822:     }
 5823: 
 5824: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 5825:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 5826:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 5827:         if (exists($env{'request.course.id'})) {
 5828:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5829:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5830:             if (($domain eq $cdom) && ($name eq $cnum)) {
 5831:                 my $courseprivid=$env{'request.course.id'};
 5832:                 $courseprivid=~s/\_/\//;
 5833:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 5834:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 5835:                     return $1; 
 5836:                 } else {
 5837:                     if ($env{'request.course.sec'}) {
 5838:                         $courseprivid.='/'.$env{'request.course.sec'};
 5839:                     }
 5840:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 5841:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 5842:                         return $2;
 5843:                     }
 5844:                 }
 5845:             }
 5846:         }
 5847:     }
 5848: 
 5849: # Free bre to public access
 5850: 
 5851:     if ($priv eq 'bre') {
 5852:         my $copyright=&metadata($uri,'copyright');
 5853: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 5854:            return 'F'; 
 5855:         }
 5856:         if ($copyright eq 'priv') {
 5857:             $uri=~/([^\/]+)\/([^\/]+)\//;
 5858: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 5859: 		return '';
 5860:             }
 5861:         }
 5862:         if ($copyright eq 'domain') {
 5863:             $uri=~/([^\/]+)\/([^\/]+)\//;
 5864: 	    unless (($env{'user.domain'} eq $1) ||
 5865:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 5866: 		return '';
 5867:             }
 5868:         }
 5869:         if ($env{'request.role'}=~ /li\.\//) {
 5870:             # Library role, so allow browsing of resources in this domain.
 5871:             return 'F';
 5872:         }
 5873:         if ($copyright eq 'custom') {
 5874: 	    unless (&customaccess($priv,$uri)) { return ''; }
 5875:         }
 5876:     }
 5877:     # Domain coordinator is trying to create a course
 5878:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 5879:         # uri is the requested domain in this case.
 5880:         # comparison to 'request.role.domain' shows if the user has selected
 5881:         # a role of dc for the domain in question.
 5882:         return 'F' if ($uri eq $env{'request.role.domain'});
 5883:     }
 5884: 
 5885:     my $thisallowed='';
 5886:     my $statecond=0;
 5887:     my $courseprivid='';
 5888: 
 5889:     my $ownaccess;
 5890:     # Community Coordinator or Assistant Co-author browsing resource space.
 5891:     if (($priv eq 'bro') && ($env{'user.author'})) {
 5892:         if ($uri eq '') {
 5893:             $ownaccess = 1;
 5894:         } else {
 5895:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 5896:                 my $udom = $env{'user.domain'};
 5897:                 my $uname = $env{'user.name'};
 5898:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 5899:                     $ownaccess = 1;
 5900:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 5901:                     unless ($uri =~ m{\.\./}) {
 5902:                         $ownaccess = 1;
 5903:                     }
 5904:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 5905:                     my $now = time;
 5906:                     if ($uri =~ m{^([^/]+)/?$}) {
 5907:                         my $adom = $1;
 5908:                         foreach my $key (keys(%env)) {
 5909:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 5910:                                 my ($start,$end) = split('.',$env{$key});
 5911:                                 if (($now >= $start) && (!$end || $end < $now)) {
 5912:                                     $ownaccess = 1;
 5913:                                     last;
 5914:                                 }
 5915:                             }
 5916:                         }
 5917:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 5918:                         my $adom = $1;
 5919:                         my $aname = $2;
 5920:                         foreach my $role ('ca','aa') { 
 5921:                             if ($env{"user.role.$role./$adom/$aname"}) {
 5922:                                 my ($start,$end) =
 5923:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 5924:                                 if (($now >= $start) && (!$end || $end < $now)) {
 5925:                                     $ownaccess = 1;
 5926:                                     last;
 5927:                                 }
 5928:                             }
 5929:                         }
 5930:                     }
 5931:                 }
 5932:             }
 5933:         }
 5934:     }
 5935: 
 5936: # Course
 5937: 
 5938:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 5939:         unless (($priv eq 'bro') && (!$ownaccess)) {
 5940:             $thisallowed.=$1;
 5941:         }
 5942:     }
 5943: 
 5944: # Domain
 5945: 
 5946:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 5947:        =~/\Q$priv\E\&([^\:]*)/) {
 5948:         unless (($priv eq 'bro') && (!$ownaccess)) {
 5949:             $thisallowed.=$1;
 5950:         }
 5951:     }
 5952: 
 5953: # User who is not author or co-author might still be able to edit
 5954: # resource of an author in the domain (e.g., if Domain Coordinator).
 5955:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 5956:         (&allowed('mdc',$env{'request.course.id'}))) {
 5957:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 5958:             $thisallowed.=$1;
 5959:         }
 5960:     }
 5961: 
 5962: # Course: uri itself is a course
 5963:     my $courseuri=$uri;
 5964:     $courseuri=~s/\_(\d)/\/$1/;
 5965:     $courseuri=~s/^([^\/])/\/$1/;
 5966: 
 5967:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 5968:        =~/\Q$priv\E\&([^\:]*)/) {
 5969:         unless (($priv eq 'bro') && (!$ownaccess)) {
 5970:             $thisallowed.=$1;
 5971:         }
 5972:     }
 5973: 
 5974: # URI is an uploaded document for this course, default permissions don't matter
 5975: # not allowing 'edit' access (editupload) to uploaded course docs
 5976:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 5977: 	$thisallowed='';
 5978:         my ($match)=&is_on_map($uri);
 5979:         if ($match) {
 5980:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 5981:                   =~/\Q$priv\E\&([^\:]*)/) {
 5982:                 $thisallowed.=$1;
 5983:             }
 5984:         } else {
 5985:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 5986:             if ($refuri) {
 5987:                 if ($refuri =~ m|^/adm/|) {
 5988:                     $thisallowed='F';
 5989:                 } else {
 5990:                     $refuri=&declutter($refuri);
 5991:                     my ($match) = &is_on_map($refuri);
 5992:                     if ($match) {
 5993:                         $thisallowed='F';
 5994:                     }
 5995:                 }
 5996:             }
 5997:         }
 5998:     }
 5999: 
 6000:     if ($priv eq 'bre'
 6001: 	&& $thisallowed ne 'F' 
 6002: 	&& $thisallowed ne '2'
 6003: 	&& &is_portfolio_url($uri)) {
 6004: 	$thisallowed = &portfolio_access($uri);
 6005:     }
 6006:     
 6007: # Full access at system, domain or course-wide level? Exit.
 6008:     if ($thisallowed=~/F/) {
 6009: 	return 'F';
 6010:     }
 6011: 
 6012: # If this is generating or modifying users, exit with special codes
 6013: 
 6014:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 6015: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 6016: 	    my ($audom,$auname)=split('/',$uri);
 6017: # no author name given, so this just checks on the general right to make a co-author in this domain
 6018: 	    unless ($auname) { return $thisallowed; }
 6019: # an author name is given, so we are about to actually make a co-author for a certain account
 6020: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 6021: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 6022: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 6023: 	}
 6024: 	return $thisallowed;
 6025:     }
 6026: #
 6027: # Gathered so far: system, domain and course wide privileges
 6028: #
 6029: # Course: See if uri or referer is an individual resource that is part of 
 6030: # the course
 6031: 
 6032:     if ($env{'request.course.id'}) {
 6033: 
 6034:        $courseprivid=$env{'request.course.id'};
 6035:        if ($env{'request.course.sec'}) {
 6036:           $courseprivid.='/'.$env{'request.course.sec'};
 6037:        }
 6038:        $courseprivid=~s/\_/\//;
 6039:        my $checkreferer=1;
 6040:        my ($match,$cond)=&is_on_map($uri);
 6041:        if ($match) {
 6042:            $statecond=$cond;
 6043:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 6044:                =~/\Q$priv\E\&([^\:]*)/) {
 6045:                $thisallowed.=$1;
 6046:                $checkreferer=0;
 6047:            }
 6048:        }
 6049:        
 6050:        if ($checkreferer) {
 6051: 	  my $refuri=$env{'httpref.'.$orguri};
 6052:             unless ($refuri) {
 6053:                 foreach my $key (keys(%env)) {
 6054: 		    if ($key=~/^httpref\..*\*/) {
 6055: 			my $pattern=$key;
 6056:                         $pattern=~s/^httpref\.\/res\///;
 6057:                         $pattern=~s/\*/\[\^\/\]\+/g;
 6058:                         $pattern=~s/\//\\\//g;
 6059:                         if ($orguri=~/$pattern/) {
 6060: 			    $refuri=$env{$key};
 6061:                         }
 6062:                     }
 6063:                 }
 6064:             }
 6065: 
 6066:          if ($refuri) { 
 6067: 	  $refuri=&declutter($refuri);
 6068:           my ($match,$cond)=&is_on_map($refuri);
 6069:             if ($match) {
 6070:               my $refstatecond=$cond;
 6071:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 6072:                   =~/\Q$priv\E\&([^\:]*)/) {
 6073:                   $thisallowed.=$1;
 6074:                   $uri=$refuri;
 6075:                   $statecond=$refstatecond;
 6076:               }
 6077:           }
 6078:         }
 6079:        }
 6080:    }
 6081: 
 6082: #
 6083: # Gathered now: all privileges that could apply, and condition number
 6084: # 
 6085: #
 6086: # Full or no access?
 6087: #
 6088: 
 6089:     if ($thisallowed=~/F/) {
 6090: 	return 'F';
 6091:     }
 6092: 
 6093:     unless ($thisallowed) {
 6094:         return '';
 6095:     }
 6096: 
 6097: # Restrictions exist, deal with them
 6098: #
 6099: #   C:according to course preferences
 6100: #   R:according to resource settings
 6101: #   L:unless locked
 6102: #   X:according to user session state
 6103: #
 6104: 
 6105: # Possibly locked functionality, check all courses
 6106: # Locks might take effect only after 10 minutes cache expiration for other
 6107: # courses, and 2 minutes for current course
 6108: 
 6109:     my $envkey;
 6110:     if ($thisallowed=~/L/) {
 6111:         foreach $envkey (keys(%env)) {
 6112:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 6113:                my $courseid=$2;
 6114:                my $roleid=$1.'.'.$2;
 6115:                $courseid=~s/^\///;
 6116:                my $expiretime=600;
 6117:                if ($env{'request.role'} eq $roleid) {
 6118: 		  $expiretime=120;
 6119:                }
 6120: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 6121:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 6122:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 6123: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 6124:                }
 6125:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 6126:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 6127: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 6128:                        &log($env{'user.domain'},$env{'user.name'},
 6129:                             $env{'user.home'},
 6130:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 6131:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 6132:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 6133: 		       return '';
 6134:                    }
 6135:                }
 6136:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 6137:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 6138: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 6139:                        &log($env{'user.domain'},$env{'user.name'},
 6140:                             $env{'user.home'},
 6141:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 6142:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 6143:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 6144: 		       return '';
 6145:                    }
 6146:                }
 6147: 	   }
 6148:        }
 6149:     }
 6150:    
 6151: #
 6152: # Rest of the restrictions depend on selected course
 6153: #
 6154: 
 6155:     unless ($env{'request.course.id'}) {
 6156: 	if ($thisallowed eq 'A') {
 6157: 	    return 'A';
 6158:         } elsif ($thisallowed eq 'B') {
 6159:             return 'B';
 6160: 	} else {
 6161: 	    return '1';
 6162: 	}
 6163:     }
 6164: 
 6165: #
 6166: # Now user is definitely in a course
 6167: #
 6168: 
 6169: 
 6170: # Course preferences
 6171: 
 6172:    if ($thisallowed=~/C/) {
 6173:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 6174:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 6175:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 6176: 	   =~/\Q$rolecode\E/) {
 6177: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6178: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 6179: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 6180: 			$env{'request.course.id'});
 6181: 	   }
 6182:            return '';
 6183:        }
 6184: 
 6185:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 6186: 	   =~/\Q$unamedom\E/) {
 6187: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6188: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 6189: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 6190: 			$env{'request.course.id'});
 6191: 	   }
 6192:            return '';
 6193:        }
 6194:    }
 6195: 
 6196: # Resource preferences
 6197: 
 6198:    if ($thisallowed=~/R/) {
 6199:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 6200:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 6201: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6202: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 6203: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 6204: 	   }
 6205: 	   return '';
 6206:        }
 6207:    }
 6208: 
 6209: # Restricted by state or randomout?
 6210: 
 6211:    if ($thisallowed=~/X/) {
 6212:       if ($env{'acc.randomout'}) {
 6213: 	 if (!$symb) { $symb=&symbread($uri,1); }
 6214:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 6215:             return ''; 
 6216:          }
 6217:       }
 6218:       if (&condval($statecond)) {
 6219: 	 return '2';
 6220:       } else {
 6221:          return '';
 6222:       }
 6223:    }
 6224: 
 6225:     if ($thisallowed eq 'A') {
 6226: 	return 'A';
 6227:     } elsif ($thisallowed eq 'B') {
 6228:         return 'B';
 6229:     }
 6230:    return 'F';
 6231: }
 6232: #
 6233: #   Removes the versino from a URI and
 6234: #   splits it in to its filename and path to the filename.
 6235: #   Seems like File::Basename could have done this more clearly.
 6236: #   Parameters:
 6237: #      $uri   - input URI
 6238: #   Returns:
 6239: #     Two element list consisting of 
 6240: #     $pathname  - the URI up to and excluding the trailing /
 6241: #     $filename  - The part of the URI following the last /
 6242: #  NOTE:
 6243: #    Another realization of this is simply:
 6244: #    use File::Basename;
 6245: #    ...
 6246: #    $uri = shift;
 6247: #    $filename = basename($uri);
 6248: #    $path     = dirname($uri);
 6249: #    return ($filename, $path);
 6250: #
 6251: #     The implementation below is probably faster however.
 6252: #
 6253: sub split_uri_for_cond {
 6254:     my $uri=&deversion(&declutter(shift));
 6255:     my @uriparts=split(/\//,$uri);
 6256:     my $filename=pop(@uriparts);
 6257:     my $pathname=join('/',@uriparts);
 6258:     return ($pathname,$filename);
 6259: }
 6260: # --------------------------------------------------- Is a resource on the map?
 6261: 
 6262: sub is_on_map {
 6263:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 6264:     #Trying to find the conditional for the file
 6265:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 6266: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 6267:     if ($match) {
 6268: 	return (1,$1);
 6269:     } else {
 6270: 	return (0,0);
 6271:     }
 6272: }
 6273: 
 6274: # --------------------------------------------------------- Get symb from alias
 6275: 
 6276: sub get_symb_from_alias {
 6277:     my $symb=shift;
 6278:     my ($map,$resid,$url)=&decode_symb($symb);
 6279: # Already is a symb
 6280:     if ($url) { return $symb; }
 6281: # Must be an alias
 6282:     my $aliassymb='';
 6283:     my %bighash;
 6284:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6285:                             &GDBM_READER(),0640)) {
 6286:         my $rid=$bighash{'mapalias_'.$symb};
 6287: 	if ($rid) {
 6288: 	    my ($mapid,$resid)=split(/\./,$rid);
 6289: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 6290: 				    $resid,$bighash{'src_'.$rid});
 6291: 	}
 6292:         untie %bighash;
 6293:     }
 6294:     return $aliassymb;
 6295: }
 6296: 
 6297: # ----------------------------------------------------------------- Define Role
 6298: 
 6299: sub definerole {
 6300:   if (allowed('mcr','/')) {
 6301:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 6302:     foreach my $role (split(':',$sysrole)) {
 6303: 	my ($crole,$cqual)=split(/\&/,$role);
 6304:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 6305:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 6306: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 6307:                return "refused:s:$crole&$cqual"; 
 6308:             }
 6309:         }
 6310:     }
 6311:     foreach my $role (split(':',$domrole)) {
 6312: 	my ($crole,$cqual)=split(/\&/,$role);
 6313:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 6314:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 6315: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 6316:                return "refused:d:$crole&$cqual"; 
 6317:             }
 6318:         }
 6319:     }
 6320:     foreach my $role (split(':',$courole)) {
 6321: 	my ($crole,$cqual)=split(/\&/,$role);
 6322:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 6323:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 6324: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 6325:                return "refused:c:$crole&$cqual"; 
 6326:             }
 6327:         }
 6328:     }
 6329:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 6330:                 "$env{'user.domain'}:$env{'user.name'}:".
 6331: 	        "rolesdef_$rolename=".
 6332:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 6333:     return reply($command,$env{'user.home'});
 6334:   } else {
 6335:     return 'refused';
 6336:   }
 6337: }
 6338: 
 6339: # ---------------- Make a metadata query against the network of library servers
 6340: 
 6341: sub metadata_query {
 6342:     my ($query,$custom,$customshow,$server_array)=@_;
 6343:     my %rhash;
 6344:     my %libserv = &all_library();
 6345:     my @server_list = (defined($server_array) ? @$server_array
 6346:                                               : keys(%libserv) );
 6347:     for my $server (@server_list) {
 6348: 	unless ($custom or $customshow) {
 6349: 	    my $reply=&reply("querysend:".&escape($query),$server);
 6350: 	    $rhash{$server}=$reply;
 6351: 	}
 6352: 	else {
 6353: 	    my $reply=&reply("querysend:".&escape($query).':'.
 6354: 			     &escape($custom).':'.&escape($customshow),
 6355: 			     $server);
 6356: 	    $rhash{$server}=$reply;
 6357: 	}
 6358:     }
 6359:     return \%rhash;
 6360: }
 6361: 
 6362: # ----------------------------------------- Send log queries and wait for reply
 6363: 
 6364: sub log_query {
 6365:     my ($uname,$udom,$query,%filters)=@_;
 6366:     my $uhome=&homeserver($uname,$udom);
 6367:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 6368:     my $uhost=&hostname($uhome);
 6369:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 6370:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 6371:                        $uhome);
 6372:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 6373:     return get_query_reply($queryid);
 6374: }
 6375: 
 6376: # -------------------------- Update MySQL table for portfolio file
 6377: 
 6378: sub update_portfolio_table {
 6379:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 6380:     if ($group ne '') {
 6381:         $file_name =~s /^\Q$group\E//;
 6382:     }
 6383:     my $homeserver = &homeserver($uname,$udom);
 6384:     my $queryid=
 6385:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 6386:                ':'.&escape($file_name).':'.$action,$homeserver);
 6387:     my $reply = &get_query_reply($queryid);
 6388:     return $reply;
 6389: }
 6390: 
 6391: # -------------------------- Update MySQL allusers table
 6392: 
 6393: sub update_allusers_table {
 6394:     my ($uname,$udom,$names) = @_;
 6395:     my $homeserver = &homeserver($uname,$udom);
 6396:     my $queryid=
 6397:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 6398:                'lastname='.&escape($names->{'lastname'}).'%%'.
 6399:                'firstname='.&escape($names->{'firstname'}).'%%'.
 6400:                'middlename='.&escape($names->{'middlename'}).'%%'.
 6401:                'generation='.&escape($names->{'generation'}).'%%'.
 6402:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 6403:                'id='.&escape($names->{'id'}),$homeserver);
 6404:     return;
 6405: }
 6406: 
 6407: # ------- Request retrieval of institutional classlists for course(s)
 6408: 
 6409: sub fetch_enrollment_query {
 6410:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 6411:     my $homeserver;
 6412:     my $maxtries = 1;
 6413:     if ($context eq 'automated') {
 6414:         $homeserver = $perlvar{'lonHostID'};
 6415:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 6416:     } else {
 6417:         $homeserver = &homeserver($cnum,$dom);
 6418:     }
 6419:     my $host=&hostname($homeserver);
 6420:     my $cmd = '';
 6421:     foreach my $affiliate (keys(%{$affiliatesref})) {
 6422:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 6423:     }
 6424:     $cmd =~ s/%%$//;
 6425:     $cmd = &escape($cmd);
 6426:     my $query = 'fetchenrollment';
 6427:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 6428:     unless ($queryid=~/^\Q$host\E\_/) { 
 6429:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 6430:         return 'error: '.$queryid;
 6431:     }
 6432:     my $reply = &get_query_reply($queryid);
 6433:     my $tries = 1;
 6434:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 6435:         $reply = &get_query_reply($queryid);
 6436:         $tries ++;
 6437:     }
 6438:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 6439:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 6440:     } else {
 6441:         my @responses = split(/:/,$reply);
 6442:         if ($homeserver eq $perlvar{'lonHostID'}) {
 6443:             foreach my $line (@responses) {
 6444:                 my ($key,$value) = split(/=/,$line,2);
 6445:                 $$replyref{$key} = $value;
 6446:             }
 6447:         } else {
 6448:             my $pathname = LONCAPA::tempdir();
 6449:             foreach my $line (@responses) {
 6450:                 my ($key,$value) = split(/=/,$line);
 6451:                 $$replyref{$key} = $value;
 6452:                 if ($value > 0) {
 6453:                     foreach my $item (@{$$affiliatesref{$key}}) {
 6454:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 6455:                         my $destname = $pathname.'/'.$filename;
 6456:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 6457:                         if ($xml_classlist =~ /^error/) {
 6458:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 6459:                         } else {
 6460:                             if ( open(FILE,">$destname") ) {
 6461:                                 print FILE &unescape($xml_classlist);
 6462:                                 close(FILE);
 6463:                             } else {
 6464:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 6465:                             }
 6466:                         }
 6467:                     }
 6468:                 }
 6469:             }
 6470:         }
 6471:         return 'ok';
 6472:     }
 6473:     return 'error';
 6474: }
 6475: 
 6476: sub get_query_reply {
 6477:     my $queryid=shift;
 6478:     my $replyfile=LONCAPA::tempdir().$queryid;
 6479:     my $reply='';
 6480:     for (1..100) {
 6481: 	sleep 2;
 6482:         if (-e $replyfile.'.end') {
 6483: 	    if (open(my $fh,$replyfile)) {
 6484: 		$reply = join('',<$fh>);
 6485: 		close($fh);
 6486: 	   } else { return 'error: reply_file_error'; }
 6487:            return &unescape($reply);
 6488: 	}
 6489:     }
 6490:     return 'timeout:'.$queryid;
 6491: }
 6492: 
 6493: sub courselog_query {
 6494: #
 6495: # possible filters:
 6496: # url: url or symb
 6497: # username
 6498: # domain
 6499: # action: view, submit, grade
 6500: # start: timestamp
 6501: # end: timestamp
 6502: #
 6503:     my (%filters)=@_;
 6504:     unless ($env{'request.course.id'}) { return 'no_course'; }
 6505:     if ($filters{'url'}) {
 6506: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 6507:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 6508:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 6509:     }
 6510:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6511:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6512:     return &log_query($cname,$cdom,'courselog',%filters);
 6513: }
 6514: 
 6515: sub userlog_query {
 6516: #
 6517: # possible filters:
 6518: # action: log check role
 6519: # start: timestamp
 6520: # end: timestamp
 6521: #
 6522:     my ($uname,$udom,%filters)=@_;
 6523:     return &log_query($uname,$udom,'userlog',%filters);
 6524: }
 6525: 
 6526: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 6527: 
 6528: sub auto_run {
 6529:     my ($cnum,$cdom) = @_;
 6530:     my $response = 0;
 6531:     my $settings;
 6532:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 6533:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 6534:         $settings = $domconfig{'autoenroll'};
 6535:         if ($settings->{'run'} eq '1') {
 6536:             $response = 1;
 6537:         }
 6538:     } else {
 6539:         my $homeserver;
 6540:         if (&is_course($cdom,$cnum)) {
 6541:             $homeserver = &homeserver($cnum,$cdom);
 6542:         } else {
 6543:             $homeserver = &domain($cdom,'primary');
 6544:         }
 6545:         if ($homeserver ne 'no_host') {
 6546:             $response = &reply('autorun:'.$cdom,$homeserver);
 6547:         }
 6548:     }
 6549:     return $response;
 6550: }
 6551: 
 6552: sub auto_get_sections {
 6553:     my ($cnum,$cdom,$inst_coursecode) = @_;
 6554:     my $homeserver;
 6555:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 6556:         $homeserver = &homeserver($cnum,$cdom);
 6557:     }
 6558:     if (!defined($homeserver)) { 
 6559:         if ($cdom =~ /^$match_domain$/) {
 6560:             $homeserver = &domain($cdom,'primary');
 6561:         }
 6562:     }
 6563:     my @secs;
 6564:     if (defined($homeserver)) {
 6565:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 6566:         unless ($response eq 'refused') {
 6567:             @secs = split(/:/,$response);
 6568:         }
 6569:     }
 6570:     return @secs;
 6571: }
 6572: 
 6573: sub auto_new_course {
 6574:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 6575:     my $homeserver = &homeserver($cnum,$cdom);
 6576:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 6577:     return $response;
 6578: }
 6579: 
 6580: sub auto_validate_courseID {
 6581:     my ($cnum,$cdom,$inst_course_id) = @_;
 6582:     my $homeserver = &homeserver($cnum,$cdom);
 6583:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 6584:     return $response;
 6585: }
 6586: 
 6587: sub auto_validate_instcode {
 6588:     my ($cnum,$cdom,$instcode,$owner) = @_;
 6589:     my ($homeserver,$response);
 6590:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 6591:         $homeserver = &homeserver($cnum,$cdom);
 6592:     }
 6593:     if (!defined($homeserver)) {
 6594:         if ($cdom =~ /^$match_domain$/) {
 6595:             $homeserver = &domain($cdom,'primary');
 6596:         }
 6597:     }
 6598:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 6599:                         &escape($instcode).':'.&escape($owner),$homeserver));
 6600:     my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
 6601:     return ($outcome,$description);
 6602: }
 6603: 
 6604: sub auto_create_password {
 6605:     my ($cnum,$cdom,$authparam,$udom) = @_;
 6606:     my ($homeserver,$response);
 6607:     my $create_passwd = 0;
 6608:     my $authchk = '';
 6609:     if ($udom =~ /^$match_domain$/) {
 6610:         $homeserver = &domain($udom,'primary');
 6611:     }
 6612:     if ($homeserver eq '') {
 6613:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 6614:             $homeserver = &homeserver($cnum,$cdom);
 6615:         }
 6616:     }
 6617:     if ($homeserver eq '') {
 6618:         $authchk = 'nodomain';
 6619:     } else {
 6620:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 6621:         if ($response eq 'refused') {
 6622:             $authchk = 'refused';
 6623:         } else {
 6624:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 6625:         }
 6626:     }
 6627:     return ($authparam,$create_passwd,$authchk);
 6628: }
 6629: 
 6630: sub auto_photo_permission {
 6631:     my ($cnum,$cdom,$students) = @_;
 6632:     my $homeserver = &homeserver($cnum,$cdom);
 6633:     my ($outcome,$perm_reqd,$conditions) = 
 6634: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 6635:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 6636: 	return (undef,undef);
 6637:     }
 6638:     return ($outcome,$perm_reqd,$conditions);
 6639: }
 6640: 
 6641: sub auto_checkphotos {
 6642:     my ($uname,$udom,$pid) = @_;
 6643:     my $homeserver = &homeserver($uname,$udom);
 6644:     my ($result,$resulttype);
 6645:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 6646: 				   &escape($uname).':'.&escape($pid),
 6647: 				   $homeserver));
 6648:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 6649: 	return (undef,undef);
 6650:     }
 6651:     if ($outcome) {
 6652:         ($result,$resulttype) = split(/:/,$outcome);
 6653:     } 
 6654:     return ($result,$resulttype);
 6655: }
 6656: 
 6657: sub auto_photochoice {
 6658:     my ($cnum,$cdom) = @_;
 6659:     my $homeserver = &homeserver($cnum,$cdom);
 6660:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 6661: 						       &escape($cdom),
 6662: 						       $homeserver)));
 6663:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 6664: 	return (undef,undef);
 6665:     }
 6666:     return ($update,$comment);
 6667: }
 6668: 
 6669: sub auto_photoupdate {
 6670:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 6671:     my $homeserver = &homeserver($cnum,$dom);
 6672:     my $host=&hostname($homeserver);
 6673:     my $cmd = '';
 6674:     my $maxtries = 1;
 6675:     foreach my $affiliate (keys(%{$affiliatesref})) {
 6676:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 6677:     }
 6678:     $cmd =~ s/%%$//;
 6679:     $cmd = &escape($cmd);
 6680:     my $query = 'institutionalphotos';
 6681:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 6682:     unless ($queryid=~/^\Q$host\E\_/) {
 6683:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 6684:         return 'error: '.$queryid;
 6685:     }
 6686:     my $reply = &get_query_reply($queryid);
 6687:     my $tries = 1;
 6688:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 6689:         $reply = &get_query_reply($queryid);
 6690:         $tries ++;
 6691:     }
 6692:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 6693:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 6694:     } else {
 6695:         my @responses = split(/:/,$reply);
 6696:         my $outcome = shift(@responses); 
 6697:         foreach my $item (@responses) {
 6698:             my ($key,$value) = split(/=/,$item);
 6699:             $$photo{$key} = $value;
 6700:         }
 6701:         return $outcome;
 6702:     }
 6703:     return 'error';
 6704: }
 6705: 
 6706: sub auto_instcode_format {
 6707:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 6708: 	$cat_order) = @_;
 6709:     my $courses = '';
 6710:     my @homeservers;
 6711:     if ($caller eq 'global') {
 6712: 	my %servers = &get_servers($codedom,'library');
 6713: 	foreach my $tryserver (keys(%servers)) {
 6714: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 6715: 		push(@homeservers,$tryserver);
 6716: 	    }
 6717:         }
 6718:     } elsif ($caller eq 'requests') {
 6719:         if ($codedom =~ /^$match_domain$/) {
 6720:             my $chome = &domain($codedom,'primary');
 6721:             unless ($chome eq 'no_host') {
 6722:                 push(@homeservers,$chome);
 6723:             }
 6724:         }
 6725:     } else {
 6726:         push(@homeservers,&homeserver($caller,$codedom));
 6727:     }
 6728:     foreach my $code (keys(%{$instcodes})) {
 6729:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 6730:     }
 6731:     chop($courses);
 6732:     my $ok_response = 0;
 6733:     my $response;
 6734:     while (@homeservers > 0 && $ok_response == 0) {
 6735:         my $server = shift(@homeservers); 
 6736:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 6737:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 6738:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 6739: 		split(/:/,$response);
 6740:             %{$codes} = (%{$codes},&str2hash($codes_str));
 6741:             push(@{$codetitles},&str2array($codetitles_str));
 6742:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 6743:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 6744:             $ok_response = 1;
 6745:         }
 6746:     }
 6747:     if ($ok_response) {
 6748:         return 'ok';
 6749:     } else {
 6750:         return $response;
 6751:     }
 6752: }
 6753: 
 6754: sub auto_instcode_defaults {
 6755:     my ($domain,$returnhash,$code_order) = @_;
 6756:     my @homeservers;
 6757: 
 6758:     my %servers = &get_servers($domain,'library');
 6759:     foreach my $tryserver (keys(%servers)) {
 6760: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 6761: 	    push(@homeservers,$tryserver);
 6762: 	}
 6763:     }
 6764: 
 6765:     my $response;
 6766:     foreach my $server (@homeservers) {
 6767:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 6768:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 6769: 	
 6770: 	foreach my $pair (split(/\&/,$response)) {
 6771: 	    my ($name,$value)=split(/\=/,$pair);
 6772: 	    if ($name eq 'code_order') {
 6773: 		@{$code_order} = split(/\&/,&unescape($value));
 6774: 	    } else {
 6775: 		$returnhash->{&unescape($name)}=&unescape($value);
 6776: 	    }
 6777: 	}
 6778: 	return 'ok';
 6779:     }
 6780: 
 6781:     return $response;
 6782: }
 6783: 
 6784: sub auto_possible_instcodes {
 6785:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 6786:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 6787:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 6788:         return;
 6789:     }
 6790:     my (@homeservers,$uhome);
 6791:     if (defined(&domain($domain,'primary'))) {
 6792:         $uhome=&domain($domain,'primary');
 6793:         push(@homeservers,&domain($domain,'primary'));
 6794:     } else {
 6795:         my %servers = &get_servers($domain,'library');
 6796:         foreach my $tryserver (keys(%servers)) {
 6797:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 6798:                 push(@homeservers,$tryserver);
 6799:             }
 6800:         }
 6801:     }
 6802:     my $response;
 6803:     foreach my $server (@homeservers) {
 6804:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 6805:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 6806:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 6807:             split(':',$response);
 6808:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 6809:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 6810:         foreach my $item (split('&',$cat_title)) {   
 6811:             my ($name,$value)=split('=',$item);
 6812:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 6813:         }
 6814:         foreach my $item (split('&',$cat_order)) {
 6815:             my ($name,$value)=split('=',$item);
 6816:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 6817:         }
 6818:         return 'ok';
 6819:     }
 6820:     return $response;
 6821: }
 6822: 
 6823: sub auto_courserequest_checks {
 6824:     my ($dom) = @_;
 6825:     my ($homeserver,%validations);
 6826:     if ($dom =~ /^$match_domain$/) {
 6827:         $homeserver = &domain($dom,'primary');
 6828:     }
 6829:     unless ($homeserver eq 'no_host') {
 6830:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 6831:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 6832:             my @items = split(/&/,$response);
 6833:             foreach my $item (@items) {
 6834:                 my ($key,$value) = split('=',$item);
 6835:                 $validations{&unescape($key)} = &thaw_unescape($value);
 6836:             }
 6837:         }
 6838:     }
 6839:     return %validations; 
 6840: }
 6841: 
 6842: sub auto_courserequest_validation {
 6843:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
 6844:     my ($homeserver,$response);
 6845:     if ($dom =~ /^$match_domain$/) {
 6846:         $homeserver = &domain($dom,'primary');
 6847:     }
 6848:     unless ($homeserver eq 'no_host') {  
 6849:           
 6850:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 6851:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 6852:                                     ':'.&escape($instcode).':'.&escape($instseclist),
 6853:                                     $homeserver));
 6854:     }
 6855:     return $response;
 6856: }
 6857: 
 6858: sub auto_validate_class_sec {
 6859:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 6860:     my $homeserver = &homeserver($cnum,$cdom);
 6861:     my $ownerlist;
 6862:     if (ref($owners) eq 'ARRAY') {
 6863:         $ownerlist = join(',',@{$owners});
 6864:     } else {
 6865:         $ownerlist = $owners;
 6866:     }
 6867:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 6868:                         &escape($ownerlist).':'.$cdom,$homeserver);
 6869:     return $response;
 6870: }
 6871: 
 6872: # ------------------------------------------------------- Course Group routines
 6873: 
 6874: sub get_coursegroups {
 6875:     my ($cdom,$cnum,$group,$namespace) = @_;
 6876:     return(&dump($namespace,$cdom,$cnum,$group));
 6877: }
 6878: 
 6879: sub modify_coursegroup {
 6880:     my ($cdom,$cnum,$groupsettings) = @_;
 6881:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 6882: }
 6883: 
 6884: sub toggle_coursegroup_status {
 6885:     my ($cdom,$cnum,$group,$action) = @_;
 6886:     my ($from_namespace,$to_namespace);
 6887:     if ($action eq 'delete') {
 6888:         $from_namespace = 'coursegroups';
 6889:         $to_namespace = 'deleted_groups';
 6890:     } else {
 6891:         $from_namespace = 'deleted_groups';
 6892:         $to_namespace = 'coursegroups';
 6893:     }
 6894:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 6895:     if (my $tmp = &error(%curr_group)) {
 6896:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 6897:         return ('read error',$tmp);
 6898:     } else {
 6899:         my %savedsettings = %curr_group; 
 6900:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 6901:         my $deloutcome;
 6902:         if ($result eq 'ok') {
 6903:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 6904:         } else {
 6905:             return ('write error',$result);
 6906:         }
 6907:         if ($deloutcome eq 'ok') {
 6908:             return 'ok';
 6909:         } else {
 6910:             return ('delete error',$deloutcome);
 6911:         }
 6912:     }
 6913: }
 6914: 
 6915: sub modify_group_roles {
 6916:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 6917:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 6918:     my $role = 'gr/'.&escape($userprivs);
 6919:     my ($uname,$udom) = split(/:/,$user);
 6920:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 6921:     if ($result eq 'ok') {
 6922:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 6923:     }
 6924:     return $result;
 6925: }
 6926: 
 6927: sub modify_coursegroup_membership {
 6928:     my ($cdom,$cnum,$membership) = @_;
 6929:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 6930:     return $result;
 6931: }
 6932: 
 6933: sub get_active_groups {
 6934:     my ($udom,$uname,$cdom,$cnum) = @_;
 6935:     my $now = time;
 6936:     my %groups = ();
 6937:     foreach my $key (keys(%env)) {
 6938:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 6939:             my ($start,$end) = split(/\./,$env{$key});
 6940:             if (($end!=0) && ($end<$now)) { next; }
 6941:             if (($start!=0) && ($start>$now)) { next; }
 6942:             if ($1 eq $cdom && $2 eq $cnum) {
 6943:                 $groups{$3} = $env{$key} ;
 6944:             }
 6945:         }
 6946:     }
 6947:     return %groups;
 6948: }
 6949: 
 6950: sub get_group_membership {
 6951:     my ($cdom,$cnum,$group) = @_;
 6952:     return(&dump('groupmembership',$cdom,$cnum,$group));
 6953: }
 6954: 
 6955: sub get_users_groups {
 6956:     my ($udom,$uname,$courseid) = @_;
 6957:     my @usersgroups;
 6958:     my $cachetime=1800;
 6959: 
 6960:     my $hashid="$udom:$uname:$courseid";
 6961:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 6962:     if (defined($cached)) {
 6963:         @usersgroups = split(/:/,$grouplist);
 6964:     } else {  
 6965:         $grouplist = '';
 6966:         my $courseurl = &courseid_to_courseurl($courseid);
 6967:         my $extra = &freeze_escape({'skipcheck' => 1});
 6968:         my %roleshash = &dump('roles',$udom,$uname,$courseurl,undef,$extra);
 6969:         my $access_end = $env{'course.'.$courseid.
 6970:                               '.default_enrollment_end_date'};
 6971:         my $now = time;
 6972:         foreach my $key (keys(%roleshash)) {
 6973:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 6974:                 my $group = $1;
 6975:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 6976:                     my $start = $2;
 6977:                     my $end = $1;
 6978:                     if ($start == -1) { next; } # deleted from group
 6979:                     if (($start!=0) && ($start>$now)) { next; }
 6980:                     if (($end!=0) && ($end<$now)) {
 6981:                         if ($access_end && $access_end < $now) {
 6982:                             if ($access_end - $end < 86400) {
 6983:                                 push(@usersgroups,$group);
 6984:                             }
 6985:                         }
 6986:                         next;
 6987:                     }
 6988:                     push(@usersgroups,$group);
 6989:                 }
 6990:             }
 6991:         }
 6992:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 6993:         $grouplist = join(':',@usersgroups);
 6994:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 6995:     }
 6996:     return @usersgroups;
 6997: }
 6998: 
 6999: sub devalidate_getgroups_cache {
 7000:     my ($udom,$uname,$cdom,$cnum)=@_;
 7001:     my $courseid = $cdom.'_'.$cnum;
 7002: 
 7003:     my $hashid="$udom:$uname:$courseid";
 7004:     &devalidate_cache_new('getgroups',$hashid);
 7005: }
 7006: 
 7007: # ------------------------------------------------------------------ Plain Text
 7008: 
 7009: sub plaintext {
 7010:     my ($short,$type,$cid,$forcedefault) = @_;
 7011:     if ($short =~ m{^cr/}) {
 7012: 	return (split('/',$short))[-1];
 7013:     }
 7014:     if (!defined($cid)) {
 7015:         $cid = $env{'request.course.id'};
 7016:     }
 7017:     my %rolenames = (
 7018:                       Course    => 'std',
 7019:                       Community => 'alt1',
 7020:                     );
 7021:     if ($cid ne '') {
 7022:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 7023:             unless ($forcedefault) {
 7024:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 7025:                 &Apache::lonlocal::mt_escape(\$roletext);
 7026:                 return &Apache::lonlocal::mt($roletext);
 7027:             }
 7028:         }
 7029:     }
 7030:     if ((defined($type)) && (defined($rolenames{$type})) &&
 7031:         (defined($rolenames{$type})) && 
 7032:         (defined($prp{$short}{$rolenames{$type}}))) {
 7033:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 7034:     } elsif ($cid ne '') {
 7035:         my $crstype = $env{'course.'.$cid.'.type'};
 7036:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
 7037:             (defined($prp{$short}{$rolenames{$crstype}}))) {
 7038:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
 7039:         }
 7040:     }
 7041:     return &Apache::lonlocal::mt($prp{$short}{'std'});
 7042: }
 7043: 
 7044: # ----------------------------------------------------------------- Assign Role
 7045: 
 7046: sub assignrole {
 7047:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 7048:         $context)=@_;
 7049:     my $mrole;
 7050:     if ($role =~ /^cr\//) {
 7051:         my $cwosec=$url;
 7052:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 7053: 	unless (&allowed('ccr',$cwosec)) {
 7054:            my $refused = 1;
 7055:            if ($context eq 'requestcourses') {
 7056:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 7057:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
 7058:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
 7059:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 7060:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 7061:                            if ($crsenv{'internal.courseowner'} eq
 7062:                                $env{'user.name'}.':'.$env{'user.domain'}) {
 7063:                                $refused = '';
 7064:                            }
 7065:                        }
 7066:                    }
 7067:                }
 7068:            }
 7069:            if ($refused) {
 7070:                &logthis('Refused custom assignrole: '.
 7071:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
 7072:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
 7073:                return 'refused';
 7074:            }
 7075:         }
 7076:         $mrole='cr';
 7077:     } elsif ($role =~ /^gr\//) {
 7078:         my $cwogrp=$url;
 7079:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 7080:         unless (&allowed('mdg',$cwogrp)) {
 7081:             &logthis('Refused group assignrole: '.
 7082:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 7083:                     $env{'user.name'}.' at '.$env{'user.domain'});
 7084:             return 'refused';
 7085:         }
 7086:         $mrole='gr';
 7087:     } else {
 7088:         my $cwosec=$url;
 7089:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 7090:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 7091:             my $refused;
 7092:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 7093:                 if (!(&allowed('c'.$role,$url))) {
 7094:                     $refused = 1;
 7095:                 }
 7096:             } else {
 7097:                 $refused = 1;
 7098:             }
 7099:             if ($refused) {
 7100:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 7101:                 if (!$selfenroll && $context eq 'course') {
 7102:                     my %crsenv;
 7103:                     if ($role eq 'cc' || $role eq 'co') {
 7104:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 7105:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
 7106:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
 7107:                                 if ($crsenv{'internal.courseowner'} eq 
 7108:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 7109:                                     $refused = '';
 7110:                                 }
 7111:                             }
 7112:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
 7113:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
 7114:                                 if ($crsenv{'internal.courseowner'} eq 
 7115:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 7116:                                     $refused = '';
 7117:                                 }
 7118:                             }
 7119:                         }
 7120:                     }
 7121:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7122:                     $refused = '';
 7123:                 } elsif ($context eq 'requestcourses') {
 7124:                     my @possroles = ('st','ta','ep','in','cc','co');
 7125:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
 7126:                         my $wrongcc;
 7127:                         if ($cnum =~ /^$match_community$/) {
 7128:                             $wrongcc = 1 if ($role eq 'cc');
 7129:                         } else {
 7130:                             $wrongcc = 1 if ($role eq 'co');
 7131:                         }
 7132:                         unless ($wrongcc) {
 7133:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 7134:                             if ($crsenv{'internal.courseowner'} eq 
 7135:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
 7136:                                 $refused = '';
 7137:                             }
 7138:                         }
 7139:                     }
 7140:                 }
 7141:                 if ($refused) {
 7142:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 7143:                              ' '.$role.' '.$end.' '.$start.' by '.
 7144: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 7145:                     return 'refused';
 7146:                 }
 7147:             }
 7148:         } elsif ($role eq 'au') {
 7149:             if ($url ne '/'.$udom.'/') {
 7150:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
 7151:                          ' to assign author role for '.$uname.':'.$udom.
 7152:                          ' in domain: '.$url.' refused (wrong domain).');
 7153:                 return 'refused';
 7154:             }
 7155:         }
 7156:         $mrole=$role;
 7157:     }
 7158:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 7159:                 "$udom:$uname:$url".'_'."$mrole=$role";
 7160:     if ($end) { $command.='_'.$end; }
 7161:     if ($start) {
 7162: 	if ($end) { 
 7163:            $command.='_'.$start; 
 7164:         } else {
 7165:            $command.='_0_'.$start;
 7166:         }
 7167:     }
 7168:     my $origstart = $start;
 7169:     my $origend = $end;
 7170:     my $delflag;
 7171: # actually delete
 7172:     if ($deleteflag) {
 7173: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 7174: # modify command to delete the role
 7175:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 7176:                 "$udom:$uname:$url".'_'."$mrole";
 7177: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 7178: # set start and finish to negative values for userrolelog
 7179:            $start=-1;
 7180:            $end=-1;
 7181:            $delflag = 1;
 7182:         }
 7183:     }
 7184: # send command
 7185:     my $answer=&reply($command,&homeserver($uname,$udom));
 7186: # log new user role if status is ok
 7187:     if ($answer eq 'ok') {
 7188: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 7189: # for course roles, perform group memberships changes triggered by role change.
 7190:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
 7191:         unless ($role =~ /^gr/) {
 7192:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 7193:                                              $origstart,$selfenroll,$context);
 7194:         }
 7195:         if ($role eq 'cc') {
 7196:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
 7197:         }
 7198:     }
 7199:     return $answer;
 7200: }
 7201: 
 7202: sub autoupdate_coowners {
 7203:     my ($url,$end,$start,$uname,$udom) = @_;
 7204:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
 7205:     if (($cdom ne '') && ($cnum ne '')) {
 7206:         my $now = time;
 7207:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
 7208:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
 7209:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
 7210:             my $instcode = $coursehash{'internal.coursecode'};
 7211:             if ($instcode ne '') {
 7212:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
 7213:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
 7214:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
 7215:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
 7216:                         if ($result eq 'valid') {
 7217:                             if ($coursehash{'internal.co-owners'}) {
 7218:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 7219:                                     push(@newcoowners,$coowner);
 7220:                                 }
 7221:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
 7222:                                     push(@newcoowners,$uname.':'.$udom);
 7223:                                 }
 7224:                                 @newcoowners = sort(@newcoowners);
 7225:                             } else {
 7226:                                 push(@newcoowners,$uname.':'.$udom);
 7227:                             }
 7228:                         } else {
 7229:                             if ($coursehash{'internal.co-owners'}) {
 7230:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 7231:                                     unless ($coowner eq $uname.':'.$udom) {
 7232:                                         push(@newcoowners,$coowner);
 7233:                                     }
 7234:                                 }
 7235:                                 unless (@newcoowners > 0) {
 7236:                                     $delcoowners = 1;
 7237:                                     $coowners = '';
 7238:                                 }
 7239:                             }
 7240:                         }
 7241:                         if (@newcoowners || $delcoowners) {
 7242:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
 7243:                                             $delcoowners,@newcoowners);
 7244:                         }
 7245:                     }
 7246:                 }
 7247:             }
 7248:         }
 7249:     }
 7250: }
 7251: 
 7252: sub store_coowners {
 7253:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
 7254:     my $cid = $cdom.'_'.$cnum;
 7255:     my ($coowners,$delresult,$putresult);
 7256:     if (@newcoowners) {
 7257:         $coowners = join(',',@newcoowners);
 7258:         my %coownershash = (
 7259:                             'internal.co-owners' => $coowners,
 7260:                            );
 7261:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
 7262:         if ($putresult eq 'ok') {
 7263:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
 7264:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
 7265:             }
 7266:         }
 7267:     }
 7268:     if ($delcoowners) {
 7269:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
 7270:         if ($delresult eq 'ok') {
 7271:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
 7272:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
 7273:             }
 7274:         }
 7275:     }
 7276:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
 7277:         my %crsinfo =
 7278:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 7279:         if (ref($crsinfo{$cid}) eq 'HASH') {
 7280:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
 7281:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
 7282:         }
 7283:     }
 7284: }
 7285: 
 7286: # -------------------------------------------------- Modify user authentication
 7287: # Overrides without validation
 7288: 
 7289: sub modifyuserauth {
 7290:     my ($udom,$uname,$umode,$upass)=@_;
 7291:     my $uhome=&homeserver($uname,$udom);
 7292:     unless (&allowed('mau',$udom)) { return 'refused'; }
 7293:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 7294:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 7295:              ' in domain '.$env{'request.role.domain'});  
 7296:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 7297: 		     &escape($upass),$uhome);
 7298:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 7299:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 7300:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 7301:     &log($udom,,$uname,$uhome,
 7302:         'Authentication changed by '.$env{'user.domain'}.', '.
 7303:                                      $env{'user.name'}.', '.$umode.
 7304:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 7305:     unless ($reply eq 'ok') {
 7306:         &logthis('Authentication mode error: '.$reply);
 7307: 	return 'error: '.$reply;
 7308:     }   
 7309:     return 'ok';
 7310: }
 7311: 
 7312: # --------------------------------------------------------------- Modify a user
 7313: 
 7314: sub modifyuser {
 7315:     my ($udom,    $uname, $uid,
 7316:         $umode,   $upass, $first,
 7317:         $middle,  $last,  $gene,
 7318:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
 7319:     $udom= &LONCAPA::clean_domain($udom);
 7320:     $uname=&LONCAPA::clean_username($uname);
 7321:     my $showcandelete = 'none';
 7322:     if (ref($candelete) eq 'ARRAY') {
 7323:         if (@{$candelete} > 0) {
 7324:             $showcandelete = join(', ',@{$candelete});
 7325:         }
 7326:     }
 7327:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 7328:              $umode.', '.$first.', '.$middle.', '.
 7329: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
 7330:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 7331:                                      ' desiredhome not specified'). 
 7332:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 7333:              ' in domain '.$env{'request.role.domain'});
 7334:     my $uhome=&homeserver($uname,$udom,'true');
 7335:     my $newuser;
 7336:     if ($uhome eq 'no_host') {
 7337:         $newuser = 1;
 7338:     }
 7339: # ----------------------------------------------------------------- Create User
 7340:     if (($uhome eq 'no_host') && 
 7341: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 7342:         my $unhome='';
 7343:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 7344:             $unhome = $desiredhome;
 7345: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 7346: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 7347:         } else { # load balancing routine for determining $unhome
 7348:             my $loadm=10000000;
 7349: 	    my %servers = &get_servers($udom,'library');
 7350: 	    foreach my $tryserver (keys(%servers)) {
 7351: 		my $answer=reply('load',$tryserver);
 7352: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 7353: 		    $loadm=$answer;
 7354: 		    $unhome=$tryserver;
 7355: 		}
 7356: 	    }
 7357:         }
 7358:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 7359: 	    return 'error: unable to find a home server for '.$uname.
 7360:                    ' in domain '.$udom;
 7361:         }
 7362:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 7363:                          &escape($upass),$unhome);
 7364: 	unless ($reply eq 'ok') {
 7365:             return 'error: '.$reply;
 7366:         }   
 7367:         $uhome=&homeserver($uname,$udom,'true');
 7368:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 7369: 	    return 'error: unable verify users home machine.';
 7370:         }
 7371:     }   # End of creation of new user
 7372: # ---------------------------------------------------------------------- Add ID
 7373:     if ($uid) {
 7374:        $uid=~tr/A-Z/a-z/;
 7375:        my %uidhash=&idrget($udom,$uname);
 7376:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 7377:          && (!$forceid)) {
 7378: 	  unless ($uid eq $uidhash{$uname}) {
 7379: 	      return 'error: user id "'.$uid.'" does not match '.
 7380:                   'current user id "'.$uidhash{$uname}.'".';
 7381:           }
 7382:        } else {
 7383: 	  &idput($udom,($uname => $uid));
 7384:        }
 7385:     }
 7386: # -------------------------------------------------------------- Add names, etc
 7387:     my @tmp=&get('environment',
 7388: 		   ['firstname','middlename','lastname','generation','id',
 7389:                     'permanentemail','inststatus'],
 7390: 		   $udom,$uname);
 7391:     my (%names,%oldnames);
 7392:     if ($tmp[0] =~ m/^error:.*/) { 
 7393:         %names=(); 
 7394:     } else {
 7395:         %names = @tmp;
 7396:         %oldnames = %names;
 7397:     }
 7398: #
 7399: # If name, email and/or uid are blank (e.g., because an uploaded file
 7400: # of users did not contain them), do not overwrite existing values
 7401: # unless field is in $candelete array ref.  
 7402: #
 7403: 
 7404:     my @fields = ('firstname','middlename','lastname','generation',
 7405:                   'permanentemail','id');
 7406:     my %newvalues;
 7407:     if (ref($candelete) eq 'ARRAY') {
 7408:         foreach my $field (@fields) {
 7409:             if (grep(/^\Q$field\E$/,@{$candelete})) {
 7410:                 if ($field eq 'firstname') {
 7411:                     $names{$field} = $first;
 7412:                 } elsif ($field eq 'middlename') {
 7413:                     $names{$field} = $middle;
 7414:                 } elsif ($field eq 'lastname') {
 7415:                     $names{$field} = $last;
 7416:                 } elsif ($field eq 'generation') { 
 7417:                     $names{$field} = $gene;
 7418:                 } elsif ($field eq 'permanentemail') {
 7419:                     $names{$field} = $email;
 7420:                 } elsif ($field eq 'id') {
 7421:                     $names{$field}  = $uid;
 7422:                 }
 7423:             }
 7424:         }
 7425:     }
 7426:     if ($first)  { $names{'firstname'}  = $first; }
 7427:     if (defined($middle)) { $names{'middlename'} = $middle; }
 7428:     if ($last)   { $names{'lastname'}   = $last; }
 7429:     if (defined($gene))   { $names{'generation'} = $gene; }
 7430:     if ($email) {
 7431:        $email=~s/[^\w\@\.\-\,]//gs;
 7432:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 7433:     }
 7434:     if ($uid) { $names{'id'}  = $uid; }
 7435:     if (defined($inststatus)) {
 7436:         $names{'inststatus'} = '';
 7437:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
 7438:         if (ref($usertypes) eq 'HASH') {
 7439:             my @okstatuses; 
 7440:             foreach my $item (split(/:/,$inststatus)) {
 7441:                 if (defined($usertypes->{$item})) {
 7442:                     push(@okstatuses,$item);  
 7443:                 }
 7444:             }
 7445:             if (@okstatuses) {
 7446:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
 7447:             }
 7448:         }
 7449:     }
 7450:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
 7451:                  $umode.', '.$first.', '.$middle.', '.
 7452:                  $last.', '.$gene.', '.$email.', '.$inststatus;
 7453:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 7454:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 7455:     } else {
 7456:         $logmsg .= ' during self creation';
 7457:     }
 7458:     my $changed;
 7459:     if ($newuser) {
 7460:         $changed = 1;
 7461:     } else {
 7462:         foreach my $field (@fields) {
 7463:             if ($names{$field} ne $oldnames{$field}) {
 7464:                 $changed = 1;
 7465:                 last;
 7466:             }
 7467:         }
 7468:     }
 7469:     unless ($changed) {
 7470:         $logmsg = 'No changes in user information needed for: '.$logmsg;
 7471:         &logthis($logmsg);
 7472:         return 'ok';
 7473:     }
 7474:     my $reply = &put('environment', \%names, $udom,$uname);
 7475:     if ($reply ne 'ok') { 
 7476:         return 'error: '.$reply;
 7477:     }
 7478:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
 7479:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
 7480:     }
 7481:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 7482:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 7483:     $logmsg = 'Success modifying user '.$logmsg;
 7484:     &logthis($logmsg);
 7485:     return 'ok';
 7486: }
 7487: 
 7488: # -------------------------------------------------------------- Modify student
 7489: 
 7490: sub modifystudent {
 7491:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 7492:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 7493:         $selfenroll,$context,$inststatus)=@_;
 7494:     if (!$cid) {
 7495: 	unless ($cid=$env{'request.course.id'}) {
 7496: 	    return 'not_in_class';
 7497: 	}
 7498:     }
 7499: # --------------------------------------------------------------- Make the user
 7500:     my $reply=&modifyuser
 7501: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 7502:          $desiredhome,$email,$inststatus);
 7503:     unless ($reply eq 'ok') { return $reply; }
 7504:     # This will cause &modify_student_enrollment to get the uid from the
 7505:     # students environment
 7506:     $uid = undef if (!$forceid);
 7507:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 7508: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
 7509:     return $reply;
 7510: }
 7511: 
 7512: sub modify_student_enrollment {
 7513:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
 7514:     my ($cdom,$cnum,$chome);
 7515:     if (!$cid) {
 7516: 	unless ($cid=$env{'request.course.id'}) {
 7517: 	    return 'not_in_class';
 7518: 	}
 7519: 	$cdom=$env{'course.'.$cid.'.domain'};
 7520: 	$cnum=$env{'course.'.$cid.'.num'};
 7521:     } else {
 7522: 	($cdom,$cnum)=split(/_/,$cid);
 7523:     }
 7524:     $chome=$env{'course.'.$cid.'.home'};
 7525:     if (!$chome) {
 7526: 	$chome=&homeserver($cnum,$cdom);
 7527:     }
 7528:     if (!$chome) { return 'unknown_course'; }
 7529:     # Make sure the user exists
 7530:     my $uhome=&homeserver($uname,$udom);
 7531:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 7532: 	return 'error: no such user';
 7533:     }
 7534:     # Get student data if we were not given enough information
 7535:     if (!defined($first)  || $first  eq '' || 
 7536:         !defined($last)   || $last   eq '' || 
 7537:         !defined($uid)    || $uid    eq '' || 
 7538:         !defined($middle) || $middle eq '' || 
 7539:         !defined($gene)   || $gene   eq '') {
 7540:         # They did not supply us with enough data to enroll the student, so
 7541:         # we need to pick up more information.
 7542:         my %tmp = &get('environment',
 7543:                        ['firstname','middlename','lastname', 'generation','id']
 7544:                        ,$udom,$uname);
 7545: 
 7546:         #foreach my $key (keys(%tmp)) {
 7547:         #    &logthis("key $key = ".$tmp{$key});
 7548:         #}
 7549:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 7550:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 7551:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 7552:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 7553:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 7554:     }
 7555:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 7556:     my $user = "$uname:$udom";
 7557:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
 7558:     my $reply=cput('classlist',
 7559: 		   {$user => 
 7560: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
 7561: 		   $cdom,$cnum);
 7562:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
 7563:         &devalidate_getsection_cache($udom,$uname,$cid);
 7564:     } else { 
 7565: 	return 'error: '.$reply;
 7566:     }
 7567:     # Add student role to user
 7568:     my $uurl='/'.$cid;
 7569:     $uurl=~s/\_/\//g;
 7570:     if ($usec) {
 7571: 	$uurl.='/'.$usec;
 7572:     }
 7573:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
 7574:                              $selfenroll,$context);
 7575:     if ($result ne 'ok') {
 7576:         if ($old_entry{$user} ne '') {
 7577:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
 7578:         } else {
 7579:             $reply = &del('classlist',[$user],$cdom,$cnum);
 7580:         }
 7581:     }
 7582:     return $result; 
 7583: }
 7584: 
 7585: sub format_name {
 7586:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 7587:     my $name;
 7588:     if ($first ne 'lastname') {
 7589: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 7590:     } else {
 7591: 	if ($lastname=~/\S/) {
 7592: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 7593: 	    $name=~s/\s+,/,/;
 7594: 	} else {
 7595: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 7596: 	}
 7597:     }
 7598:     $name=~s/^\s+//;
 7599:     $name=~s/\s+$//;
 7600:     $name=~s/\s+/ /g;
 7601:     return $name;
 7602: }
 7603: 
 7604: # ------------------------------------------------- Write to course preferences
 7605: 
 7606: sub writecoursepref {
 7607:     my ($courseid,%prefs)=@_;
 7608:     $courseid=~s/^\///;
 7609:     $courseid=~s/\_/\//g;
 7610:     my ($cdomain,$cnum)=split(/\//,$courseid);
 7611:     my $chome=homeserver($cnum,$cdomain);
 7612:     if (($chome eq '') || ($chome eq 'no_host')) { 
 7613: 	return 'error: no such course';
 7614:     }
 7615:     my $cstring='';
 7616:     foreach my $pref (keys(%prefs)) {
 7617: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 7618:     }
 7619:     $cstring=~s/\&$//;
 7620:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 7621: }
 7622: 
 7623: # ---------------------------------------------------------- Make/modify course
 7624: 
 7625: sub createcourse {
 7626:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 7627:         $course_owner,$crstype,$cnum,$context,$category)=@_;
 7628:     $url=&declutter($url);
 7629:     my $cid='';
 7630:     if ($context eq 'requestcourses') {
 7631:         my $can_create = 0;
 7632:         my ($ownername,$ownerdom) = split(':',$course_owner);
 7633:         if ($udom eq $ownerdom) {
 7634:             if (&usertools_access($ownername,$ownerdom,$category,undef,
 7635:                                   $context)) {
 7636:                 $can_create = 1;
 7637:             }
 7638:         } else {
 7639:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
 7640:                                            $category);
 7641:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
 7642:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
 7643:                 if (@curr > 0) {
 7644:                     my @options = qw(approval validate autolimit);
 7645:                     my $optregex = join('|',@options);
 7646:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
 7647:                         $can_create = 1;
 7648:                     }
 7649:                 }
 7650:             }
 7651:         }
 7652:         if ($can_create) {
 7653:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
 7654:                 unless (&allowed('ccc',$udom)) {
 7655:                     return 'refused'; 
 7656:                 }
 7657:             }
 7658:         } else {
 7659:             return 'refused';
 7660:         }
 7661:     } elsif (!&allowed('ccc',$udom)) {
 7662:         return 'refused';
 7663:     }
 7664: # --------------------------------------------------------------- Get Unique ID
 7665:     my $uname;
 7666:     if ($cnum =~ /^$match_courseid$/) {
 7667:         my $chome=&homeserver($cnum,$udom,'true');
 7668:         if (($chome eq '') || ($chome eq 'no_host')) {
 7669:             $uname = $cnum;
 7670:         } else {
 7671:             $uname = &generate_coursenum($udom,$crstype);
 7672:         }
 7673:     } else {
 7674:         $uname = &generate_coursenum($udom,$crstype);
 7675:     }
 7676:     return $uname if ($uname =~ /^error/);
 7677: # -------------------------------------------------- Check supplied server name
 7678:     if (!defined($course_server)) {
 7679:         if (defined(&domain($udom,'primary'))) {
 7680:             $course_server = &domain($udom,'primary');
 7681:         } else {
 7682:             $course_server = $env{'user.home'}; 
 7683:         }
 7684:     }
 7685:     my %host_servers =
 7686:         &Apache::lonnet::get_servers($udom,'library');
 7687:     unless ($host_servers{$course_server}) {
 7688:         return 'error: invalid home server for course: '.$course_server;
 7689:     }
 7690: # ------------------------------------------------------------- Make the course
 7691:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 7692:                       $course_server);
 7693:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 7694:     my $uhome=&homeserver($uname,$udom,'true');
 7695:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 7696: 	return 'error: no such course';
 7697:     }
 7698: # ----------------------------------------------------------------- Course made
 7699: # log existence
 7700:     my $now = time;
 7701:     my $newcourse = {
 7702:                     $udom.'_'.$uname => {
 7703:                                      description => $description,
 7704:                                      inst_code   => $inst_code,
 7705:                                      owner       => $course_owner,
 7706:                                      type        => $crstype,
 7707:                                      creator     => $env{'user.name'}.':'.
 7708:                                                     $env{'user.domain'},
 7709:                                      created     => $now,
 7710:                                      context     => $context,
 7711:                                                 },
 7712:                     };
 7713:     &courseidput($udom,$newcourse,$uhome,'notime');
 7714: # set toplevel url
 7715:     my $topurl=$url;
 7716:     unless ($nonstandard) {
 7717: # ------------------------------------------ For standard courses, make top url
 7718:         my $mapurl=&clutter($url);
 7719:         if ($mapurl eq '/res/') { $mapurl=''; }
 7720:         $env{'form.initmap'}=(<<ENDINITMAP);
 7721: <map>
 7722: <resource id="1" type="start"></resource>
 7723: <resource id="2" src="$mapurl"></resource>
 7724: <resource id="3" type="finish"></resource>
 7725: <link index="1" from="1" to="2"></link>
 7726: <link index="2" from="2" to="3"></link>
 7727: </map>
 7728: ENDINITMAP
 7729:         $topurl=&declutter(
 7730:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 7731:                           );
 7732:     }
 7733: # ----------------------------------------------------------- Write preferences
 7734:     &writecoursepref($udom.'_'.$uname,
 7735:                      ('description'              => $description,
 7736:                       'url'                      => $topurl,
 7737:                       'internal.creator'         => $env{'user.name'}.':'.
 7738:                                                     $env{'user.domain'},
 7739:                       'internal.created'         => $now,
 7740:                       'internal.creationcontext' => $context)
 7741:                     );
 7742:     return '/'.$udom.'/'.$uname;
 7743: }
 7744: 
 7745: # ------------------------------------------------------------------- Create ID
 7746: sub generate_coursenum {
 7747:     my ($udom,$crstype) = @_;
 7748:     my $domdesc = &domain($udom);
 7749:     return 'error: invalid domain' if ($domdesc eq '');
 7750:     my $first;
 7751:     if ($crstype eq 'Community') {
 7752:         $first = '0';
 7753:     } else {
 7754:         $first = int(1+rand(9)); 
 7755:     } 
 7756:     my $uname=$first.
 7757:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 7758:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
 7759:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 7760: # ----------------------------------------------- Make sure that does not exist
 7761:     my $uhome=&homeserver($uname,$udom,'true');
 7762:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
 7763:         if ($crstype eq 'Community') {
 7764:             $first = '0';
 7765:         } else {
 7766:             $first = int(1+rand(9));
 7767:         }
 7768:         $uname=$first.
 7769:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 7770:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
 7771:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 7772:         $uhome=&homeserver($uname,$udom,'true');
 7773:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
 7774:             return 'error: unable to generate unique course-ID';
 7775:         }
 7776:     }
 7777:     return $uname;
 7778: }
 7779: 
 7780: sub is_course {
 7781:     my ($cdom,$cnum) = @_;
 7782:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
 7783: 				undef,'.');
 7784:     if (exists($courses{$cdom.'_'.$cnum})) {
 7785:         return 1;
 7786:     }
 7787:     return 0;
 7788: }
 7789: 
 7790: sub store_userdata {
 7791:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
 7792:     my $result;
 7793:     if ($datakey ne '') {
 7794:         if (ref($storehash) eq 'HASH') {
 7795:             if ($udom eq '' || $uname eq '') {
 7796:                 $udom = $env{'user.domain'};
 7797:                 $uname = $env{'user.name'};
 7798:             }
 7799:             my $uhome=&homeserver($uname,$udom);
 7800:             if (($uhome eq '') || ($uhome eq 'no_host')) {
 7801:                 $result = 'error: no_host';
 7802:             } else {
 7803:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
 7804:                 $storehash->{'host'} = $perlvar{'lonHostID'};
 7805: 
 7806:                 my $namevalue='';
 7807:                 foreach my $key (keys(%{$storehash})) {
 7808:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 7809:                 }
 7810:                 $namevalue=~s/\&$//;
 7811:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
 7812:                                   $namevalue,$uhome);
 7813:             }
 7814:         } else {
 7815:             $result = 'error: data to store was not a hash reference'; 
 7816:         }
 7817:     } else {
 7818:         $result= 'error: invalid requestkey'; 
 7819:     }
 7820:     return $result;
 7821: }
 7822: 
 7823: # ---------------------------------------------------------- Assign Custom Role
 7824: 
 7825: sub assigncustomrole {
 7826:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
 7827:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 7828:                        $end,$start,$deleteflag,$selfenroll,$context);
 7829: }
 7830: 
 7831: # ----------------------------------------------------------------- Revoke Role
 7832: 
 7833: sub revokerole {
 7834:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
 7835:     my $now=time;
 7836:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
 7837: }
 7838: 
 7839: # ---------------------------------------------------------- Revoke Custom Role
 7840: 
 7841: sub revokecustomrole {
 7842:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
 7843:     my $now=time;
 7844:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 7845:            $deleteflag,$selfenroll,$context);
 7846: }
 7847: 
 7848: # ------------------------------------------------------------ Disk usage
 7849: sub diskusage {
 7850:     my ($udom,$uname,$directorypath,$getpropath)=@_;
 7851:     $directorypath =~ s/\/$//;
 7852:     my $listing=&reply('du2:'.&escape($directorypath).':'
 7853:                        .&escape($getpropath).':'.&escape($uname).':'
 7854:                        .&escape($udom),homeserver($uname,$udom));
 7855:     if ($listing eq 'unknown_cmd') {
 7856:         if ($getpropath) {
 7857:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
 7858:         }
 7859:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
 7860:     }
 7861:     return $listing;
 7862: }
 7863: 
 7864: sub is_locked {
 7865:     my ($file_name, $domain, $user, $which) = @_;
 7866:     my @check;
 7867:     my $is_locked;
 7868:     push (@check,$file_name);
 7869:     my %locked = &get('file_permissions',\@check,
 7870: 		      $env{'user.domain'},$env{'user.name'});
 7871:     my ($tmp)=keys(%locked);
 7872:     if ($tmp=~/^error:/) { undef(%locked); }
 7873:     
 7874:     if (ref($locked{$file_name}) eq 'ARRAY') {
 7875:         $is_locked = 'false';
 7876:         foreach my $entry (@{$locked{$file_name}}) {
 7877:            if (ref($entry) eq 'ARRAY') {
 7878:                $is_locked = 'true';
 7879:                if (ref($which) eq 'ARRAY') {
 7880:                    push(@{$which},$entry);
 7881:                } else {
 7882:                    last;
 7883:                }
 7884:            }
 7885:        }
 7886:     } else {
 7887:         $is_locked = 'false';
 7888:     }
 7889:     return $is_locked;
 7890: }
 7891: 
 7892: sub declutter_portfile {
 7893:     my ($file) = @_;
 7894:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 7895:     return $file;
 7896: }
 7897: 
 7898: # ------------------------------------------------------------- Mark as Read Only
 7899: 
 7900: sub mark_as_readonly {
 7901:     my ($domain,$user,$files,$what) = @_;
 7902:     my %current_permissions = &dump('file_permissions',$domain,$user);
 7903:     my ($tmp)=keys(%current_permissions);
 7904:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 7905:     foreach my $file (@{$files}) {
 7906: 	$file = &declutter_portfile($file);
 7907:         push(@{$current_permissions{$file}},$what);
 7908:     }
 7909:     &put('file_permissions',\%current_permissions,$domain,$user);
 7910:     return;
 7911: }
 7912: 
 7913: # ------------------------------------------------------------Save Selected Files
 7914: 
 7915: sub save_selected_files {
 7916:     my ($user, $path, @files) = @_;
 7917:     my $filename = $user."savedfiles";
 7918:     my @other_files = &files_not_in_path($user, $path);
 7919:     open (OUT, '>'.$tmpdir.$filename);
 7920:     foreach my $file (@files) {
 7921:         print (OUT $env{'form.currentpath'}.$file."\n");
 7922:     }
 7923:     foreach my $file (@other_files) {
 7924:         print (OUT $file."\n");
 7925:     }
 7926:     close (OUT);
 7927:     return 'ok';
 7928: }
 7929: 
 7930: sub clear_selected_files {
 7931:     my ($user) = @_;
 7932:     my $filename = $user."savedfiles";
 7933:     open (OUT, '>'.LONCAPA::tempdir().$filename);
 7934:     print (OUT undef);
 7935:     close (OUT);
 7936:     return ("ok");    
 7937: }
 7938: 
 7939: sub files_in_path {
 7940:     my ($user, $path) = @_;
 7941:     my $filename = $user."savedfiles";
 7942:     my %return_files;
 7943:     open (IN, '<'.LONCAPA::tempdir().$filename);
 7944:     while (my $line_in = <IN>) {
 7945:         chomp ($line_in);
 7946:         my @paths_and_file = split (m!/!, $line_in);
 7947:         my $file_part = pop (@paths_and_file);
 7948:         my $path_part = join ('/', @paths_and_file);
 7949:         $path_part.='/';
 7950:         my $path_and_file = $path_part.$file_part;
 7951:         if ($path_part eq $path) {
 7952:             $return_files{$file_part}= 'selected';
 7953:         }
 7954:     }
 7955:     close (IN);
 7956:     return (\%return_files);
 7957: }
 7958: 
 7959: # called in portfolio select mode, to show files selected NOT in current directory
 7960: sub files_not_in_path {
 7961:     my ($user, $path) = @_;
 7962:     my $filename = $user."savedfiles";
 7963:     my @return_files;
 7964:     my $path_part;
 7965:     open(IN, '<'.LONCAPA::.$filename);
 7966:     while (my $line = <IN>) {
 7967:         #ok, I know it's clunky, but I want it to work
 7968:         my @paths_and_file = split(m|/|, $line);
 7969:         my $file_part = pop(@paths_and_file);
 7970:         chomp($file_part);
 7971:         my $path_part = join('/', @paths_and_file);
 7972:         $path_part .= '/';
 7973:         my $path_and_file = $path_part.$file_part;
 7974:         if ($path_part ne $path) {
 7975:             push(@return_files, ($path_and_file));
 7976:         }
 7977:     }
 7978:     close(OUT);
 7979:     return (@return_files);
 7980: }
 7981: 
 7982: #----------------------------------------------Get portfolio file permissions
 7983: 
 7984: sub get_portfile_permissions {
 7985:     my ($domain,$user) = @_;
 7986:     my %current_permissions = &dump('file_permissions',$domain,$user);
 7987:     my ($tmp)=keys(%current_permissions);
 7988:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 7989:     return \%current_permissions;
 7990: }
 7991: 
 7992: #---------------------------------------------Get portfolio file access controls
 7993: 
 7994: sub get_access_controls {
 7995:     my ($current_permissions,$group,$file) = @_;
 7996:     my %access;
 7997:     my $real_file = $file;
 7998:     $file =~ s/\.meta$//;
 7999:     if (defined($file)) {
 8000:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 8001:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 8002:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 8003:             }
 8004:         }
 8005:     } else {
 8006:         foreach my $key (keys(%{$current_permissions})) {
 8007:             if ($key =~ /\0accesscontrol$/) {
 8008:                 if (defined($group)) {
 8009:                     if ($key !~ m-^\Q$group\E/-) {
 8010:                         next;
 8011:                     }
 8012:                 }
 8013:                 my ($fullpath) = split(/\0/,$key);
 8014:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 8015:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 8016:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 8017:                     }
 8018:                 }
 8019:             }
 8020:         }
 8021:     }
 8022:     return %access;
 8023: }
 8024: 
 8025: sub modify_access_controls {
 8026:     my ($file_name,$changes,$domain,$user)=@_;
 8027:     my ($outcome,$deloutcome);
 8028:     my %store_permissions;
 8029:     my %new_values;
 8030:     my %new_control;
 8031:     my %translation;
 8032:     my @deletions = ();
 8033:     my $now = time;
 8034:     if (exists($$changes{'activate'})) {
 8035:         if (ref($$changes{'activate'}) eq 'HASH') {
 8036:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 8037:             my $numnew = scalar(@newitems);
 8038:             for (my $i=0; $i<$numnew; $i++) {
 8039:                 my $newkey = $newitems[$i];
 8040:                 my $newid = &Apache::loncommon::get_cgi_id();
 8041:                 if ($newkey =~ /^\d+:/) { 
 8042:                     $newkey =~ s/^(\d+)/$newid/;
 8043:                     $translation{$1} = $newid;
 8044:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 8045:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 8046:                     $translation{$1} = $newid;
 8047:                 }
 8048:                 $new_values{$file_name."\0".$newkey} = 
 8049:                                           $$changes{'activate'}{$newitems[$i]};
 8050:                 $new_control{$newkey} = $now;
 8051:             }
 8052:         }
 8053:     }
 8054:     my %todelete;
 8055:     my %changed_items;
 8056:     foreach my $action ('delete','update') {
 8057:         if (exists($$changes{$action})) {
 8058:             if (ref($$changes{$action}) eq 'HASH') {
 8059:                 foreach my $key (keys(%{$$changes{$action}})) {
 8060:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 8061:                     if ($action eq 'delete') { 
 8062:                         $todelete{$itemnum} = 1;
 8063:                     } else {
 8064:                         $changed_items{$itemnum} = $key;
 8065:                     }
 8066:                 }
 8067:             }
 8068:         }
 8069:     }
 8070:     # get lock on access controls for file.
 8071:     my $lockhash = {
 8072:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 8073:                                                        ':'.$env{'user.domain'},
 8074:                    }; 
 8075:     my $tries = 0;
 8076:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 8077:    
 8078:     while (($gotlock ne 'ok') && $tries <3) {
 8079:         $tries ++;
 8080:         sleep 1;
 8081:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 8082:     }
 8083:     if ($gotlock eq 'ok') {
 8084:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 8085:         my ($tmp)=keys(%curr_permissions);
 8086:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 8087:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 8088:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 8089:             if (ref($curr_controls) eq 'HASH') {
 8090:                 foreach my $control_item (keys(%{$curr_controls})) {
 8091:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 8092:                     if (defined($todelete{$itemnum})) {
 8093:                         push(@deletions,$file_name."\0".$control_item);
 8094:                     } else {
 8095:                         if (defined($changed_items{$itemnum})) {
 8096:                             $new_control{$changed_items{$itemnum}} = $now;
 8097:                             push(@deletions,$file_name."\0".$control_item);
 8098:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 8099:                         } else {
 8100:                             $new_control{$control_item} = $$curr_controls{$control_item};
 8101:                         }
 8102:                     }
 8103:                 }
 8104:             }
 8105:         }
 8106:         my ($group);
 8107:         if (&is_course($domain,$user)) {
 8108:             ($group,my $file) = split(/\//,$file_name,2);
 8109:         }
 8110:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 8111:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 8112:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 8113:         #  remove lock
 8114:         my @del_lock = ($file_name."\0".'locked_access_records');
 8115:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 8116:         my $sqlresult =
 8117:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
 8118:                                     $group);
 8119:     } else {
 8120:         $outcome = "error: could not obtain lockfile\n";  
 8121:     }
 8122:     return ($outcome,$deloutcome,\%new_values,\%translation);
 8123: }
 8124: 
 8125: sub make_public_indefinitely {
 8126:     my ($requrl) = @_;
 8127:     my $now = time;
 8128:     my $action = 'activate';
 8129:     my $aclnum = 0;
 8130:     if (&is_portfolio_url($requrl)) {
 8131:         my (undef,$udom,$unum,$file_name,$group) =
 8132:             &parse_portfolio_url($requrl);
 8133:         my $current_perms = &get_portfile_permissions($udom,$unum);
 8134:         my %access_controls = &get_access_controls($current_perms,
 8135:                                                    $group,$file_name);
 8136:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 8137:             my ($num,$scope,$end,$start) = 
 8138:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 8139:             if ($scope eq 'public') {
 8140:                 if ($start <= $now && $end == 0) {
 8141:                     $action = 'none';
 8142:                 } else {
 8143:                     $action = 'update';
 8144:                     $aclnum = $num;
 8145:                 }
 8146:                 last;
 8147:             }
 8148:         }
 8149:         if ($action eq 'none') {
 8150:              return 'ok';
 8151:         } else {
 8152:             my %changes;
 8153:             my $newend = 0;
 8154:             my $newstart = $now;
 8155:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 8156:             $changes{$action}{$newkey} = {
 8157:                 type => 'public',
 8158:                 time => {
 8159:                     start => $newstart,
 8160:                     end   => $newend,
 8161:                 },
 8162:             };
 8163:             my ($outcome,$deloutcome,$new_values,$translation) =
 8164:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 8165:             return $outcome;
 8166:         }
 8167:     } else {
 8168:         return 'invalid';
 8169:     }
 8170: }
 8171: 
 8172: #------------------------------------------------------Get Marked as Read Only
 8173: 
 8174: sub get_marked_as_readonly {
 8175:     my ($domain,$user,$what,$group) = @_;
 8176:     my $current_permissions = &get_portfile_permissions($domain,$user);
 8177:     my @readonly_files;
 8178:     my $cmp1=$what;
 8179:     if (ref($what)) { $cmp1=join('',@{$what}) };
 8180:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 8181:         if (defined($group)) {
 8182:             if ($file_name !~ m-^\Q$group\E/-) {
 8183:                 next;
 8184:             }
 8185:         }
 8186:         if (ref($value) eq "ARRAY"){
 8187:             foreach my $stored_what (@{$value}) {
 8188:                 my $cmp2=$stored_what;
 8189:                 if (ref($stored_what) eq 'ARRAY') {
 8190:                     $cmp2=join('',@{$stored_what});
 8191:                 }
 8192:                 if ($cmp1 eq $cmp2) {
 8193:                     push(@readonly_files, $file_name);
 8194:                     last;
 8195:                 } elsif (!defined($what)) {
 8196:                     push(@readonly_files, $file_name);
 8197:                     last;
 8198:                 }
 8199:             }
 8200:         }
 8201:     }
 8202:     return @readonly_files;
 8203: }
 8204: #-----------------------------------------------------------Get Marked as Read Only Hash
 8205: 
 8206: sub get_marked_as_readonly_hash {
 8207:     my ($current_permissions,$group,$what) = @_;
 8208:     my %readonly_files;
 8209:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 8210:         if (defined($group)) {
 8211:             if ($file_name !~ m-^\Q$group\E/-) {
 8212:                 next;
 8213:             }
 8214:         }
 8215:         if (ref($value) eq "ARRAY"){
 8216:             foreach my $stored_what (@{$value}) {
 8217:                 if (ref($stored_what) eq 'ARRAY') {
 8218:                     foreach my $lock_descriptor(@{$stored_what}) {
 8219:                         if ($lock_descriptor eq 'graded') {
 8220:                             $readonly_files{$file_name} = 'graded';
 8221:                         } elsif ($lock_descriptor eq 'handback') {
 8222:                             $readonly_files{$file_name} = 'handback';
 8223:                         } else {
 8224:                             if (!exists($readonly_files{$file_name})) {
 8225:                                 $readonly_files{$file_name} = 'locked';
 8226:                             }
 8227:                         }
 8228:                     }
 8229:                 } 
 8230:             }
 8231:         } 
 8232:     }
 8233:     return %readonly_files;
 8234: }
 8235: # ------------------------------------------------------------ Unmark as Read Only
 8236: 
 8237: sub unmark_as_readonly {
 8238:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 8239:     # for portfolio submissions, $what contains [$symb,$crsid] 
 8240:     my ($domain,$user,$what,$file_name,$group) = @_;
 8241:     $file_name = &declutter_portfile($file_name);
 8242:     my $symb_crs = $what;
 8243:     if (ref($what)) { $symb_crs=join('',@$what); }
 8244:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 8245:     my ($tmp)=keys(%current_permissions);
 8246:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 8247:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 8248:     foreach my $file (@readonly_files) {
 8249: 	my $clean_file = &declutter_portfile($file);
 8250: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 8251: 	my $current_locks = $current_permissions{$file};
 8252:         my @new_locks;
 8253:         my @del_keys;
 8254:         if (ref($current_locks) eq "ARRAY"){
 8255:             foreach my $locker (@{$current_locks}) {
 8256:                 my $compare=$locker;
 8257:                 if (ref($locker) eq 'ARRAY') {
 8258:                     $compare=join('',@{$locker});
 8259:                     if ($compare ne $symb_crs) {
 8260:                         push(@new_locks, $locker);
 8261:                     }
 8262:                 }
 8263:             }
 8264:             if (scalar(@new_locks) > 0) {
 8265:                 $current_permissions{$file} = \@new_locks;
 8266:             } else {
 8267:                 push(@del_keys, $file);
 8268:                 &del('file_permissions',\@del_keys, $domain, $user);
 8269:                 delete($current_permissions{$file});
 8270:             }
 8271:         }
 8272:     }
 8273:     &put('file_permissions',\%current_permissions,$domain,$user);
 8274:     return;
 8275: }
 8276: 
 8277: # ------------------------------------------------------------ Directory lister
 8278: 
 8279: sub dirlist {
 8280:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
 8281:     $uri=~s/^\///;
 8282:     $uri=~s/\/$//;
 8283:     my ($udom, $uname);
 8284:     if ($getuserdir) {
 8285:         $udom = $userdomain;
 8286:         $uname = $username;
 8287:     } else {
 8288:         (undef,$udom,$uname)=split(/\//,$uri);
 8289:         if(defined($userdomain)) {
 8290:             $udom = $userdomain;
 8291:         }
 8292:         if(defined($username)) {
 8293:             $uname = $username;
 8294:         }
 8295:     }
 8296:     my ($dirRoot,$listing,@listing_results);
 8297: 
 8298:     $dirRoot = $perlvar{'lonDocRoot'};
 8299:     if (defined($getpropath)) {
 8300:         $dirRoot = &propath($udom,$uname);
 8301:         $dirRoot =~ s/\/$//;
 8302:     } elsif (defined($getuserdir)) {
 8303:         my $subdir=$uname.'__';
 8304:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 8305:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
 8306:                    ."/$udom/$subdir/$uname";
 8307:     } elsif (defined($alternateRoot)) {
 8308:         $dirRoot = $alternateRoot;
 8309:     }
 8310: 
 8311:     if($udom) {
 8312:         if($uname) {
 8313:             my $uhome = &homeserver($uname,$udom);
 8314:             if ($uhome eq 'no_host') {
 8315:                 return ([],'no_host');
 8316:             }
 8317:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
 8318:                               .$getuserdir.':'.&escape($dirRoot)
 8319:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
 8320:             if ($listing eq 'unknown_cmd') {
 8321:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
 8322:             } else {
 8323:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 8324:             }
 8325:             if ($listing eq 'unknown_cmd') {
 8326:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
 8327:                 @listing_results = split(/:/,$listing);
 8328:             } else {
 8329:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 8330:             }
 8331:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
 8332:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
 8333:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 8334:                 return ([],$listing);
 8335:             } else {
 8336:                 return (\@listing_results);
 8337:             }
 8338:         } elsif(!$alternateRoot) {
 8339:             my (%allusers,%listerror);
 8340: 	    my %servers = &get_servers($udom,'library');
 8341:  	    foreach my $tryserver (keys(%servers)) {
 8342:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
 8343:                                   &escape($udom),$tryserver);
 8344:                 if ($listing eq 'unknown_cmd') {
 8345: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 8346: 				      $udom, $tryserver);
 8347:                 } else {
 8348:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
 8349:                 }
 8350: 		if ($listing eq 'unknown_cmd') {
 8351: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 8352: 				      $udom, $tryserver);
 8353: 		    @listing_results = split(/:/,$listing);
 8354: 		} else {
 8355: 		    @listing_results =
 8356: 			map { &unescape($_); } split(/:/,$listing);
 8357: 		}
 8358:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
 8359:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
 8360:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 8361:                     $listerror{$tryserver} = $listing;
 8362:                 } else {
 8363: 		    foreach my $line (@listing_results) {
 8364: 			my ($entry) = split(/&/,$line,2);
 8365: 			$allusers{$entry} = 1;
 8366: 		    }
 8367: 		}
 8368:             }
 8369:             my @alluserslist=();
 8370:             foreach my $user (sort(keys(%allusers))) {
 8371:                 push(@alluserslist,$user.'&user');
 8372:             }
 8373:             return (\@alluserslist);
 8374:         } else {
 8375:             return ([],'missing username');
 8376:         }
 8377:     } elsif(!defined($getpropath)) {
 8378:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
 8379:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
 8380:         return (\@all_domains);
 8381:     } else {
 8382:         return ([],'missing domain');
 8383:     }
 8384: }
 8385: 
 8386: # --------------------------------------------- GetFileTimestamp
 8387: # This function utilizes dirlist and returns the date stamp for
 8388: # when it was last modified.  It will also return an error of -1
 8389: # if an error occurs
 8390: 
 8391: sub GetFileTimestamp {
 8392:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
 8393:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 8394:     $studentName   = &LONCAPA::clean_username($studentName);
 8395:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
 8396:                                     undef,$getuserdir);
 8397:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 8398:         return -1;
 8399:     }
 8400:     if (ref($fileref) eq 'ARRAY') {
 8401:         my @stats = split('&',$fileref->[0]);
 8402:         # @stats contains first the filename, then the stat output
 8403:         return $stats[10]; # so this is 10 instead of 9.
 8404:     } else {
 8405:         return -1;
 8406:     }
 8407: }
 8408: 
 8409: sub stat_file {
 8410:     my ($uri) = @_;
 8411:     $uri = &clutter_with_no_wrapper($uri);
 8412: 
 8413:     my ($udom,$uname,$file);
 8414:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 8415: 	($udom,$uname,$file) =
 8416: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 8417: 	$file = 'userfiles/'.$file;
 8418:     }
 8419:     if ($uri =~ m-^/res/-) {
 8420: 	($udom,$uname) = 
 8421: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 8422: 	$file = $uri;
 8423:     }
 8424: 
 8425:     if (!$udom || !$uname || !$file) {
 8426: 	# unable to handle the uri
 8427: 	return ();
 8428:     }
 8429:     my $getpropath;
 8430:     if ($file =~ /^userfiles\//) {
 8431:         $getpropath = 1;
 8432:     }
 8433:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
 8434:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 8435:         return ();
 8436:     } else {
 8437:         if (ref($listref) eq 'ARRAY') {
 8438:             my @stats = split('&',$listref->[0]);
 8439: 	    shift(@stats); #filename is first
 8440: 	    return @stats;
 8441:         }
 8442:     }
 8443:     return ();
 8444: }
 8445: 
 8446: # -------------------------------------------------------- Value of a Condition
 8447: 
 8448: # gets the value of a specific preevaluated condition
 8449: #    stored in the string  $env{user.state.<cid>}
 8450: # or looks up a condition reference in the bighash and if if hasn't
 8451: # already been evaluated recurses into docondval to get the value of
 8452: # the condition, then memoizing it to 
 8453: #   $env{user.state.<cid>.<condition>}
 8454: sub directcondval {
 8455:     my $number=shift;
 8456:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 8457: 	&Apache::lonuserstate::evalstate();
 8458:     }
 8459:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 8460: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 8461:     } elsif ($number =~ /^_/) {
 8462: 	my $sub_condition;
 8463: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8464: 		&GDBM_READER(),0640)) {
 8465: 	    $sub_condition=$bighash{'conditions'.$number};
 8466: 	    untie(%bighash);
 8467: 	}
 8468: 	my $value = &docondval($sub_condition);
 8469: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
 8470: 	return $value;
 8471:     }
 8472:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 8473:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 8474:     } else {
 8475:        return 2;
 8476:     }
 8477: }
 8478: 
 8479: # get the collection of conditions for this resource
 8480: sub condval {
 8481:     my $condidx=shift;
 8482:     my $allpathcond='';
 8483:     foreach my $cond (split(/\|/,$condidx)) {
 8484: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 8485: 	    $allpathcond.=
 8486: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 8487: 	}
 8488:     }
 8489:     $allpathcond=~s/\|$//;
 8490:     return &docondval($allpathcond);
 8491: }
 8492: 
 8493: #evaluates an expression of conditions
 8494: sub docondval {
 8495:     my ($allpathcond) = @_;
 8496:     my $result=0;
 8497:     if ($env{'request.course.id'}
 8498: 	&& defined($allpathcond)) {
 8499: 	my $operand='|';
 8500: 	my @stack;
 8501: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 8502: 	    if ($chunk eq '(') {
 8503: 		push @stack,($operand,$result);
 8504: 	    } elsif ($chunk eq ')') {
 8505: 		my $before=pop @stack;
 8506: 		if (pop @stack eq '&') {
 8507: 		    $result=$result>$before?$before:$result;
 8508: 		} else {
 8509: 		    $result=$result>$before?$result:$before;
 8510: 		}
 8511: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 8512: 		$operand=$chunk;
 8513: 	    } else {
 8514: 		my $new=directcondval($chunk);
 8515: 		if ($operand eq '&') {
 8516: 		    $result=$result>$new?$new:$result;
 8517: 		} else {
 8518: 		    $result=$result>$new?$result:$new;
 8519: 		}
 8520: 	    }
 8521: 	}
 8522:     }
 8523:     return $result;
 8524: }
 8525: 
 8526: # ---------------------------------------------------- Devalidate courseresdata
 8527: 
 8528: sub devalidatecourseresdata {
 8529:     my ($coursenum,$coursedomain)=@_;
 8530:     my $hashid=$coursenum.':'.$coursedomain;
 8531:     &devalidate_cache_new('courseres',$hashid);
 8532: }
 8533: 
 8534: 
 8535: # --------------------------------------------------- Course Resourcedata Query
 8536: #
 8537: #  Parameters:
 8538: #      $coursenum    - Number of the course.
 8539: #      $coursedomain - Domain at which the course was created.
 8540: #  Returns:
 8541: #     A hash of the course parameters along (I think) with timestamps
 8542: #     and version info.
 8543: 
 8544: sub get_courseresdata {
 8545:     my ($coursenum,$coursedomain)=@_;
 8546:     my $coursehom=&homeserver($coursenum,$coursedomain);
 8547:     my $hashid=$coursenum.':'.$coursedomain;
 8548:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 8549:     my %dumpreply;
 8550:     unless (defined($cached)) {
 8551: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 8552: 	$result=\%dumpreply;
 8553: 	my ($tmp) = keys(%dumpreply);
 8554: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 8555: 	    &do_cache_new('courseres',$hashid,$result,600);
 8556: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 8557: 	    return $tmp;
 8558: 	} elsif ($tmp =~ /^(error)/) {
 8559: 	    $result=undef;
 8560: 	    &do_cache_new('courseres',$hashid,$result,600);
 8561: 	}
 8562:     }
 8563:     return $result;
 8564: }
 8565: 
 8566: sub devalidateuserresdata {
 8567:     my ($uname,$udom)=@_;
 8568:     my $hashid="$udom:$uname";
 8569:     &devalidate_cache_new('userres',$hashid);
 8570: }
 8571: 
 8572: sub get_userresdata {
 8573:     my ($uname,$udom)=@_;
 8574:     #most student don\'t have any data set, check if there is some data
 8575:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 8576: 
 8577:     my $hashid="$udom:$uname";
 8578:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 8579:     if (!defined($cached)) {
 8580: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 8581: 	$result=\%resourcedata;
 8582: 	&do_cache_new('userres',$hashid,$result,600);
 8583:     }
 8584:     my ($tmp)=keys(%$result);
 8585:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 8586: 	return $result;
 8587:     }
 8588:     #error 2 occurs when the .db doesn't exist
 8589:     if ($tmp!~/error: 2 /) {
 8590: 	&logthis("<font color=\"blue\">WARNING:".
 8591: 		 " Trying to get resource data for ".
 8592: 		 $uname." at ".$udom.": ".
 8593: 		 $tmp."</font>");
 8594:     } elsif ($tmp=~/error: 2 /) {
 8595: 	#&EXT_cache_set($udom,$uname);
 8596: 	&do_cache_new('userres',$hashid,undef,600);
 8597: 	undef($tmp); # not really an error so don't send it back
 8598:     }
 8599:     return $tmp;
 8600: }
 8601: #----------------------------------------------- resdata - return resource data
 8602: #  Purpose:
 8603: #    Return resource data for either users or for a course.
 8604: #  Parameters:
 8605: #     $name      - Course/user name.
 8606: #     $domain    - Name of the domain the user/course is registered on.
 8607: #     $type      - Type of thing $name is (must be 'course' or 'user'
 8608: #     @which     - Array of names of resources desired.
 8609: #  Returns:
 8610: #     The value of the first reasource in @which that is found in the
 8611: #     resource hash.
 8612: #  Exceptional Conditions:
 8613: #     If the $type passed in is not valid (not the string 'course' or 
 8614: #     'user', an undefined  reference is returned.
 8615: #     If none of the resources are found, an undef is returned
 8616: sub resdata {
 8617:     my ($name,$domain,$type,@which)=@_;
 8618:     my $result;
 8619:     if ($type eq 'course') {
 8620: 	$result=&get_courseresdata($name,$domain);
 8621:     } elsif ($type eq 'user') {
 8622: 	$result=&get_userresdata($name,$domain);
 8623:     }
 8624:     if (!ref($result)) { return $result; }    
 8625:     foreach my $item (@which) {
 8626: 	if (defined($result->{$item->[0]})) {
 8627: 	    return [$result->{$item->[0]},$item->[1]];
 8628: 	}
 8629:     }
 8630:     return undef;
 8631: }
 8632: 
 8633: #
 8634: # EXT resource caching routines
 8635: #
 8636: 
 8637: sub clear_EXT_cache_status {
 8638:     &delenv('cache.EXT.');
 8639: }
 8640: 
 8641: sub EXT_cache_status {
 8642:     my ($target_domain,$target_user) = @_;
 8643:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 8644:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 8645:         # We know already the user has no data
 8646:         return 1;
 8647:     } else {
 8648:         return 0;
 8649:     }
 8650: }
 8651: 
 8652: sub EXT_cache_set {
 8653:     my ($target_domain,$target_user) = @_;
 8654:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 8655:     #&appenv({$cachename => time});
 8656: }
 8657: 
 8658: # --------------------------------------------------------- Value of a Variable
 8659: sub EXT {
 8660: 
 8661:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
 8662:     unless ($varname) { return ''; }
 8663:     #get real user name/domain, courseid and symb
 8664:     my $courseid;
 8665:     my $publicuser;
 8666:     if ($symbparm) {
 8667: 	$symbparm=&get_symb_from_alias($symbparm);
 8668:     }
 8669:     if (!($uname && $udom)) {
 8670:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 8671:       if (!$symbparm) {	$symbparm=$cursymb; }
 8672:     } else {
 8673: 	$courseid=$env{'request.course.id'};
 8674:     }
 8675:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 8676:     my $rest;
 8677:     if (defined($therest[0])) {
 8678:        $rest=join('.',@therest);
 8679:     } else {
 8680:        $rest='';
 8681:     }
 8682: 
 8683:     my $qualifierrest=$qualifier;
 8684:     if ($rest) { $qualifierrest.='.'.$rest; }
 8685:     my $spacequalifierrest=$space;
 8686:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 8687:     if ($realm eq 'user') {
 8688: # --------------------------------------------------------------- user.resource
 8689: 	if ($space eq 'resource') {
 8690: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 8691: 		  || defined($Apache::lonhomework::parsing_a_task))
 8692: 		 &&
 8693: 		 ($symbparm eq &symbread()) ) {	
 8694: 		# if we are in the middle of processing the resource the
 8695: 		# get the value we are planning on committing
 8696:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 8697:                     return $Apache::lonhomework::results{$qualifierrest};
 8698:                 } else {
 8699:                     return $Apache::lonhomework::history{$qualifierrest};
 8700:                 }
 8701: 	    } else {
 8702: 		my %restored;
 8703: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 8704: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 8705: 		} else {
 8706: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 8707: 		}
 8708: 		return $restored{$qualifierrest};
 8709: 	    }
 8710: # ----------------------------------------------------------------- user.access
 8711:         } elsif ($space eq 'access') {
 8712: 	    # FIXME - not supporting calls for a specific user
 8713:             return &allowed($qualifier,$rest);
 8714: # ------------------------------------------ user.preferences, user.environment
 8715:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 8716: 	    if (($uname eq $env{'user.name'}) &&
 8717: 		($udom eq $env{'user.domain'})) {
 8718: 		return $env{join('.',('environment',$qualifierrest))};
 8719: 	    } else {
 8720: 		my %returnhash;
 8721: 		if (!$publicuser) {
 8722: 		    %returnhash=&userenvironment($udom,$uname,
 8723: 						 $qualifierrest);
 8724: 		}
 8725: 		return $returnhash{$qualifierrest};
 8726: 	    }
 8727: # ----------------------------------------------------------------- user.course
 8728:         } elsif ($space eq 'course') {
 8729: 	    # FIXME - not supporting calls for a specific user
 8730:             return $env{join('.',('request.course',$qualifier))};
 8731: # ------------------------------------------------------------------- user.role
 8732:         } elsif ($space eq 'role') {
 8733: 	    # FIXME - not supporting calls for a specific user
 8734:             my ($role,$where)=split(/\./,$env{'request.role'});
 8735:             if ($qualifier eq 'value') {
 8736: 		return $role;
 8737:             } elsif ($qualifier eq 'extent') {
 8738:                 return $where;
 8739:             }
 8740: # ----------------------------------------------------------------- user.domain
 8741:         } elsif ($space eq 'domain') {
 8742:             return $udom;
 8743: # ------------------------------------------------------------------- user.name
 8744:         } elsif ($space eq 'name') {
 8745:             return $uname;
 8746: # ---------------------------------------------------- Any other user namespace
 8747:         } else {
 8748: 	    my %reply;
 8749: 	    if (!$publicuser) {
 8750: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 8751: 	    }
 8752: 	    return $reply{$qualifierrest};
 8753:         }
 8754:     } elsif ($realm eq 'query') {
 8755: # ---------------------------------------------- pull stuff out of query string
 8756:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 8757: 						[$spacequalifierrest]);
 8758: 	return $env{'form.'.$spacequalifierrest}; 
 8759:    } elsif ($realm eq 'request') {
 8760: # ------------------------------------------------------------- request.browser
 8761:         if ($space eq 'browser') {
 8762:             return $env{'browser.'.$qualifier};
 8763: # ------------------------------------------------------------ request.filename
 8764:         } else {
 8765:             return $env{'request.'.$spacequalifierrest};
 8766:         }
 8767:     } elsif ($realm eq 'course') {
 8768: # ---------------------------------------------------------- course.description
 8769:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 8770:     } elsif ($realm eq 'resource') {
 8771: 
 8772: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 8773: 	    if (!$symbparm) { $symbparm=&symbread(); }
 8774: 	}
 8775: 
 8776: 	if ($space eq 'title') {
 8777: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 8778: 	    return &gettitle($symbparm);
 8779: 	}
 8780: 	
 8781: 	if ($space eq 'map') {
 8782: 	    my ($map) = &decode_symb($symbparm);
 8783: 	    return &symbread($map);
 8784: 	}
 8785: 	if ($space eq 'filename') {
 8786: 	    if ($symbparm) {
 8787: 		return &clutter((&decode_symb($symbparm))[2]);
 8788: 	    }
 8789: 	    return &hreflocation('',$env{'request.filename'});
 8790: 	}
 8791: 
 8792: 	my ($section, $group, @groups);
 8793: 	my ($courselevelm,$courselevel);
 8794: 	if ($symbparm && defined($courseid) && 
 8795: 	    $courseid eq $env{'request.course.id'}) {
 8796: 
 8797: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 8798: 
 8799: # ----------------------------------------------------- Cascading lookup scheme
 8800: 	    my $symbp=$symbparm;
 8801: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 8802: 
 8803: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 8804: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 8805: 
 8806: 	    if (($env{'user.name'} eq $uname) &&
 8807: 		($env{'user.domain'} eq $udom)) {
 8808: 		$section=$env{'request.course.sec'};
 8809:                 @groups = split(/:/,$env{'request.course.groups'});  
 8810:                 @groups=&sort_course_groups($courseid,@groups); 
 8811: 	    } else {
 8812: 		if (! defined($usection)) {
 8813: 		    $section=&getsection($udom,$uname,$courseid);
 8814: 		} else {
 8815: 		    $section = $usection;
 8816: 		}
 8817:                 @groups = &get_users_groups($udom,$uname,$courseid);
 8818: 	    }
 8819: 
 8820: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 8821: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 8822: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 8823: 
 8824: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 8825: 	    my $courselevelr=$courseid.'.'.$symbparm;
 8826: 	    $courselevelm=$courseid.'.'.$mapparm;
 8827: 
 8828: # ----------------------------------------------------------- first, check user
 8829: 
 8830: 	    my $userreply=&resdata($uname,$udom,'user',
 8831: 				       ([$courselevelr,'resource'],
 8832: 					[$courselevelm,'map'     ],
 8833: 					[$courselevel, 'course'  ]));
 8834: 	    if (defined($userreply)) { return &get_reply($userreply); }
 8835: 
 8836: # ------------------------------------------------ second, check some of course
 8837:             my $coursereply;
 8838:             if (@groups > 0) {
 8839:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 8840:                                        $mapparm,$spacequalifierrest);
 8841:                 if (defined($coursereply)) { return &get_reply($coursereply); }
 8842:             }
 8843: 
 8844: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 8845: 				  $env{'course.'.$courseid.'.domain'},
 8846: 				  'course',
 8847: 				  ([$seclevelr,   'resource'],
 8848: 				   [$seclevelm,   'map'     ],
 8849: 				   [$seclevel,    'course'  ],
 8850: 				   [$courselevelr,'resource']));
 8851: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 8852: 
 8853: # ------------------------------------------------------ third, check map parms
 8854: 	    my %parmhash=();
 8855: 	    my $thisparm='';
 8856: 	    if (tie(%parmhash,'GDBM_File',
 8857: 		    $env{'request.course.fn'}.'_parms.db',
 8858: 		    &GDBM_READER(),0640)) {
 8859: 		$thisparm=$parmhash{$symbparm};
 8860: 		untie(%parmhash);
 8861: 	    }
 8862: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
 8863: 	}
 8864: # ------------------------------------------ fourth, look in resource metadata
 8865: 
 8866: 	$spacequalifierrest=~s/\./\_/;
 8867: 	my $filename;
 8868: 	if (!$symbparm) { $symbparm=&symbread(); }
 8869: 	if ($symbparm) {
 8870: 	    $filename=(&decode_symb($symbparm))[2];
 8871: 	} else {
 8872: 	    $filename=$env{'request.filename'};
 8873: 	}
 8874: 	my $metadata=&metadata($filename,$spacequalifierrest);
 8875: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 8876: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 8877: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 8878: 
 8879: # ---------------------------------------------- fourth, look in rest of course
 8880: 	if ($symbparm && defined($courseid) && 
 8881: 	    $courseid eq $env{'request.course.id'}) {
 8882: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 8883: 				     $env{'course.'.$courseid.'.domain'},
 8884: 				     'course',
 8885: 				     ([$courselevelm,'map'   ],
 8886: 				      [$courselevel, 'course']));
 8887: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 8888: 	}
 8889: # ------------------------------------------------------------------ Cascade up
 8890: 	unless ($space eq '0') {
 8891: 	    my @parts=split(/_/,$space);
 8892: 	    my $id=pop(@parts);
 8893: 	    my $part=join('_',@parts);
 8894: 	    if ($part eq '') { $part='0'; }
 8895: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 8896: 				 $symbparm,$udom,$uname,$section,1);
 8897: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
 8898: 	}
 8899: 	if ($recurse) { return undef; }
 8900: 	my $pack_def=&packages_tab_default($filename,$varname);
 8901: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
 8902: # ---------------------------------------------------- Any other user namespace
 8903:     } elsif ($realm eq 'environment') {
 8904: # ----------------------------------------------------------------- environment
 8905: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 8906: 	    return $env{'environment.'.$spacequalifierrest};
 8907: 	} else {
 8908: 	    if ($uname eq 'anonymous' && $udom eq '') {
 8909: 		return '';
 8910: 	    }
 8911: 	    my %returnhash=&userenvironment($udom,$uname,
 8912: 					    $spacequalifierrest);
 8913: 	    return $returnhash{$spacequalifierrest};
 8914: 	}
 8915:     } elsif ($realm eq 'system') {
 8916: # ----------------------------------------------------------------- system.time
 8917: 	if ($space eq 'time') {
 8918: 	    return time;
 8919:         }
 8920:     } elsif ($realm eq 'server') {
 8921: # ----------------------------------------------------------------- system.time
 8922: 	if ($space eq 'name') {
 8923: 	    return $ENV{'SERVER_NAME'};
 8924:         }
 8925:     }
 8926:     return '';
 8927: }
 8928: 
 8929: sub get_reply {
 8930:     my ($reply_value) = @_;
 8931:     if (ref($reply_value) eq 'ARRAY') {
 8932:         if (wantarray) {
 8933: 	    return @$reply_value;
 8934:         }
 8935:         return $reply_value->[0];
 8936:     } else {
 8937:         return $reply_value;
 8938:     }
 8939: }
 8940: 
 8941: sub check_group_parms {
 8942:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
 8943:     my @groupitems = ();
 8944:     my $resultitem;
 8945:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
 8946:     foreach my $group (@{$groups}) {
 8947:         foreach my $level (@levels) {
 8948:              my $item = $courseid.'.['.$group.'].'.$level->[0];
 8949:              push(@groupitems,[$item,$level->[1]]);
 8950:         }
 8951:     }
 8952:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
 8953:                             $env{'course.'.$courseid.'.domain'},
 8954:                                      'course',@groupitems);
 8955:     return $coursereply;
 8956: }
 8957: 
 8958: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
 8959:     my ($courseid,@groups) = @_;
 8960:     @groups = sort(@groups);
 8961:     return @groups;
 8962: }
 8963: 
 8964: sub packages_tab_default {
 8965:     my ($uri,$varname)=@_;
 8966:     my (undef,$part,$name)=split(/\./,$varname);
 8967: 
 8968:     my (@extension,@specifics,$do_default);
 8969:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
 8970: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 8971: 	if ($pack_type eq 'default') {
 8972: 	    $do_default=1;
 8973: 	} elsif ($pack_type eq 'extension') {
 8974: 	    push(@extension,[$package,$pack_type,$pack_part]);
 8975: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
 8976: 	    # only look at packages defaults for packages that this id is
 8977: 	    push(@specifics,[$package,$pack_type,$pack_part]);
 8978: 	}
 8979:     }
 8980:     # first look for a package that matches the requested part id
 8981:     foreach my $package (@specifics) {
 8982: 	my (undef,$pack_type,$pack_part)=@{$package};
 8983: 	next if ($pack_part ne $part);
 8984: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 8985: 	    return $packagetab{"$pack_type&$name&default"};
 8986: 	}
 8987:     }
 8988:     # look for any possible matching non extension_ package
 8989:     foreach my $package (@specifics) {
 8990: 	my (undef,$pack_type,$pack_part)=@{$package};
 8991: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 8992: 	    return $packagetab{"$pack_type&$name&default"};
 8993: 	}
 8994: 	if ($pack_type eq 'part') { $pack_part='0'; }
 8995: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
 8996: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
 8997: 	}
 8998:     }
 8999:     # look for any posible extension_ match
 9000:     foreach my $package (@extension) {
 9001: 	my ($package,$pack_type)=@{$package};
 9002: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 9003: 	    return $packagetab{"$pack_type&$name&default"};
 9004: 	}
 9005: 	if (defined($packagetab{$package."&$name&default"})) {
 9006: 	    return $packagetab{$package."&$name&default"};
 9007: 	}
 9008:     }
 9009:     # look for a global default setting
 9010:     if ($do_default && defined($packagetab{"default&$name&default"})) {
 9011: 	return $packagetab{"default&$name&default"};
 9012:     }
 9013:     return undef;
 9014: }
 9015: 
 9016: sub add_prefix_and_part {
 9017:     my ($prefix,$part)=@_;
 9018:     my $keyroot;
 9019:     if (defined($prefix) && $prefix !~ /^__/) {
 9020: 	# prefix that has a part already
 9021: 	$keyroot=$prefix;
 9022:     } elsif (defined($prefix)) {
 9023: 	# prefix that is missing a part
 9024: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 9025:     } else {
 9026: 	# no prefix at all
 9027: 	if (defined($part)) { $keyroot='_'.$part; }
 9028:     }
 9029:     return $keyroot;
 9030: }
 9031: 
 9032: # ---------------------------------------------------------------- Get metadata
 9033: 
 9034: my %metaentry;
 9035: my %importedpartids;
 9036: sub metadata {
 9037:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 9038:     $uri=&declutter($uri);
 9039:     # if it is a non metadata possible uri return quickly
 9040:     if (($uri eq '') || 
 9041: 	(($uri =~ m|^/*adm/|) && 
 9042: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
 9043:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
 9044: 	return undef;
 9045:     }
 9046:     if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) 
 9047: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
 9048: 	return undef;
 9049:     }
 9050:     my $filename=$uri;
 9051:     $uri=~s/\.meta$//;
 9052: #
 9053: # Is the metadata already cached?
 9054: # Look at timestamp of caching
 9055: # Everything is cached by the main uri, libraries are never directly cached
 9056: #
 9057:     if (!defined($liburi)) {
 9058: 	my ($result,$cached)=&is_cached_new('meta',$uri);
 9059: 	if (defined($cached)) { return $result->{':'.$what}; }
 9060:     }
 9061:     {
 9062: # Imported parts would go here
 9063:         my %importedids=();
 9064:         my @origfileimportpartids=();
 9065:         my $importedparts=0;
 9066: #
 9067: # Is this a recursive call for a library?
 9068: #
 9069: #	if (! exists($metacache{$uri})) {
 9070: #	    $metacache{$uri}={};
 9071: #	}
 9072: 	my $cachetime = 60*60;
 9073:         if ($liburi) {
 9074: 	    $liburi=&declutter($liburi);
 9075:             $filename=$liburi;
 9076:         } else {
 9077: 	    &devalidate_cache_new('meta',$uri);
 9078: 	    undef(%metaentry);
 9079: 	}
 9080:         my %metathesekeys=();
 9081:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 9082: 	my $metastring;
 9083: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
 9084: 	    my $which = &hreflocation('','/'.($liburi || $uri));
 9085: 	    $metastring = 
 9086: 		&Apache::lonnet::ssi_body($which,
 9087: 					  ('grade_target' => 'meta'));
 9088: 	    $cachetime = 1; # only want this cached in the child not long term
 9089: 	} elsif (($uri !~ m -^(editupload)/-) && 
 9090:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
 9091: 	    my $file=&filelocation('',&clutter($filename));
 9092: 	    #push(@{$metaentry{$uri.'.file'}},$file);
 9093: 	    $metastring=&getfile($file);
 9094: 	}
 9095:         my $parser=HTML::LCParser->new(\$metastring);
 9096:         my $token;
 9097:         undef %metathesekeys;
 9098:         while ($token=$parser->get_token) {
 9099: 	    if ($token->[0] eq 'S') {
 9100: 		if (defined($token->[2]->{'package'})) {
 9101: #
 9102: # This is a package - get package info
 9103: #
 9104: 		    my $package=$token->[2]->{'package'};
 9105: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 9106: 		    if (defined($token->[2]->{'id'})) { 
 9107: 			$keyroot.='_'.$token->[2]->{'id'}; 
 9108: 		    }
 9109: 		    if ($metaentry{':packages'}) {
 9110: 			$metaentry{':packages'}.=','.$package.$keyroot;
 9111: 		    } else {
 9112: 			$metaentry{':packages'}=$package.$keyroot;
 9113: 		    }
 9114: 		    foreach my $pack_entry (keys(%packagetab)) {
 9115: 			my $part=$keyroot;
 9116: 			$part=~s/^\_//;
 9117: 			if ($pack_entry=~/^\Q$package\E\&/ || 
 9118: 			    $pack_entry=~/^\Q$package\E_0\&/) {
 9119: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
 9120: 			    # ignore package.tab specified default values
 9121:                             # here &package_tab_default() will fetch those
 9122: 			    if ($subp eq 'default') { next; }
 9123: 			    my $value=$packagetab{$pack_entry};
 9124: 			    my $unikey;
 9125: 			    if ($pack =~ /_0$/) {
 9126: 				$unikey='parameter_0_'.$name;
 9127: 				$part=0;
 9128: 			    } else {
 9129: 				$unikey='parameter'.$keyroot.'_'.$name;
 9130: 			    }
 9131: 			    if ($subp eq 'display') {
 9132: 				$value.=' [Part: '.$part.']';
 9133: 			    }
 9134: 			    $metaentry{':'.$unikey.'.part'}=$part;
 9135: 			    $metathesekeys{$unikey}=1;
 9136: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 9137: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
 9138: 			    }
 9139: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
 9140: 				$metaentry{':'.$unikey}=
 9141: 				    $metaentry{':'.$unikey.'.default'};
 9142: 			    }
 9143: 			}
 9144: 		    }
 9145: 		} else {
 9146: #
 9147: # This is not a package - some other kind of start tag
 9148: #
 9149: 		    my $entry=$token->[1];
 9150: 		    my $unikey='';
 9151: 
 9152: 		    if ($entry eq 'import') {
 9153: #
 9154: # Importing a library here
 9155: #
 9156:                         my $location=$parser->get_text('/import');
 9157:                         my $dir=$filename;
 9158:                         $dir=~s|[^/]*$||;
 9159:                         $location=&filelocation($dir,$location);
 9160:                        
 9161:                         my $importmode=$token->[2]->{'importmode'};
 9162:                         if ($importmode eq 'problem') {
 9163: # Import as problem/response
 9164:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 9165:                         } elsif ($importmode eq 'part') {
 9166: # Import as part(s)
 9167:                            $importedparts=1;
 9168: # We need to get the original file and the imported file to get the part order correct
 9169: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
 9170: # Load and inspect original file
 9171:                            if ($#origfileimportpartids<0) {
 9172:                               undef(%importedpartids);
 9173:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
 9174:                               my $origfile=&getfile($origfilelocation);
 9175:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
 9176:                            }
 9177: 
 9178: # Load and inspect imported file
 9179:                            my $impfile=&getfile($location);
 9180:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
 9181:                            if ($#impfilepartids>=0) {
 9182: # This problem had parts
 9183:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
 9184:                            } else {
 9185: # Importing by turning a single problem into a problem part
 9186: # It gets the import-tags ID as part-ID
 9187:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
 9188:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
 9189:                            }
 9190:                         } else {
 9191: # Normal import
 9192:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 9193:                            if (defined($token->[2]->{'id'})) {
 9194:                               $unikey.='_'.$token->[2]->{'id'};
 9195:                            }
 9196:                         }
 9197: 
 9198: 			if ($depthcount<20) {
 9199: 			    my $metadata = 
 9200: 				&metadata($uri,'keys', $location,$unikey,
 9201: 					  $depthcount+1);
 9202: 			    foreach my $meta (split(',',$metadata)) {
 9203: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
 9204: 				$metathesekeys{$meta}=1;
 9205: 			    }
 9206: 			
 9207:                         }
 9208: 		    } else {
 9209: #
 9210: # Not importing, some other kind of non-package, non-library start tag
 9211: # 
 9212:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
 9213:                         if (defined($token->[2]->{'id'})) {
 9214:                             $unikey.='_'.$token->[2]->{'id'};
 9215:                         }
 9216: 			if (defined($token->[2]->{'name'})) { 
 9217: 			    $unikey.='_'.$token->[2]->{'name'}; 
 9218: 			}
 9219: 			$metathesekeys{$unikey}=1;
 9220: 			foreach my $param (@{$token->[3]}) {
 9221: 			    $metaentry{':'.$unikey.'.'.$param} =
 9222: 				$token->[2]->{$param};
 9223: 			}
 9224: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
 9225: 			my $default=$metaentry{':'.$unikey.'.default'};
 9226: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
 9227: 		 # only ws inside the tag, and not in default, so use default
 9228: 		 # as value
 9229: 			    $metaentry{':'.$unikey}=$default;
 9230: 			} elsif ( $internaltext =~ /\S/ ) {
 9231: 		  # something interesting inside the tag
 9232: 			    $metaentry{':'.$unikey}=$internaltext;
 9233: 			} else {
 9234: 		  # no interesting values, don't set a default
 9235: 			}
 9236: # end of not-a-package not-a-library import
 9237: 		    }
 9238: # end of not-a-package start tag
 9239: 		}
 9240: # the next is the end of "start tag"
 9241: 	    }
 9242: 	}
 9243: 	my ($extension) = ($uri =~ /\.(\w+)$/);
 9244: 	$extension = lc($extension);
 9245: 	if ($extension eq 'htm') { $extension='html'; }
 9246: 
 9247: 	foreach my $key (keys(%packagetab)) {
 9248: 	    #no specific packages #how's our extension
 9249: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
 9250: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
 9251: 					 \%metathesekeys);
 9252: 	}
 9253: 
 9254: 	if (!exists($metaentry{':packages'})
 9255: 	    || $packagetab{"import_defaults&extension_$extension"}) {
 9256: 	    foreach my $key (keys(%packagetab)) {
 9257: 		#no specific packages well let's get default then
 9258: 		if ($key!~/^default&/) { next; }
 9259: 		&metadata_create_package_def($uri,$key,'default',
 9260: 					     \%metathesekeys);
 9261: 	    }
 9262: 	}
 9263: # are there custom rights to evaluate
 9264: 	if ($metaentry{':copyright'} eq 'custom') {
 9265: 
 9266:     #
 9267:     # Importing a rights file here
 9268:     #
 9269: 	    unless ($depthcount) {
 9270: 		my $location=$metaentry{':customdistributionfile'};
 9271: 		my $dir=$filename;
 9272: 		$dir=~s|[^/]*$||;
 9273: 		$location=&filelocation($dir,$location);
 9274: 		my $rights_metadata =
 9275: 		    &metadata($uri,'keys',$location,'_rights',
 9276: 			      $depthcount+1);
 9277: 		foreach my $rights (split(',',$rights_metadata)) {
 9278: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
 9279: 		    $metathesekeys{$rights}=1;
 9280: 		}
 9281: 	    }
 9282: 	}
 9283: 	# uniqifiy package listing
 9284: 	my %seen;
 9285: 	my @uniq_packages =
 9286: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
 9287: 	$metaentry{':packages'} = join(',',@uniq_packages);
 9288: 
 9289:         if ($importedparts) {
 9290: # We had imported parts and need to rebuild partorder
 9291:            $metaentry{':partorder'}='';
 9292:            $metathesekeys{'partorder'}=1;
 9293:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
 9294:                if ($origfileimportpartids[$index] eq 'part') {
 9295: # original part, part of the problem
 9296:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
 9297:                } else {
 9298: # we have imported parts at this position
 9299:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
 9300:                }
 9301:            }
 9302:            $metaentry{':partorder'}=~s/^\,//;
 9303:         }
 9304: 
 9305: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
 9306: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
 9307: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
 9308: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
 9309: # this is the end of "was not already recently cached
 9310:     }
 9311:     return $metaentry{':'.$what};
 9312: }
 9313: 
 9314: sub metadata_create_package_def {
 9315:     my ($uri,$key,$package,$metathesekeys)=@_;
 9316:     my ($pack,$name,$subp)=split(/\&/,$key);
 9317:     if ($subp eq 'default') { next; }
 9318:     
 9319:     if (defined($metaentry{':packages'})) {
 9320: 	$metaentry{':packages'}.=','.$package;
 9321:     } else {
 9322: 	$metaentry{':packages'}=$package;
 9323:     }
 9324:     my $value=$packagetab{$key};
 9325:     my $unikey;
 9326:     $unikey='parameter_0_'.$name;
 9327:     $metaentry{':'.$unikey.'.part'}=0;
 9328:     $$metathesekeys{$unikey}=1;
 9329:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 9330: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
 9331:     }
 9332:     if (defined($metaentry{':'.$unikey.'.default'})) {
 9333: 	$metaentry{':'.$unikey}=
 9334: 	    $metaentry{':'.$unikey.'.default'};
 9335:     }
 9336: }
 9337: 
 9338: sub metadata_generate_part0 {
 9339:     my ($metadata,$metacache,$uri) = @_;
 9340:     my %allnames;
 9341:     foreach my $metakey (keys(%$metadata)) {
 9342: 	if ($metakey=~/^parameter\_(.*)/) {
 9343: 	  my $part=$$metacache{':'.$metakey.'.part'};
 9344: 	  my $name=$$metacache{':'.$metakey.'.name'};
 9345: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
 9346: 	    $allnames{$name}=$part;
 9347: 	  }
 9348: 	}
 9349:     }
 9350:     foreach my $name (keys(%allnames)) {
 9351:       $$metadata{"parameter_0_$name"}=1;
 9352:       my $key=":parameter_0_$name";
 9353:       $$metacache{"$key.part"}='0';
 9354:       $$metacache{"$key.name"}=$name;
 9355:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
 9356: 					   $allnames{$name}.'_'.$name.
 9357: 					   '.type'};
 9358:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
 9359: 			     '.display'};
 9360:       my $expr='[Part: '.$allnames{$name}.']';
 9361:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
 9362:       $$metacache{"$key.display"}=$olddis;
 9363:     }
 9364: }
 9365: 
 9366: # ------------------------------------------------------ Devalidate title cache
 9367: 
 9368: sub devalidate_title_cache {
 9369:     my ($url)=@_;
 9370:     if (!$env{'request.course.id'}) { return; }
 9371:     my $symb=&symbread($url);
 9372:     if (!$symb) { return; }
 9373:     my $key=$env{'request.course.id'}."\0".$symb;
 9374:     &devalidate_cache_new('title',$key);
 9375: }
 9376: 
 9377: # ------------------------------------------------- Get the title of a course
 9378: 
 9379: sub current_course_title {
 9380:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
 9381: }
 9382: # ------------------------------------------------- Get the title of a resource
 9383: 
 9384: sub gettitle {
 9385:     my $urlsymb=shift;
 9386:     my $symb=&symbread($urlsymb);
 9387:     if ($symb) {
 9388: 	my $key=$env{'request.course.id'}."\0".$symb;
 9389: 	my ($result,$cached)=&is_cached_new('title',$key);
 9390: 	if (defined($cached)) { 
 9391: 	    return $result;
 9392: 	}
 9393: 	my ($map,$resid,$url)=&decode_symb($symb);
 9394: 	my $title='';
 9395: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
 9396: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
 9397: 	} else {
 9398: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9399: 		    &GDBM_READER(),0640)) {
 9400: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
 9401: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
 9402: 		untie(%bighash);
 9403: 	    }
 9404: 	}
 9405: 	$title=~s/\&colon\;/\:/gs;
 9406: 	if ($title) {
 9407: 	    return &do_cache_new('title',$key,$title,600);
 9408: 	}
 9409: 	$urlsymb=$url;
 9410:     }
 9411:     my $title=&metadata($urlsymb,'title');
 9412:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
 9413:     return $title;
 9414: }
 9415: 
 9416: sub get_slot {
 9417:     my ($which,$cnum,$cdom)=@_;
 9418:     if (!$cnum || !$cdom) {
 9419: 	(undef,my $courseid)=&whichuser();
 9420: 	$cdom=$env{'course.'.$courseid.'.domain'};
 9421: 	$cnum=$env{'course.'.$courseid.'.num'};
 9422:     }
 9423:     my $key=join("\0",'slots',$cdom,$cnum,$which);
 9424:     my %slotinfo;
 9425:     if (exists($remembered{$key})) {
 9426: 	$slotinfo{$which} = $remembered{$key};
 9427:     } else {
 9428: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
 9429: 	&Apache::lonhomework::showhash(%slotinfo);
 9430: 	my ($tmp)=keys(%slotinfo);
 9431: 	if ($tmp=~/^error:/) { return (); }
 9432: 	$remembered{$key} = $slotinfo{$which};
 9433:     }
 9434:     if (ref($slotinfo{$which}) eq 'HASH') {
 9435: 	return %{$slotinfo{$which}};
 9436:     }
 9437:     return $slotinfo{$which};
 9438: }
 9439: 
 9440: sub get_reservable_slots {
 9441:     my ($cnum,$cdom,$uname,$udom) = @_;
 9442:     my $now = time;
 9443:     my $reservable_info;
 9444:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
 9445:     if (exists($remembered{$key})) {
 9446:         $reservable_info = $remembered{$key};
 9447:     } else {
 9448:         my %resv;
 9449:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
 9450:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
 9451:         $reservable_info = \%resv;
 9452:         $remembered{$key} = $reservable_info;
 9453:     }
 9454:     return $reservable_info;
 9455: }
 9456: 
 9457: sub get_course_slots {
 9458:     my ($cnum,$cdom) = @_;
 9459:     my $hashid=$cnum.':'.$cdom;
 9460:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
 9461:     if (defined($cached)) {
 9462:         if (ref($result) eq 'HASH') {
 9463:             return %{$result};
 9464:         }
 9465:     } else {
 9466:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
 9467:         my ($tmp) = keys(%slots);
 9468:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 9469:             &Apache::lonnet::do_cache_new('allslots',$hashid,\%slots,600);
 9470:             return %slots;
 9471:         }
 9472:     }
 9473:     return;
 9474: }
 9475: 
 9476: sub devalidate_slots_cache {
 9477:     my ($cnum,$cdom)=@_;
 9478:     my $hashid=$cnum.':'.$cdom;
 9479:     &devalidate_cache_new('allslots',$hashid);
 9480: }
 9481: 
 9482: # ------------------------------------------------- Update symbolic store links
 9483: 
 9484: sub symblist {
 9485:     my ($mapname,%newhash)=@_;
 9486:     $mapname=&deversion(&declutter($mapname));
 9487:     my %hash;
 9488:     if (($env{'request.course.fn'}) && (%newhash)) {
 9489:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 9490:                       &GDBM_WRCREAT(),0640)) {
 9491: 	    foreach my $url (keys(%newhash)) {
 9492: 		next if ($url eq 'last_known'
 9493: 			 && $env{'form.no_update_last_known'});
 9494: 		$hash{declutter($url)}=&encode_symb($mapname,
 9495: 						    $newhash{$url}->[1],
 9496: 						    $newhash{$url}->[0]);
 9497:             }
 9498:             if (untie(%hash)) {
 9499: 		return 'ok';
 9500:             }
 9501:         }
 9502:     }
 9503:     return 'error';
 9504: }
 9505: 
 9506: # --------------------------------------------------------------- Verify a symb
 9507: 
 9508: sub symbverify {
 9509:     my ($symb,$thisurl)=@_;
 9510:     my $thisfn=$thisurl;
 9511:     $thisfn=&declutter($thisfn);
 9512: # direct jump to resource in page or to a sequence - will construct own symbs
 9513:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
 9514: # check URL part
 9515:     my ($map,$resid,$url)=&decode_symb($symb);
 9516: 
 9517:     unless ($url eq $thisfn) { return 0; }
 9518: 
 9519:     $symb=&symbclean($symb);
 9520:     $thisurl=&deversion($thisurl);
 9521:     $thisfn=&deversion($thisfn);
 9522: 
 9523:     my %bighash;
 9524:     my $okay=0;
 9525: 
 9526:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9527:                             &GDBM_READER(),0640)) {
 9528:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
 9529:             $thisurl =~ s/\?.+$//;
 9530:         }
 9531:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
 9532:         unless ($ids) {
 9533:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
 9534:             $ids=$bighash{$idkey};
 9535:         }
 9536:         if ($ids) {
 9537: # ------------------------------------------------------------------- Has ID(s)
 9538: 	    foreach my $id (split(/\,/,$ids)) {
 9539: 	       my ($mapid,$resid)=split(/\./,$id);
 9540:                if ($thisfn =~ m{^/adm/wrapper/ext/}) {
 9541:                    $symb =~ s/\?.+$//;
 9542:                }
 9543:                if (
 9544:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
 9545:    eq $symb) { 
 9546: 		   if (($env{'request.role.adv'}) ||
 9547: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
 9548:                        ($thisurl eq '/adm/navmaps')) {
 9549: 		       $okay=1; 
 9550: 		   }
 9551: 	       }
 9552: 	   }
 9553:         }
 9554: 	untie(%bighash);
 9555:     }
 9556:     return $okay;
 9557: }
 9558: 
 9559: # --------------------------------------------------------------- Clean-up symb
 9560: 
 9561: sub symbclean {
 9562:     my $symb=shift;
 9563:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 9564: # remove version from map
 9565:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
 9566: 
 9567: # remove version from URL
 9568:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
 9569: 
 9570: # remove wrapper
 9571: 
 9572:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
 9573:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
 9574:     return $symb;
 9575: }
 9576: 
 9577: # ---------------------------------------------- Split symb to find map and url
 9578: 
 9579: sub encode_symb {
 9580:     my ($map,$resid,$url)=@_;
 9581:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
 9582: }
 9583: 
 9584: sub decode_symb {
 9585:     my $symb=shift;
 9586:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 9587:     my ($map,$resid,$url)=split(/___/,$symb);
 9588:     return (&fixversion($map),$resid,&fixversion($url));
 9589: }
 9590: 
 9591: sub fixversion {
 9592:     my $fn=shift;
 9593:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
 9594:     my %bighash;
 9595:     my $uri=&clutter($fn);
 9596:     my $key=$env{'request.course.id'}.'_'.$uri;
 9597: # is this cached?
 9598:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
 9599:     if (defined($cached)) { return $result; }
 9600: # unfortunately not cached, or expired
 9601:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9602: 	    &GDBM_READER(),0640)) {
 9603:  	if ($bighash{'version_'.$uri}) {
 9604:  	    my $version=$bighash{'version_'.$uri};
 9605:  	    unless (($version eq 'mostrecent') || 
 9606: 		    ($version==&getversion($uri))) {
 9607:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
 9608:  	    }
 9609:  	}
 9610:  	untie %bighash;
 9611:     }
 9612:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
 9613: }
 9614: 
 9615: sub deversion {
 9616:     my $url=shift;
 9617:     $url=~s/\.\d+\.(\w+)$/\.$1/;
 9618:     return $url;
 9619: }
 9620: 
 9621: # ------------------------------------------------------ Return symb list entry
 9622: 
 9623: sub symbread {
 9624:     my ($thisfn,$donotrecurse)=@_;
 9625:     my $cache_str='request.symbread.cached.'.$thisfn;
 9626:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
 9627: # no filename provided? try from environment
 9628:     unless ($thisfn) {
 9629:         if ($env{'request.symb'}) {
 9630: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
 9631: 	}
 9632: 	$thisfn=$env{'request.filename'};
 9633:     }
 9634:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 9635: # is that filename actually a symb? Verify, clean, and return
 9636:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
 9637: 	if (&symbverify($thisfn,$1)) {
 9638: 	    return $env{$cache_str}=&symbclean($thisfn);
 9639: 	}
 9640:     }
 9641:     $thisfn=declutter($thisfn);
 9642:     my %hash;
 9643:     my %bighash;
 9644:     my $syval='';
 9645:     if (($env{'request.course.fn'}) && ($thisfn)) {
 9646:         my $targetfn = $thisfn;
 9647:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
 9648:             $targetfn = 'adm/wrapper/'.$thisfn;
 9649:         }
 9650: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
 9651: 	    $targetfn=$1;
 9652: 	}
 9653:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 9654:                       &GDBM_READER(),0640)) {
 9655: 	    $syval=$hash{$targetfn};
 9656:             untie(%hash);
 9657:         }
 9658: # ---------------------------------------------------------- There was an entry
 9659:         if ($syval) {
 9660: 	    #unless ($syval=~/\_\d+$/) {
 9661: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
 9662: 		    #&appenv({'request.ambiguous' => $thisfn});
 9663: 		    #return $env{$cache_str}='';
 9664: 		#}    
 9665: 		#$syval.=$1;
 9666: 	    #}
 9667:         } else {
 9668: # ------------------------------------------------------- Was not in symb table
 9669:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9670:                             &GDBM_READER(),0640)) {
 9671: # ---------------------------------------------- Get ID(s) for current resource
 9672:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
 9673:               unless ($ids) { 
 9674:                  $ids=$bighash{'ids_/'.$thisfn};
 9675:               }
 9676:               unless ($ids) {
 9677: # alias?
 9678: 		  $ids=$bighash{'mapalias_'.$thisfn};
 9679:               }
 9680:               if ($ids) {
 9681: # ------------------------------------------------------------------- Has ID(s)
 9682:                  my @possibilities=split(/\,/,$ids);
 9683:                  if ($#possibilities==0) {
 9684: # ----------------------------------------------- There is only one possibility
 9685: 		     my ($mapid,$resid)=split(/\./,$ids);
 9686: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
 9687: 						    $resid,$thisfn);
 9688:                  } elsif (!$donotrecurse) {
 9689: # ------------------------------------------ There is more than one possibility
 9690:                      my $realpossible=0;
 9691:                      foreach my $id (@possibilities) {
 9692: 			 my $file=$bighash{'src_'.$id};
 9693:                          if (&allowed('bre',$file)) {
 9694:          		    my ($mapid,$resid)=split(/\./,$id);
 9695:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
 9696: 				$realpossible++;
 9697:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
 9698: 						    $resid,$thisfn);
 9699:                             }
 9700: 			 }
 9701:                      }
 9702: 		     if ($realpossible!=1) { $syval=''; }
 9703:                  } else {
 9704:                      $syval='';
 9705:                  }
 9706: 	      }
 9707:               untie(%bighash)
 9708:            }
 9709:         }
 9710:         if ($syval) {
 9711: 	    return $env{$cache_str}=$syval;
 9712:         }
 9713:     }
 9714:     &appenv({'request.ambiguous' => $thisfn});
 9715:     return $env{$cache_str}='';
 9716: }
 9717: 
 9718: # ---------------------------------------------------------- Return random seed
 9719: 
 9720: sub numval {
 9721:     my $txt=shift;
 9722:     $txt=~tr/A-J/0-9/;
 9723:     $txt=~tr/a-j/0-9/;
 9724:     $txt=~tr/K-T/0-9/;
 9725:     $txt=~tr/k-t/0-9/;
 9726:     $txt=~tr/U-Z/0-5/;
 9727:     $txt=~tr/u-z/0-5/;
 9728:     $txt=~s/\D//g;
 9729:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
 9730:     return int($txt);
 9731: }
 9732: 
 9733: sub numval2 {
 9734:     my $txt=shift;
 9735:     $txt=~tr/A-J/0-9/;
 9736:     $txt=~tr/a-j/0-9/;
 9737:     $txt=~tr/K-T/0-9/;
 9738:     $txt=~tr/k-t/0-9/;
 9739:     $txt=~tr/U-Z/0-5/;
 9740:     $txt=~tr/u-z/0-5/;
 9741:     $txt=~s/\D//g;
 9742:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 9743:     my $total;
 9744:     foreach my $val (@txts) { $total+=$val; }
 9745:     if ($_64bit) { if ($total > 2**32) { return -1; } }
 9746:     return int($total);
 9747: }
 9748: 
 9749: sub numval3 {
 9750:     use integer;
 9751:     my $txt=shift;
 9752:     $txt=~tr/A-J/0-9/;
 9753:     $txt=~tr/a-j/0-9/;
 9754:     $txt=~tr/K-T/0-9/;
 9755:     $txt=~tr/k-t/0-9/;
 9756:     $txt=~tr/U-Z/0-5/;
 9757:     $txt=~tr/u-z/0-5/;
 9758:     $txt=~s/\D//g;
 9759:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 9760:     my $total;
 9761:     foreach my $val (@txts) { $total+=$val; }
 9762:     if ($_64bit) { $total=(($total<<32)>>32); }
 9763:     return $total;
 9764: }
 9765: 
 9766: sub digest {
 9767:     my ($data)=@_;
 9768:     my $digest=&Digest::MD5::md5($data);
 9769:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
 9770:     my ($e,$f);
 9771:     {
 9772:         use integer;
 9773:         $e=($a+$b);
 9774:         $f=($c+$d);
 9775:         if ($_64bit) {
 9776:             $e=(($e<<32)>>32);
 9777:             $f=(($f<<32)>>32);
 9778:         }
 9779:     }
 9780:     if (wantarray) {
 9781: 	return ($e,$f);
 9782:     } else {
 9783: 	my $g;
 9784: 	{
 9785: 	    use integer;
 9786: 	    $g=($e+$f);
 9787: 	    if ($_64bit) {
 9788: 		$g=(($g<<32)>>32);
 9789: 	    }
 9790: 	}
 9791: 	return $g;
 9792:     }
 9793: }
 9794: 
 9795: sub latest_rnd_algorithm_id {
 9796:     return '64bit5';
 9797: }
 9798: 
 9799: sub get_rand_alg {
 9800:     my ($courseid)=@_;
 9801:     if (!$courseid) { $courseid=(&whichuser())[1]; }
 9802:     if ($courseid) {
 9803: 	return $env{"course.$courseid.rndseed"};
 9804:     }
 9805:     return &latest_rnd_algorithm_id();
 9806: }
 9807: 
 9808: sub validCODE {
 9809:     my ($CODE)=@_;
 9810:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
 9811:     return 0;
 9812: }
 9813: 
 9814: sub getCODE {
 9815:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
 9816:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
 9817: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
 9818: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
 9819: 	return $Apache::lonhomework::history{'resource.CODE'};
 9820:     }
 9821:     return undef;
 9822: }
 9823: #
 9824: #  Determines the random seed for a specific context:
 9825: #
 9826: # parameters:
 9827: #   symb      - in course context the symb for the seed.
 9828: #   course_id - The course id of the form domain_coursenum.
 9829: #   domain    - Domain for the user.
 9830: #   course    - Course for the user.
 9831: #   cenv      - environment of the course.
 9832: #
 9833: # NOTE:
 9834: #   All parameters are picked out of the environment if missing
 9835: #   or not defined.
 9836: #   If a symb cannot be determined the current time is used instead.
 9837: #
 9838: #  For a given well defined symb, courside, domain, username,
 9839: #  and course environment, the seed is reproducible.
 9840: #
 9841: sub rndseed {
 9842:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
 9843:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
 9844:     if (!defined($symb)) {
 9845: 	unless ($symb=$wsymb) { return time; }
 9846:     }
 9847:     if (!defined $courseid) { 
 9848: 	$courseid=$wcourseid; 
 9849:     }
 9850:     if (!defined $domain) { $domain=$wdomain; }
 9851:     if (!defined $username) { $username=$wusername }
 9852: 
 9853:     my $which;
 9854:     if (defined($cenv->{'rndseed'})) {
 9855: 	$which = $cenv->{'rndseed'};
 9856:     } else {
 9857: 	$which =&get_rand_alg($courseid);
 9858:     }
 9859:     if (defined(&getCODE())) {
 9860: 
 9861: 	if ($which eq '64bit5') {
 9862: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
 9863: 	} elsif ($which eq '64bit4') {
 9864: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
 9865: 	} else {
 9866: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
 9867: 	}
 9868:     } elsif ($which eq '64bit5') {
 9869: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
 9870:     } elsif ($which eq '64bit4') {
 9871: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
 9872:     } elsif ($which eq '64bit3') {
 9873: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
 9874:     } elsif ($which eq '64bit2') {
 9875: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
 9876:     } elsif ($which eq '64bit') {
 9877: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
 9878:     }
 9879:     return &rndseed_32bit($symb,$courseid,$domain,$username);
 9880: }
 9881: 
 9882: sub rndseed_32bit {
 9883:     my ($symb,$courseid,$domain,$username)=@_;
 9884:     {
 9885: 	use integer;
 9886: 	my $symbchck=unpack("%32C*",$symb) << 27;
 9887: 	my $symbseed=numval($symb) << 22;
 9888: 	my $namechck=unpack("%32C*",$username) << 17;
 9889: 	my $nameseed=numval($username) << 12;
 9890: 	my $domainseed=unpack("%32C*",$domain) << 7;
 9891: 	my $courseseed=unpack("%32C*",$courseid);
 9892: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
 9893: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 9894: 	#&logthis("rndseed :$num:$symb");
 9895: 	if ($_64bit) { $num=(($num<<32)>>32); }
 9896: 	return $num;
 9897:     }
 9898: }
 9899: 
 9900: sub rndseed_64bit {
 9901:     my ($symb,$courseid,$domain,$username)=@_;
 9902:     {
 9903: 	use integer;
 9904: 	my $symbchck=unpack("%32S*",$symb) << 21;
 9905: 	my $symbseed=numval($symb) << 10;
 9906: 	my $namechck=unpack("%32S*",$username);
 9907: 	
 9908: 	my $nameseed=numval($username) << 21;
 9909: 	my $domainseed=unpack("%32S*",$domain) << 10;
 9910: 	my $courseseed=unpack("%32S*",$courseid);
 9911: 	
 9912: 	my $num1=$symbchck+$symbseed+$namechck;
 9913: 	my $num2=$nameseed+$domainseed+$courseseed;
 9914: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 9915: 	#&logthis("rndseed :$num:$symb");
 9916: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 9917: 	return "$num1,$num2";
 9918:     }
 9919: }
 9920: 
 9921: sub rndseed_64bit2 {
 9922:     my ($symb,$courseid,$domain,$username)=@_;
 9923:     {
 9924: 	use integer;
 9925: 	# strings need to be an even # of cahracters long, it it is odd the
 9926:         # last characters gets thrown away
 9927: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 9928: 	my $symbseed=numval($symb) << 10;
 9929: 	my $namechck=unpack("%32S*",$username.' ');
 9930: 	
 9931: 	my $nameseed=numval($username) << 21;
 9932: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 9933: 	my $courseseed=unpack("%32S*",$courseid.' ');
 9934: 	
 9935: 	my $num1=$symbchck+$symbseed+$namechck;
 9936: 	my $num2=$nameseed+$domainseed+$courseseed;
 9937: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 9938: 	#&logthis("rndseed :$num:$symb");
 9939: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 9940: 	return "$num1,$num2";
 9941:     }
 9942: }
 9943: 
 9944: sub rndseed_64bit3 {
 9945:     my ($symb,$courseid,$domain,$username)=@_;
 9946:     {
 9947: 	use integer;
 9948: 	# strings need to be an even # of cahracters long, it it is odd the
 9949:         # last characters gets thrown away
 9950: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 9951: 	my $symbseed=numval2($symb) << 10;
 9952: 	my $namechck=unpack("%32S*",$username.' ');
 9953: 	
 9954: 	my $nameseed=numval2($username) << 21;
 9955: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 9956: 	my $courseseed=unpack("%32S*",$courseid.' ');
 9957: 	
 9958: 	my $num1=$symbchck+$symbseed+$namechck;
 9959: 	my $num2=$nameseed+$domainseed+$courseseed;
 9960: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 9961: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 9962: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 9963: 	
 9964: 	return "$num1:$num2";
 9965:     }
 9966: }
 9967: 
 9968: sub rndseed_64bit4 {
 9969:     my ($symb,$courseid,$domain,$username)=@_;
 9970:     {
 9971: 	use integer;
 9972: 	# strings need to be an even # of cahracters long, it it is odd the
 9973:         # last characters gets thrown away
 9974: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 9975: 	my $symbseed=numval3($symb) << 10;
 9976: 	my $namechck=unpack("%32S*",$username.' ');
 9977: 	
 9978: 	my $nameseed=numval3($username) << 21;
 9979: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 9980: 	my $courseseed=unpack("%32S*",$courseid.' ');
 9981: 	
 9982: 	my $num1=$symbchck+$symbseed+$namechck;
 9983: 	my $num2=$nameseed+$domainseed+$courseseed;
 9984: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 9985: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 9986: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 9987: 	
 9988: 	return "$num1:$num2";
 9989:     }
 9990: }
 9991: 
 9992: sub rndseed_64bit5 {
 9993:     my ($symb,$courseid,$domain,$username)=@_;
 9994:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
 9995:     return "$num1:$num2";
 9996: }
 9997: 
 9998: sub rndseed_CODE_64bit {
 9999:     my ($symb,$courseid,$domain,$username)=@_;
10000:     {
10001: 	use integer;
10002: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
10003: 	my $symbseed=numval2($symb);
10004: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
10005: 	my $CODEseed=numval(&getCODE());
10006: 	my $courseseed=unpack("%32S*",$courseid.' ');
10007: 	my $num1=$symbseed+$CODEchck;
10008: 	my $num2=$CODEseed+$courseseed+$symbchck;
10009: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
10010: 	#&logthis("rndseed :$num1:$num2:$symb");
10011: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
10012: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
10013: 	return "$num1:$num2";
10014:     }
10015: }
10016: 
10017: sub rndseed_CODE_64bit4 {
10018:     my ($symb,$courseid,$domain,$username)=@_;
10019:     {
10020: 	use integer;
10021: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
10022: 	my $symbseed=numval3($symb);
10023: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
10024: 	my $CODEseed=numval3(&getCODE());
10025: 	my $courseseed=unpack("%32S*",$courseid.' ');
10026: 	my $num1=$symbseed+$CODEchck;
10027: 	my $num2=$CODEseed+$courseseed+$symbchck;
10028: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
10029: 	#&logthis("rndseed :$num1:$num2:$symb");
10030: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
10031: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
10032: 	return "$num1:$num2";
10033:     }
10034: }
10035: 
10036: sub rndseed_CODE_64bit5 {
10037:     my ($symb,$courseid,$domain,$username)=@_;
10038:     my $code = &getCODE();
10039:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
10040:     return "$num1:$num2";
10041: }
10042: 
10043: sub setup_random_from_rndseed {
10044:     my ($rndseed)=@_;
10045:     if ($rndseed =~/([,:])/) {
10046: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
10047: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
10048:     } else {
10049: 	&Math::Random::random_set_seed_from_phrase($rndseed);
10050:     }
10051: }
10052: 
10053: sub latest_receipt_algorithm_id {
10054:     return 'receipt3';
10055: }
10056: 
10057: sub recunique {
10058:     my $fucourseid=shift;
10059:     my $unique;
10060:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
10061: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
10062: 	$unique=$env{"course.$fucourseid.internal.encseed"};
10063:     } else {
10064: 	$unique=$perlvar{'lonReceipt'};
10065:     }
10066:     return unpack("%32C*",$unique);
10067: }
10068: 
10069: sub recprefix {
10070:     my $fucourseid=shift;
10071:     my $prefix;
10072:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
10073: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
10074: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
10075:     } else {
10076: 	$prefix=$perlvar{'lonHostID'};
10077:     }
10078:     return unpack("%32C*",$prefix);
10079: }
10080: 
10081: sub ireceipt {
10082:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
10083: 
10084:     my $return =&recprefix($fucourseid).'-';
10085: 
10086:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
10087: 	$env{'request.state'} eq 'construct') {
10088: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
10089: 	return $return;
10090:     }
10091: 
10092:     my $cuname=unpack("%32C*",$funame);
10093:     my $cudom=unpack("%32C*",$fudom);
10094:     my $cucourseid=unpack("%32C*",$fucourseid);
10095:     my $cusymb=unpack("%32C*",$fusymb);
10096:     my $cunique=&recunique($fucourseid);
10097:     my $cpart=unpack("%32S*",$part);
10098:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
10099: 
10100: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
10101: 			       
10102: 	$return.= ($cunique%$cuname+
10103: 		   $cunique%$cudom+
10104: 		   $cusymb%$cuname+
10105: 		   $cusymb%$cudom+
10106: 		   $cucourseid%$cuname+
10107: 		   $cucourseid%$cudom+
10108: 		   $cpart%$cuname+
10109: 		   $cpart%$cudom);
10110:     } else {
10111: 	$return.= ($cunique%$cuname+
10112: 		   $cunique%$cudom+
10113: 		   $cusymb%$cuname+
10114: 		   $cusymb%$cudom+
10115: 		   $cucourseid%$cuname+
10116: 		   $cucourseid%$cudom);
10117:     }
10118:     return $return;
10119: }
10120: 
10121: sub receipt {
10122:     my ($part)=@_;
10123:     my ($symb,$courseid,$domain,$name) = &whichuser();
10124:     return &ireceipt($name,$domain,$courseid,$symb,$part);
10125: }
10126: 
10127: sub whichuser {
10128:     my ($passedsymb)=@_;
10129:     my ($symb,$courseid,$domain,$name,$publicuser);
10130:     if (defined($env{'form.grade_symb'})) {
10131: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
10132: 	my $allowed=&allowed('vgr',$tmp_courseid);
10133: 	if (!$allowed &&
10134: 	    exists($env{'request.course.sec'}) &&
10135: 	    $env{'request.course.sec'} !~ /^\s*$/) {
10136: 	    $allowed=&allowed('vgr',$tmp_courseid.
10137: 			      '/'.$env{'request.course.sec'});
10138: 	}
10139: 	if ($allowed) {
10140: 	    ($symb)=&get_env_multiple('form.grade_symb');
10141: 	    $courseid=$tmp_courseid;
10142: 	    ($domain)=&get_env_multiple('form.grade_domain');
10143: 	    ($name)=&get_env_multiple('form.grade_username');
10144: 	    return ($symb,$courseid,$domain,$name,$publicuser);
10145: 	}
10146:     }
10147:     if (!$passedsymb) {
10148: 	$symb=&symbread();
10149:     } else {
10150: 	$symb=$passedsymb;
10151:     }
10152:     $courseid=$env{'request.course.id'};
10153:     $domain=$env{'user.domain'};
10154:     $name=$env{'user.name'};
10155:     if ($name eq 'public' && $domain eq 'public') {
10156: 	if (!defined($env{'form.username'})) {
10157: 	    $env{'form.username'}.=time.rand(10000000);
10158: 	}
10159: 	$name.=$env{'form.username'};
10160:     }
10161:     return ($symb,$courseid,$domain,$name,$publicuser);
10162: 
10163: }
10164: 
10165: # ------------------------------------------------------------ Serves up a file
10166: # returns either the contents of the file or 
10167: # -1 if the file doesn't exist
10168: #
10169: # if the target is a file that was uploaded via DOCS, 
10170: # a check will be made to see if a current copy exists on the local server,
10171: # if it does this will be served, otherwise a copy will be retrieved from
10172: # the home server for the course and stored in /home/httpd/html/userfiles on
10173: # the local server.   
10174: 
10175: sub getfile {
10176:     my ($file) = @_;
10177:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
10178:     &repcopy($file);
10179:     return &readfile($file);
10180: }
10181: 
10182: sub repcopy_userfile {
10183:     my ($file)=@_;
10184:     my $londocroot = $perlvar{'lonDocRoot'};
10185:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
10186:     if ($file =~ m{^\Q$londocroot/lonUsers/\E}) { return 'ok'; }
10187:     my ($cdom,$cnum,$filename) = 
10188: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
10189:     my $uri="/uploaded/$cdom/$cnum/$filename";
10190:     if (-e "$file") {
10191: # we already have a local copy, check it out
10192: 	my @fileinfo = stat($file);
10193: 	my $rtncode;
10194: 	my $info;
10195: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
10196: 	if ($lwpresp ne 'ok') {
10197: # there is no such file anymore, even though we had a local copy
10198: 	    if ($rtncode eq '404') {
10199: 		unlink($file);
10200: 	    }
10201: 	    return -1;
10202: 	}
10203: 	if ($info < $fileinfo[9]) {
10204: # nice, the file we have is up-to-date, just say okay
10205: 	    return 'ok';
10206: 	} else {
10207: # the file is outdated, get rid of it
10208: 	    unlink($file);
10209: 	}
10210:     }
10211: # one way or the other, at this point, we don't have the file
10212: # construct the correct path for the file
10213:     my @parts = ($cdom,$cnum); 
10214:     if ($filename =~ m|^(.+)/[^/]+$|) {
10215: 	push @parts, split(/\//,$1);
10216:     }
10217:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
10218:     foreach my $part (@parts) {
10219: 	$path .= '/'.$part;
10220: 	if (!-e $path) {
10221: 	    mkdir($path,0770);
10222: 	}
10223:     }
10224: # now the path exists for sure
10225: # get a user agent
10226:     my $ua=new LWP::UserAgent;
10227:     my $transferfile=$file.'.in.transfer';
10228: # FIXME: this should flock
10229:     if (-e $transferfile) { return 'ok'; }
10230:     my $request;
10231:     $uri=~s/^\///;
10232:     my $homeserver = &homeserver($cnum,$cdom);
10233:     my $protocol = $protocol{$homeserver};
10234:     $protocol = 'http' if ($protocol ne 'https');
10235:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
10236:     my $response=$ua->request($request,$transferfile);
10237: # did it work?
10238:     if ($response->is_error()) {
10239: 	unlink($transferfile);
10240: 	&logthis("Userfile repcopy failed for $uri");
10241: 	return -1;
10242:     }
10243: # worked, rename the transfer file
10244:     rename($transferfile,$file);
10245:     return 'ok';
10246: }
10247: 
10248: sub tokenwrapper {
10249:     my $uri=shift;
10250:     $uri=~s|^https?\://([^/]+)||;
10251:     $uri=~s|^/||;
10252:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
10253:     my $token=$1;
10254:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
10255:     if ($udom && $uname && $file) {
10256: 	$file=~s|(\?\.*)*$||;
10257:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
10258:         my $homeserver = &homeserver($uname,$udom);
10259:         my $protocol = $protocol{$homeserver};
10260:         $protocol = 'http' if ($protocol ne 'https');
10261:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
10262:                (($uri=~/\?/)?'&':'?').'token='.$token.
10263:                                '&tokenissued='.$perlvar{'lonHostID'};
10264:     } else {
10265:         return '/adm/notfound.html';
10266:     }
10267: }
10268: 
10269: # call with reqtype HEAD: get last modification time
10270: # call with reqtype GET: get the file contents
10271: # Do not call this with reqtype GET for large files! It loads everything into memory
10272: #
10273: sub getuploaded {
10274:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
10275:     $uri=~s/^\///;
10276:     my $homeserver = &homeserver($cnum,$cdom);
10277:     my $protocol = $protocol{$homeserver};
10278:     $protocol = 'http' if ($protocol ne 'https');
10279:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
10280:     my $ua=new LWP::UserAgent;
10281:     my $request=new HTTP::Request($reqtype,$uri);
10282:     my $response=$ua->request($request);
10283:     $$rtncode = $response->code;
10284:     if (! $response->is_success()) {
10285: 	return 'failed';
10286:     }      
10287:     if ($reqtype eq 'HEAD') {
10288: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
10289:     } elsif ($reqtype eq 'GET') {
10290: 	$$info = $response->content;
10291:     }
10292:     return 'ok';
10293: }
10294: 
10295: sub readfile {
10296:     my $file = shift;
10297:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
10298:     my $fh;
10299:     open($fh,"<$file");
10300:     my $a='';
10301:     while (my $line = <$fh>) { $a .= $line; }
10302:     return $a;
10303: }
10304: 
10305: sub filelocation {
10306:     my ($dir,$file) = @_;
10307:     my $location;
10308:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
10309: 
10310:     if ($file =~ m-^/adm/-) {
10311: 	$file=~s-^/adm/wrapper/-/-;
10312: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
10313:     }
10314: 
10315:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
10316:         $location = $file;
10317:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
10318:         my ($udom,$uname,$filename)=
10319:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
10320:         my $home=&homeserver($uname,$udom);
10321:         my $is_me=0;
10322:         my @ids=&current_machine_ids();
10323:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
10324:         if ($is_me) {
10325:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
10326:         } else {
10327:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
10328:   	      $udom.'/'.$uname.'/'.$filename;
10329:         }
10330:     } elsif ($file =~ m-^/adm/-) {
10331: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
10332:     } else {
10333:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
10334:         $file=~s:^/(res|priv)/:/:;
10335:         my $space=$1;
10336:         if ( !( $file =~ m:^/:) ) {
10337:             $location = $dir. '/'.$file;
10338:         } else {
10339:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
10340:         }
10341:     }
10342:     $location=~s://+:/:g; # remove duplicate /
10343:     while ($location=~m{/\.\./}) {
10344: 	if ($location =~ m{/[^/]+/\.\./}) {
10345: 	    $location=~ s{/[^/]+/\.\./}{/}g;
10346: 	} else {
10347: 	    $location=~ s{/\.\./}{/}g;
10348: 	}
10349:     } #remove dir/..
10350:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
10351:     return $location;
10352: }
10353: 
10354: sub hreflocation {
10355:     my ($dir,$file)=@_;
10356:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
10357: 	$file=filelocation($dir,$file);
10358:     } elsif ($file=~m-^/adm/-) {
10359: 	$file=~s-^/adm/wrapper/-/-;
10360: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
10361:     }
10362:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
10363: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
10364:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
10365: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
10366: 	        {/uploaded/$1/$2/}x;
10367:     }
10368:     if ($file=~ m{^/userfiles/}) {
10369: 	$file =~ s{^/userfiles/}{/uploaded/};
10370:     }
10371:     return $file;
10372: }
10373: 
10374: 
10375: 
10376: 
10377: 
10378: sub current_machine_domains {
10379:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
10380: }
10381: 
10382: sub machine_domains {
10383:     my ($hostname) = @_;
10384:     my @domains;
10385:     my %hostname = &all_hostnames();
10386:     while( my($id, $name) = each(%hostname)) {
10387: #	&logthis("-$id-$name-$hostname-");
10388: 	if ($hostname eq $name) {
10389: 	    push(@domains,&host_domain($id));
10390: 	}
10391:     }
10392:     return @domains;
10393: }
10394: 
10395: sub current_machine_ids {
10396:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
10397: }
10398: 
10399: sub machine_ids {
10400:     my ($hostname) = @_;
10401:     $hostname ||= &hostname($perlvar{'lonHostID'});
10402:     my @ids;
10403:     my %name_to_host = &all_names();
10404:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
10405: 	return @{ $name_to_host{$hostname} };
10406:     }
10407:     return;
10408: }
10409: 
10410: sub additional_machine_domains {
10411:     my @domains;
10412:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
10413:     while( my $line = <$fh>) {
10414:         $line =~ s/\s//g;
10415:         push(@domains,$line);
10416:     }
10417:     return @domains;
10418: }
10419: 
10420: sub default_login_domain {
10421:     my $domain = $perlvar{'lonDefDomain'};
10422:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
10423:     foreach my $posdom (&current_machine_domains(),
10424:                         &additional_machine_domains()) {
10425:         if (lc($posdom) eq lc($testdomain)) {
10426:             $domain=$posdom;
10427:             last;
10428:         }
10429:     }
10430:     return $domain;
10431: }
10432: 
10433: # ------------------------------------------------------------- Declutters URLs
10434: 
10435: sub declutter {
10436:     my $thisfn=shift;
10437:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
10438:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
10439:     $thisfn=~s/^\///;
10440:     $thisfn=~s|^adm/wrapper/||;
10441:     $thisfn=~s|^adm/coursedocs/showdoc/||;
10442:     $thisfn=~s/^res\///;
10443:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
10444:         $thisfn=~s/\?.+$//;
10445:     }
10446:     return $thisfn;
10447: }
10448: 
10449: # ------------------------------------------------------------- Clutter up URLs
10450: 
10451: sub clutter {
10452:     my $thisfn='/'.&declutter(shift);
10453:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
10454: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
10455:        $thisfn='/res'.$thisfn; 
10456:     }
10457:     if ($thisfn !~m|^/adm|) {
10458: 	if ($thisfn =~ m|^/ext/|) {
10459: 	    $thisfn='/adm/wrapper'.$thisfn;
10460: 	} else {
10461: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
10462: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
10463: 	    if ($embstyle eq 'ssi'
10464: 		|| ($embstyle eq 'hdn')
10465: 		|| ($embstyle eq 'rat')
10466: 		|| ($embstyle eq 'prv')
10467: 		|| ($embstyle eq 'ign')) {
10468: 		#do nothing with these
10469: 	    } elsif (($embstyle eq 'img') 
10470: 		|| ($embstyle eq 'emb')
10471: 		|| ($embstyle eq 'wrp')) {
10472: 		$thisfn='/adm/wrapper'.$thisfn;
10473: 	    } elsif ($embstyle eq 'unk'
10474: 		     && $thisfn!~/\.(sequence|page)$/) {
10475: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
10476: 	    } else {
10477: #		&logthis("Got a blank emb style");
10478: 	    }
10479: 	}
10480:     }
10481:     return $thisfn;
10482: }
10483: 
10484: sub clutter_with_no_wrapper {
10485:     my $uri = &clutter(shift);
10486:     if ($uri =~ m-^/adm/-) {
10487: 	$uri =~ s-^/adm/wrapper/-/-;
10488: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
10489:     }
10490:     return $uri;
10491: }
10492: 
10493: sub freeze_escape {
10494:     my ($value)=@_;
10495:     if (ref($value)) {
10496: 	$value=&nfreeze($value);
10497: 	return '__FROZEN__'.&escape($value);
10498:     }
10499:     return &escape($value);
10500: }
10501: 
10502: 
10503: sub thaw_unescape {
10504:     my ($value)=@_;
10505:     if ($value =~ /^__FROZEN__/) {
10506: 	substr($value,0,10,undef);
10507: 	$value=&unescape($value);
10508: 	return &thaw($value);
10509:     }
10510:     return &unescape($value);
10511: }
10512: 
10513: sub correct_line_ends {
10514:     my ($result)=@_;
10515:     $$result =~s/\r\n/\n/mg;
10516:     $$result =~s/\r/\n/mg;
10517: }
10518: # ================================================================ Main Program
10519: 
10520: sub goodbye {
10521:    &logthis("Starting Shut down");
10522: #not converted to using infrastruture and probably shouldn't be
10523:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
10524: #converted
10525: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
10526:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
10527: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
10528: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
10529: #1.1 only
10530: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
10531: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
10532: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
10533: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
10534:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
10535:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
10536:    &logthis(sprintf("%-20s is %s",'hits',$hits));
10537:    &flushcourselogs();
10538:    &logthis("Shutting down");
10539: }
10540: 
10541: sub get_dns {
10542:     my ($url,$func,$ignore_cache) = @_;
10543:     if (!$ignore_cache) {
10544: 	my ($content,$cached)=
10545: 	    &Apache::lonnet::is_cached_new('dns',$url);
10546: 	if ($cached) {
10547: 	    &$func($content);
10548: 	    return;
10549: 	}
10550:     }
10551: 
10552:     my %alldns;
10553:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
10554:     foreach my $dns (<$config>) {
10555: 	next if ($dns !~ /^\^(\S*)/x);
10556:         my $line = $1;
10557:         my ($host,$protocol) = split(/:/,$line);
10558:         if ($protocol ne 'https') {
10559:             $protocol = 'http';
10560:         }
10561: 	$alldns{$host} = $protocol;
10562:     }
10563:     while (%alldns) {
10564: 	my ($dns) = keys(%alldns);
10565: 	my $ua=new LWP::UserAgent;
10566:         $ua->timeout(30);
10567: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
10568: 	my $response=$ua->request($request);
10569:         delete($alldns{$dns});
10570: 	next if ($response->is_error());
10571: 	my @content = split("\n",$response->content);
10572: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
10573: 	&$func(\@content);
10574: 	return;
10575:     }
10576:     close($config);
10577:     my $which = (split('/',$url))[3];
10578:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
10579:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
10580:     my @content = <$config>;
10581:     &$func(\@content);
10582:     return;
10583: }
10584: # ------------------------------------------------------------ Read domain file
10585: {
10586:     my $loaded;
10587:     my %domain;
10588: 
10589:     sub parse_domain_tab {
10590: 	my ($lines) = @_;
10591: 	foreach my $line (@$lines) {
10592: 	    next if ($line =~ /^(\#|\s*$ )/x);
10593: 
10594: 	    chomp($line);
10595: 	    my ($name,@elements) = split(/:/,$line,9);
10596: 	    my %this_domain;
10597: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
10598: 			       'lang_def', 'city', 'longi', 'lati',
10599: 			       'primary') {
10600: 		$this_domain{$field} = shift(@elements);
10601: 	    }
10602: 	    $domain{$name} = \%this_domain;
10603: 	}
10604:     }
10605: 
10606:     sub reset_domain_info {
10607: 	undef($loaded);
10608: 	undef(%domain);
10609:     }
10610: 
10611:     sub load_domain_tab {
10612: 	my ($ignore_cache) = @_;
10613: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
10614: 	my $fh;
10615: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
10616: 	    my @lines = <$fh>;
10617: 	    &parse_domain_tab(\@lines);
10618: 	}
10619: 	close($fh);
10620: 	$loaded = 1;
10621:     }
10622: 
10623:     sub domain {
10624: 	&load_domain_tab() if (!$loaded);
10625: 
10626: 	my ($name,$what) = @_;
10627: 	return if ( !exists($domain{$name}) );
10628: 
10629: 	if (!$what) {
10630: 	    return $domain{$name}{'description'};
10631: 	}
10632: 	return $domain{$name}{$what};
10633:     }
10634: 
10635:     sub domain_info {
10636:         &load_domain_tab() if (!$loaded);
10637:         return %domain;
10638:     }
10639: 
10640: }
10641: 
10642: 
10643: # ------------------------------------------------------------- Read hosts file
10644: {
10645:     my %hostname;
10646:     my %hostdom;
10647:     my %libserv;
10648:     my $loaded;
10649:     my %name_to_host;
10650:     my %internetdom;
10651:     my %LC_dns_serv;
10652: 
10653:     sub parse_hosts_tab {
10654: 	my ($file) = @_;
10655: 	foreach my $configline (@$file) {
10656: 	    next if ($configline =~ /^(\#|\s*$ )/x);
10657:             chomp($configline);
10658: 	    if ($configline =~ /^\^/) {
10659:                 if ($configline =~ /^\^([\w.\-]+)/) {
10660:                     $LC_dns_serv{$1} = 1;
10661:                 }
10662:                 next;
10663:             }
10664: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
10665: 	    $name=~s/\s//g;
10666: 	    if ($id && $domain && $role && $name) {
10667: 		$hostname{$id}=$name;
10668: 		push(@{$name_to_host{$name}}, $id);
10669: 		$hostdom{$id}=$domain;
10670: 		if ($role eq 'library') { $libserv{$id}=$name; }
10671:                 if (defined($protocol)) {
10672:                     if ($protocol eq 'https') {
10673:                         $protocol{$id} = $protocol;
10674:                     } else {
10675:                         $protocol{$id} = 'http'; 
10676:                     }
10677:                 } else {
10678:                     $protocol{$id} = 'http';
10679:                 }
10680:                 if (defined($intdom)) {
10681:                     $internetdom{$id} = $intdom;
10682:                 }
10683: 	    }
10684: 	}
10685:     }
10686:     
10687:     sub reset_hosts_info {
10688: 	&purge_remembered();
10689: 	&reset_domain_info();
10690: 	&reset_hosts_ip_info();
10691: 	undef(%name_to_host);
10692: 	undef(%hostname);
10693: 	undef(%hostdom);
10694: 	undef(%libserv);
10695: 	undef($loaded);
10696:     }
10697: 
10698:     sub load_hosts_tab {
10699: 	my ($ignore_cache) = @_;
10700: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
10701: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
10702: 	my @config = <$config>;
10703: 	&parse_hosts_tab(\@config);
10704: 	close($config);
10705: 	$loaded=1;
10706:     }
10707: 
10708:     sub hostname {
10709: 	&load_hosts_tab() if (!$loaded);
10710: 
10711: 	my ($lonid) = @_;
10712: 	return $hostname{$lonid};
10713:     }
10714: 
10715:     sub all_hostnames {
10716: 	&load_hosts_tab() if (!$loaded);
10717: 
10718: 	return %hostname;
10719:     }
10720: 
10721:     sub all_names {
10722: 	&load_hosts_tab() if (!$loaded);
10723: 
10724: 	return %name_to_host;
10725:     }
10726: 
10727:     sub all_host_domain {
10728:         &load_hosts_tab() if (!$loaded);
10729:         return %hostdom;
10730:     }
10731: 
10732:     sub is_library {
10733: 	&load_hosts_tab() if (!$loaded);
10734: 
10735: 	return exists($libserv{$_[0]});
10736:     }
10737: 
10738:     sub all_library {
10739: 	&load_hosts_tab() if (!$loaded);
10740: 
10741: 	return %libserv;
10742:     }
10743: 
10744:     sub unique_library {
10745: 	#2x reverse removes all hostnames that appear more than once
10746:         my %unique = reverse &all_library();
10747:         return reverse %unique;
10748:     }
10749: 
10750:     sub get_servers {
10751: 	&load_hosts_tab() if (!$loaded);
10752: 
10753: 	my ($domain,$type) = @_;
10754: 	my %possible_hosts = ($type eq 'library') ? %libserv
10755: 	                                          : %hostname;
10756: 	my %result;
10757: 	if (ref($domain) eq 'ARRAY') {
10758: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
10759: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
10760: 		    $result{$host} = $hostname;
10761: 		}
10762: 	    }
10763: 	} else {
10764: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
10765: 		if ($hostdom{$host} eq $domain) {
10766: 		    $result{$host} = $hostname;
10767: 		}
10768: 	    }
10769: 	}
10770: 	return %result;
10771:     }
10772: 
10773:     sub get_unique_servers {
10774:         my %unique = reverse &get_servers(@_);
10775: 	return reverse %unique;
10776:     }
10777: 
10778:     sub host_domain {
10779: 	&load_hosts_tab() if (!$loaded);
10780: 
10781: 	my ($lonid) = @_;
10782: 	return $hostdom{$lonid};
10783:     }
10784: 
10785:     sub all_domains {
10786: 	&load_hosts_tab() if (!$loaded);
10787: 
10788: 	my %seen;
10789: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
10790: 	return @uniq;
10791:     }
10792: 
10793:     sub internet_dom {
10794:         &load_hosts_tab() if (!$loaded);
10795: 
10796:         my ($lonid) = @_;
10797:         return $internetdom{$lonid};
10798:     }
10799: 
10800:     sub is_LC_dns {
10801:         &load_hosts_tab() if (!$loaded);
10802: 
10803:         my ($hostname) = @_;
10804:         return exists($LC_dns_serv{$hostname});
10805:     }
10806: 
10807: }
10808: 
10809: { 
10810:     my %iphost;
10811:     my %name_to_ip;
10812:     my %lonid_to_ip;
10813: 
10814:     sub get_hosts_from_ip {
10815: 	my ($ip) = @_;
10816: 	my %iphosts = &get_iphost();
10817: 	if (ref($iphosts{$ip})) {
10818: 	    return @{$iphosts{$ip}};
10819: 	}
10820: 	return;
10821:     }
10822:     
10823:     sub reset_hosts_ip_info {
10824: 	undef(%iphost);
10825: 	undef(%name_to_ip);
10826: 	undef(%lonid_to_ip);
10827:     }
10828: 
10829:     sub get_host_ip {
10830: 	my ($lonid) = @_;
10831: 	if (exists($lonid_to_ip{$lonid})) {
10832: 	    return $lonid_to_ip{$lonid};
10833: 	}
10834: 	my $name=&hostname($lonid);
10835:    	my $ip = gethostbyname($name);
10836: 	return if (!$ip || length($ip) ne 4);
10837: 	$ip=inet_ntoa($ip);
10838: 	$name_to_ip{$name}   = $ip;
10839: 	$lonid_to_ip{$lonid} = $ip;
10840: 	return $ip;
10841:     }
10842:     
10843:     sub get_iphost {
10844: 	my ($ignore_cache) = @_;
10845: 
10846: 	if (!$ignore_cache) {
10847: 	    if (%iphost) {
10848: 		return %iphost;
10849: 	    }
10850: 	    my ($ip_info,$cached)=
10851: 		&Apache::lonnet::is_cached_new('iphost','iphost');
10852: 	    if ($cached) {
10853: 		%iphost      = %{$ip_info->[0]};
10854: 		%name_to_ip  = %{$ip_info->[1]};
10855: 		%lonid_to_ip = %{$ip_info->[2]};
10856: 		return %iphost;
10857: 	    }
10858: 	}
10859: 
10860: 	# get yesterday's info for fallback
10861: 	my %old_name_to_ip;
10862: 	my ($ip_info,$cached)=
10863: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
10864: 	if ($cached) {
10865: 	    %old_name_to_ip = %{$ip_info->[1]};
10866: 	}
10867: 
10868: 	my %name_to_host = &all_names();
10869: 	foreach my $name (keys(%name_to_host)) {
10870: 	    my $ip;
10871: 	    if (!exists($name_to_ip{$name})) {
10872: 		$ip = gethostbyname($name);
10873: 		if (!$ip || length($ip) ne 4) {
10874: 		    if (defined($old_name_to_ip{$name})) {
10875: 			$ip = $old_name_to_ip{$name};
10876: 			&logthis("Can't find $name defaulting to old $ip");
10877: 		    } else {
10878: 			&logthis("Name $name no IP found");
10879: 			next;
10880: 		    }
10881: 		} else {
10882: 		    $ip=inet_ntoa($ip);
10883: 		}
10884: 		$name_to_ip{$name} = $ip;
10885: 	    } else {
10886: 		$ip = $name_to_ip{$name};
10887: 	    }
10888: 	    foreach my $id (@{ $name_to_host{$name} }) {
10889: 		$lonid_to_ip{$id} = $ip;
10890: 	    }
10891: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
10892: 	}
10893: 	&Apache::lonnet::do_cache_new('iphost','iphost',
10894: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
10895: 				      48*60*60);
10896: 
10897: 	return %iphost;
10898:     }
10899: 
10900:     #
10901:     #  Given a DNS returns the loncapa host name for that DNS 
10902:     # 
10903:     sub host_from_dns {
10904:         my ($dns) = @_;
10905:         my @hosts;
10906:         my $ip;
10907: 
10908:         if (exists($name_to_ip{$dns})) {
10909:             $ip = $name_to_ip{$dns};
10910:         }
10911:         if (!$ip) {
10912:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
10913:             if (length($ip) == 4) { 
10914: 	        $ip   = &IO::Socket::inet_ntoa($ip);
10915:             }
10916:         }
10917:         if ($ip) {
10918: 	    @hosts = get_hosts_from_ip($ip);
10919: 	    return $hosts[0];
10920:         }
10921:         return undef;
10922:     }
10923: 
10924:     sub get_internet_names {
10925:         my ($lonid) = @_;
10926:         return if ($lonid eq '');
10927:         my ($idnref,$cached)=
10928:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
10929:         if ($cached) {
10930:             return $idnref;
10931:         }
10932:         my $ip = &get_host_ip($lonid);
10933:         my @hosts = &get_hosts_from_ip($ip);
10934:         my %iphost = &get_iphost();
10935:         my (@idns,%seen);
10936:         foreach my $id (@hosts) {
10937:             my $dom = &host_domain($id);
10938:             my $prim_id = &domain($dom,'primary');
10939:             my $prim_ip = &get_host_ip($prim_id);
10940:             next if ($seen{$prim_ip});
10941:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
10942:                 foreach my $id (@{$iphost{$prim_ip}}) {
10943:                     my $intdom = &internet_dom($id);
10944:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
10945:                         push(@idns,$intdom);
10946:                     }
10947:                 }
10948:             }
10949:             $seen{$prim_ip} = 1;
10950:         }
10951:         return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
10952:     }
10953: 
10954: }
10955: 
10956: sub all_loncaparevs {
10957:     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);
10958: }
10959: 
10960: BEGIN {
10961: 
10962: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
10963:     unless ($readit) {
10964: {
10965:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
10966:     %perlvar = (%perlvar,%{$configvars});
10967: }
10968: 
10969: 
10970: # ------------------------------------------------------ Read spare server file
10971: {
10972:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
10973: 
10974:     while (my $configline=<$config>) {
10975:        chomp($configline);
10976:        if ($configline) {
10977: 	   my ($host,$type) = split(':',$configline,2);
10978: 	   if (!defined($type) || $type eq '') { $type = 'default' };
10979: 	   push(@{ $spareid{$type} }, $host);
10980:        }
10981:     }
10982:     close($config);
10983: }
10984: # ------------------------------------------------------------ Read permissions
10985: {
10986:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
10987: 
10988:     while (my $configline=<$config>) {
10989: 	chomp($configline);
10990: 	if ($configline) {
10991: 	    my ($role,$perm)=split(/ /,$configline);
10992: 	    if ($perm ne '') { $pr{$role}=$perm; }
10993: 	}
10994:     }
10995:     close($config);
10996: }
10997: 
10998: # -------------------------------------------- Read plain texts for permissions
10999: {
11000:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
11001: 
11002:     while (my $configline=<$config>) {
11003: 	chomp($configline);
11004: 	if ($configline) {
11005: 	    my ($short,@plain)=split(/:/,$configline);
11006:             %{$prp{$short}} = ();
11007: 	    if (@plain > 0) {
11008:                 $prp{$short}{'std'} = $plain[0];
11009:                 for (my $i=1; $i<@plain; $i++) {
11010:                     $prp{$short}{'alt'.$i} = $plain[$i];  
11011:                 }
11012:             }
11013: 	}
11014:     }
11015:     close($config);
11016: }
11017: 
11018: # ---------------------------------------------------------- Read package table
11019: {
11020:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
11021: 
11022:     while (my $configline=<$config>) {
11023: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
11024: 	chomp($configline);
11025: 	my ($short,$plain)=split(/:/,$configline);
11026: 	my ($pack,$name)=split(/\&/,$short);
11027: 	if ($plain ne '') {
11028: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
11029: 	    $packagetab{$short}=$plain; 
11030: 	}
11031:     }
11032:     close($config);
11033: }
11034: 
11035: # ---------------------------------------------------------- Read loncaparev table
11036: {
11037:     if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
11038:         if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
11039:             while (my $configline=<$config>) {
11040:                 chomp($configline);
11041:                 my ($hostid,$loncaparev)=split(/:/,$configline);
11042:                 $loncaparevs{$hostid}=$loncaparev;
11043:             }
11044:             close($config);
11045:         }
11046:     }
11047: }
11048: 
11049: # ---------------------------------------------------------- Read serverhostID table
11050: {
11051:     if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
11052:         if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
11053:             while (my $configline=<$config>) {
11054:                 chomp($configline);
11055:                 my ($name,$id)=split(/:/,$configline);
11056:                 $serverhomeIDs{$name}=$id;
11057:             }
11058:             close($config);
11059:         }
11060:     }
11061: }
11062: 
11063: {
11064:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
11065:     if (-e $file) {
11066:         my $parser = HTML::LCParser->new($file);
11067:         while (my $token = $parser->get_token()) {
11068:             if ($token->[0] eq 'S') {
11069:                 my $item = $token->[1];
11070:                 my $name = $token->[2]{'name'};
11071:                 my $value = $token->[2]{'value'};
11072:                 if ($item ne '' && $name ne '' && $value ne '') {
11073:                     my $release = $parser->get_text();
11074:                     $release =~ s/(^\s*|\s*$ )//gx;
11075:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
11076:                 }
11077:             }
11078:         }
11079:     }
11080: }
11081: 
11082: # ---------------------------------------------------------- Read managers table
11083: {
11084:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
11085:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
11086:             while (my $configline=<$config>) {
11087:                 chomp($configline);
11088:                 next if ($configline =~ /^\#/);
11089:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
11090:                     $managerstab{$configline} = 1;
11091:                 }
11092:             }
11093:             close($config);
11094:         }
11095:     }
11096: }
11097: 
11098: # ------------- set up temporary directory
11099: {
11100:     $tmpdir = LONCAPA::tempdir();
11101: 
11102: }
11103: 
11104: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
11105: 				'compress_threshold'=> 20_000,
11106:  			        });
11107: 
11108: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
11109: $dumpcount=0;
11110: $locknum=0;
11111: 
11112: &logtouch();
11113: &logthis('<font color="yellow">INFO: Read configuration</font>');
11114: $readit=1;
11115:     {
11116: 	use integer;
11117: 	my $test=(2**32)+1;
11118: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
11119: 	&logthis(" Detected 64bit platform ($_64bit)");
11120:     }
11121: }
11122: }
11123: 
11124: 1;
11125: __END__
11126: 
11127: =pod
11128: 
11129: =head1 NAME
11130: 
11131: Apache::lonnet - Subroutines to ask questions about things in the network.
11132: 
11133: =head1 SYNOPSIS
11134: 
11135: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
11136: 
11137:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
11138: 
11139: Common parameters:
11140: 
11141: =over 4
11142: 
11143: =item *
11144: 
11145: $uname : an internal username (if $cname expecting a course Id specifically)
11146: 
11147: =item *
11148: 
11149: $udom : a domain (if $cdom expecting a course's domain specifically)
11150: 
11151: =item *
11152: 
11153: $symb : a resource instance identifier
11154: 
11155: =item *
11156: 
11157: $namespace : the name of a .db file that contains the data needed or
11158: being set.
11159: 
11160: =back
11161: 
11162: =head1 OVERVIEW
11163: 
11164: lonnet provides subroutines which interact with the
11165: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
11166: about classes, users, and resources.
11167: 
11168: For many of these objects you can also use this to store data about
11169: them or modify them in various ways.
11170: 
11171: =head2 Symbs
11172: 
11173: To identify a specific instance of a resource, LON-CAPA uses symbols
11174: or "symbs"X<symb>. These identifiers are built from the URL of the
11175: map, the resource number of the resource in the map, and the URL of
11176: the resource itself. The latter is somewhat redundant, but might help
11177: if maps change.
11178: 
11179: An example is
11180: 
11181:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
11182: 
11183: The respective map entry is
11184: 
11185:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
11186:   title="Problem 2">
11187:  </resource>
11188: 
11189: Symbs are used by the random number generator, as well as to store and
11190: restore data specific to a certain instance of for example a problem.
11191: 
11192: =head2 Storing And Retrieving Data
11193: 
11194: X<store()>X<cstore()>X<restore()>Three of the most important functions
11195: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
11196: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
11197: is is the non-critical message twin of cstore. These functions are for
11198: handlers to store a perl hash to a user's permanent data space in an
11199: easy manner, and to retrieve it again on another call. It is expected
11200: that a handler would use this once at the beginning to retrieve data,
11201: and then again once at the end to send only the new data back.
11202: 
11203: The data is stored in the user's data directory on the user's
11204: homeserver under the ID of the course.
11205: 
11206: The hash that is returned by restore will have all of the previous
11207: value for all of the elements of the hash.
11208: 
11209: Example:
11210: 
11211:  #creating a hash
11212:  my %hash;
11213:  $hash{'foo'}='bar';
11214: 
11215:  #storing it
11216:  &Apache::lonnet::cstore(\%hash);
11217: 
11218:  #changing a value
11219:  $hash{'foo'}='notbar';
11220: 
11221:  #adding a new value
11222:  $hash{'bar'}='foo';
11223:  &Apache::lonnet::cstore(\%hash);
11224: 
11225:  #retrieving the hash
11226:  my %history=&Apache::lonnet::restore();
11227: 
11228:  #print the hash
11229:  foreach my $key (sort(keys(%history))) {
11230:    print("\%history{$key} = $history{$key}");
11231:  }
11232: 
11233: Will print out:
11234: 
11235:  %history{1:foo} = bar
11236:  %history{1:keys} = foo:timestamp
11237:  %history{1:timestamp} = 990455579
11238:  %history{2:bar} = foo
11239:  %history{2:foo} = notbar
11240:  %history{2:keys} = foo:bar:timestamp
11241:  %history{2:timestamp} = 990455580
11242:  %history{bar} = foo
11243:  %history{foo} = notbar
11244:  %history{timestamp} = 990455580
11245:  %history{version} = 2
11246: 
11247: Note that the special hash entries C<keys>, C<version> and
11248: C<timestamp> were added to the hash. C<version> will be equal to the
11249: total number of versions of the data that have been stored. The
11250: C<timestamp> attribute will be the UNIX time the hash was
11251: stored. C<keys> is available in every historical section to list which
11252: keys were added or changed at a specific historical revision of a
11253: hash.
11254: 
11255: B<Warning>: do not store the hash that restore returns directly. This
11256: will cause a mess since it will restore the historical keys as if the
11257: were new keys. I.E. 1:foo will become 1:1:foo etc.
11258: 
11259: Calling convention:
11260: 
11261:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
11262:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
11263: 
11264: For more detailed information, see lonnet specific documentation.
11265: 
11266: =head1 RETURN MESSAGES
11267: 
11268: =over 4
11269: 
11270: =item * B<con_lost>: unable to contact remote host
11271: 
11272: =item * B<con_delayed>: unable to contact remote host, message will be delivered
11273: when the connection is brought back up
11274: 
11275: =item * B<con_failed>: unable to contact remote host and unable to save message
11276: for later delivery
11277: 
11278: =item * B<error:>: an error a occurred, a description of the error follows the :
11279: 
11280: =item * B<no_such_host>: unable to fund a host associated with the user/domain
11281: that was requested
11282: 
11283: =back
11284: 
11285: =head1 PUBLIC SUBROUTINES
11286: 
11287: =head2 Session Environment Functions
11288: 
11289: =over 4
11290: 
11291: =item * 
11292: X<appenv()>
11293: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
11294: the user envirnoment file, and will be restored for each access this
11295: user makes during this session, also modifies the %env for the current
11296: process. Optional rolesarrayref - if defined contains a reference to an array
11297: of roles which are exempt from the restriction on modifying user.role entries 
11298: in the user's environment.db and in %env.    
11299: 
11300: =item *
11301: X<delenv()>
11302: B<delenv($delthis,$regexp)>: removes all items from the session
11303: environment file that begin with $delthis. If the 
11304: optional second arg - $regexp - is true, $delthis is treated as a 
11305: regular expression, otherwise \Q$delthis\E is used. 
11306: The values are also deleted from the current processes %env.
11307: 
11308: =item * get_env_multiple($name) 
11309: 
11310: gets $name from the %env hash, it seemlessly handles the cases where multiple
11311: values may be defined and end up as an array ref.
11312: 
11313: returns an array of values
11314: 
11315: =back
11316: 
11317: =head2 User Information
11318: 
11319: =over 4
11320: 
11321: =item *
11322: X<queryauthenticate()>
11323: B<queryauthenticate($uname,$udom)>: try to determine user's current 
11324: authentication scheme
11325: 
11326: =item *
11327: X<authenticate()>
11328: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
11329: authenticate user from domain's lib servers (first use the current
11330: one). C<$upass> should be the users password.
11331: $checkdefauth is optional (value is 1 if a check should be made to
11332:    authenticate user using default authentication method, and allow
11333:    account creation if username does not have account in the domain).
11334: $clientcancheckhost is optional (value is 1 if checking whether the
11335:    server can host will occur on the client side in lonauth.pm).   
11336: 
11337: =item *
11338: X<homeserver()>
11339: B<homeserver($uname,$udom)>: find the server which has
11340: the user's directory and files (there must be only one), this caches
11341: the answer, and also caches if there is a borken connection.
11342: 
11343: =item *
11344: X<idget()>
11345: B<idget($udom,@ids)>: find the usernames behind a list of IDs
11346: (IDs are a unique resource in a domain, there must be only 1 ID per
11347: username, and only 1 username per ID in a specific domain) (returns
11348: hash: id=>name,id=>name)
11349: 
11350: =item *
11351: X<idrget()>
11352: B<idrget($udom,@unames)>: find the IDs behind a list of
11353: usernames (returns hash: name=>id,name=>id)
11354: 
11355: =item *
11356: X<idput()>
11357: B<idput($udom,%ids)>: store away a list of names and associated IDs
11358: 
11359: =item *
11360: X<rolesinit()>
11361: B<rolesinit($udom,$username,$authhost)>: get user privileges
11362: 
11363: =item *
11364: X<getsection()>
11365: B<getsection($udom,$uname,$cname)>: finds the section of student in the
11366: course $cname, return section name/number or '' for "not in course"
11367: and '-1' for "no section"
11368: 
11369: =item *
11370: X<userenvironment()>
11371: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
11372: passed in @what from the requested user's environment, returns a hash
11373: 
11374: =item * 
11375: X<userlog_query()>
11376: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
11377: activity.log file. %filters defines filters applied when parsing the
11378: log file. These can be start or end timestamps, or the type of action
11379: - log to look for Login or Logout events, check for Checkin or
11380: Checkout, role for role selection. The response is in the form
11381: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
11382: escaped strings of the action recorded in the activity.log file.
11383: 
11384: =back
11385: 
11386: =head2 User Roles
11387: 
11388: =over 4
11389: 
11390: =item *
11391: 
11392: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
11393:  F: full access
11394:  U,I,K: authentication modes (cxx only)
11395:  '': forbidden
11396:  1: user needs to choose course
11397:  2: browse allowed
11398:  A: passphrase authentication needed
11399: 
11400: =item *
11401: 
11402: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
11403: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
11404: and course level
11405: 
11406: =item *
11407: 
11408: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
11409: (rolesplain.tab); plain text explanation of a user role term.
11410: $type is Course (default) or Community.
11411: If $forcedefault evaluates to true, text returned will be default 
11412: text for $type. Otherwise, if this is a course, the text returned 
11413: will be a custom name for the role (if defined in the course's 
11414: environment).  If no custom name is defined the default is returned.
11415:    
11416: =item *
11417: 
11418: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
11419: All arguments are optional. Returns a hash of a roles, either for
11420: co-author/assistant author roles for a user's Construction Space
11421: (default), or if $context is 'userroles', roles for the user himself,
11422: In the hash, keys are set to colon-separated $uname,$udom,$role, and
11423: (optionally) if $withsec is true, a fourth colon-separated item - $section.
11424: For each key, value is set to colon-separated start and end times for
11425: the role.  If no username and domain are specified, will default to
11426: current user/domain. Types, roles, and roledoms are references to arrays
11427: of role statuses (active, future or previous), roles 
11428: (e.g., cc,in, st etc.) and domains of the roles which can be used
11429: to restrict the list of roles reported. If no array ref is 
11430: provided for types, will default to return only active roles.
11431: 
11432: =back
11433: 
11434: =head2 User Modification
11435: 
11436: =over 4
11437: 
11438: =item *
11439: 
11440: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
11441: user for the level given by URL.  Optional start and end dates (leave empty
11442: string or zero for "no date")
11443: 
11444: =item *
11445: 
11446: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
11447: change a users, password, possible return values are: ok,
11448: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
11449: refused
11450: 
11451: =item *
11452: 
11453: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
11454: 
11455: =item *
11456: 
11457: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
11458:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
11459: 
11460: will update user information (firstname,middlename,lastname,generation,
11461: permanentemail), and if forceid is true, student/employee ID also.
11462: A user's institutional affiliation(s) can also be updated.
11463: User information fields will not be overwritten with empty entries 
11464: unless the field is included in the $candelete array reference.
11465: This array is included when a single user is modified via "Manage Users",
11466: or when Autoupdate.pl is run by cron in a domain.
11467: 
11468: =item *
11469: 
11470: modifystudent
11471: 
11472: modify a student's enrollment and identification information.
11473: The course id is resolved based on the current users environment.  
11474: This means the envoking user must be a course coordinator or otherwise
11475: associated with a course.
11476: 
11477: This call is essentially a wrapper for lonnet::modifyuser and
11478: lonnet::modify_student_enrollment
11479: 
11480: Inputs: 
11481: 
11482: =over 4
11483: 
11484: =item B<$udom> Student's loncapa domain
11485: 
11486: =item B<$uname> Student's loncapa login name
11487: 
11488: =item B<$uid> Student/Employee ID
11489: 
11490: =item B<$umode> Student's authentication mode
11491: 
11492: =item B<$upass> Student's password
11493: 
11494: =item B<$first> Student's first name
11495: 
11496: =item B<$middle> Student's middle name
11497: 
11498: =item B<$last> Student's last name
11499: 
11500: =item B<$gene> Student's generation
11501: 
11502: =item B<$usec> Student's section in course
11503: 
11504: =item B<$end> Unix time of the roles expiration
11505: 
11506: =item B<$start> Unix time of the roles start date
11507: 
11508: =item B<$forceid> If defined, allow $uid to be changed
11509: 
11510: =item B<$desiredhome> server to use as home server for student
11511: 
11512: =item B<$email> Student's permanent e-mail address
11513: 
11514: =item B<$type> Type of enrollment (auto or manual)
11515: 
11516: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
11517: 
11518: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
11519: 
11520: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
11521: 
11522: =item B<$context> role change context (shown in User Management Logs display in a course)
11523: 
11524: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
11525: 
11526: =back
11527: 
11528: =item *
11529: 
11530: modify_student_enrollment
11531: 
11532: Change a students enrollment status in a class.  The environment variable
11533: 'role.request.course' must be defined for this function to proceed.
11534: 
11535: Inputs:
11536: 
11537: =over 4
11538: 
11539: =item $udom, students domain
11540: 
11541: =item $uname, students name
11542: 
11543: =item $uid, students user id
11544: 
11545: =item $first, students first name
11546: 
11547: =item $middle
11548: 
11549: =item $last
11550: 
11551: =item $gene
11552: 
11553: =item $usec
11554: 
11555: =item $end
11556: 
11557: =item $start
11558: 
11559: =item $type
11560: 
11561: =item $locktype
11562: 
11563: =item $cid
11564: 
11565: =item $selfenroll
11566: 
11567: =item $context
11568: 
11569: =back
11570: 
11571: 
11572: =item *
11573: 
11574: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
11575: custom role; give a custom role to a user for the level given by URL.  Specify
11576: name and domain of role author, and role name
11577: 
11578: =item *
11579: 
11580: revokerole($udom,$uname,$url,$role) : revoke a role for url
11581: 
11582: =item *
11583: 
11584: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
11585: 
11586: =back
11587: 
11588: =head2 Course Infomation
11589: 
11590: =over 4
11591: 
11592: =item *
11593: 
11594: coursedescription($courseid,$options) : returns a hash of information about the
11595: specified course id, including all environment settings for the
11596: course, the description of the course will be in the hash under the
11597: key 'description'
11598: 
11599: $options is an optional parameter that if supplied is a hash reference that controls
11600: what how this function works.  It has the following key/values:
11601: 
11602: =over 4
11603: 
11604: =item freshen_cache
11605: 
11606: If defined, and the environment cache for the course is valid, it is 
11607: returned in the returned hash.
11608: 
11609: =item one_time
11610: 
11611: If defined, the last cache time is set to _now_
11612: 
11613: =item user
11614: 
11615: If defined, the supplied username is used instead of the current user.
11616: 
11617: 
11618: =back
11619: 
11620: =item *
11621: 
11622: resdata($name,$domain,$type,@which) : request for current parameter
11623: setting for a specific $type, where $type is either 'course' or 'user',
11624: @what should be a list of parameters to ask about. This routine caches
11625: answers for 5 minutes.
11626: 
11627: =item *
11628: 
11629: get_courseresdata($courseid, $domain) : dump the entire course resource
11630: data base, returning a hash that is keyed by the resource name and has
11631: values that are the resource value.  I believe that the timestamps and
11632: versions are also returned.
11633: 
11634: 
11635: =back
11636: 
11637: =head2 Course Modification
11638: 
11639: =over 4
11640: 
11641: =item *
11642: 
11643: writecoursepref($courseid,%prefs) : write preferences (environment
11644: database) for a course
11645: 
11646: =item *
11647: 
11648: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
11649: 
11650: =item *
11651: 
11652: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
11653: 
11654: =back
11655: 
11656: =head2 Resource Subroutines
11657: 
11658: =over 4
11659: 
11660: =item *
11661: 
11662: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
11663: 
11664: =item *
11665: 
11666: repcopy($filename) : subscribes to the requested file, and attempts to
11667: replicate from the owning library server, Might return
11668: 'unavailable', 'not_found', 'forbidden', 'ok', or
11669: 'bad_request', also attempts to grab the metadata for the
11670: resource. Expects the local filesystem pathname
11671: (/home/httpd/html/res/....)
11672: 
11673: =back
11674: 
11675: =head2 Resource Information
11676: 
11677: =over 4
11678: 
11679: =item *
11680: 
11681: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
11682: a vairety of different possible values, $varname should be a request
11683: string, and the other parameters can be used to specify who and what
11684: one is asking about.
11685: 
11686: Possible values for $varname are environment.lastname (or other item
11687: from the envirnment hash), user.name (or someother aspect about the
11688: user), resource.0.maxtries (or some other part and parameter of a
11689: resource)
11690: 
11691: =item *
11692: 
11693: directcondval($number) : get current value of a condition; reads from a state
11694: string
11695: 
11696: =item *
11697: 
11698: condval($condidx) : value of condition index based on state
11699: 
11700: =item *
11701: 
11702: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
11703: resource's metadata, $what should be either a specific key, or either
11704: 'keys' (to get a list of possible keys) or 'packages' to get a list of
11705: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
11706: 
11707: this function automatically caches all requests
11708: 
11709: =item *
11710: 
11711: metadata_query($query,$custom,$customshow) : make a metadata query against the
11712: network of library servers; returns file handle of where SQL and regex results
11713: will be stored for query
11714: 
11715: =item *
11716: 
11717: symbread($filename) : return symbolic list entry (filename argument optional);
11718: returns the data handle
11719: 
11720: =item *
11721: 
11722: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
11723: a possible symb for the URL in $thisfn, and if is an encryypted
11724: resource that the user accessed using /enc/ returns a 1 on success, 0
11725: on failure, user must be in a course, as it assumes the existance of
11726: the course initial hash, and uses $env('request.course.id'}
11727: 
11728: 
11729: =item *
11730: 
11731: symbclean($symb) : removes versions numbers from a symb, returns the
11732: cleaned symb
11733: 
11734: =item *
11735: 
11736: is_on_map($uri) : checks if the $uri is somewhere on the current
11737: course map, user must be in a course for it to work.
11738: 
11739: =item *
11740: 
11741: numval($salt) : return random seed value (addend for rndseed)
11742: 
11743: =item *
11744: 
11745: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
11746: a random seed, all arguments are optional, if they aren't sent it uses the
11747: environment to derive them. Note: if symb isn't sent and it can't get one
11748: from &symbread it will use the current time as its return value
11749: 
11750: =item *
11751: 
11752: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
11753: unfakeable, receipt
11754: 
11755: =item *
11756: 
11757: receipt() : API to ireceipt working off of env values; given out to users
11758: 
11759: =item *
11760: 
11761: countacc($url) : count the number of accesses to a given URL
11762: 
11763: =item *
11764: 
11765: 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
11766: 
11767: =item *
11768: 
11769: 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)
11770: 
11771: =item *
11772: 
11773: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
11774: 
11775: =item *
11776: 
11777: devalidate($symb) : devalidate temporary spreadsheet calculations,
11778: forcing spreadsheet to reevaluate the resource scores next time.
11779: 
11780: =back
11781: 
11782: =head2 Storing/Retreiving Data
11783: 
11784: =over 4
11785: 
11786: =item *
11787: 
11788: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
11789: for this url; hashref needs to be given and should be a \%hashname; the
11790: remaining args aren't required and if they aren't passed or are '' they will
11791: be derived from the env
11792: 
11793: =item *
11794: 
11795: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
11796: uses critical subroutine
11797: 
11798: =item *
11799: 
11800: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
11801: all args are optional
11802: 
11803: =item *
11804: 
11805: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
11806: dumps the complete (or key matching regexp) namespace into a hash
11807: ($udom, $uname, $regexp, $range are optional) for a namespace that is
11808: normally &store()ed into
11809: 
11810: $range should be either an integer '100' (give me the first 100
11811:                                            matching records)
11812:               or be  two integers sperated by a - with no spaces
11813:                  '30-50' (give me the 30th through the 50th matching
11814:                           records)
11815: 
11816: 
11817: =item *
11818: 
11819: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
11820: replaces a &store() version of data with a replacement set of data
11821: for a particular resource in a namespace passed in the $storehash hash 
11822: reference
11823: 
11824: =item *
11825: 
11826: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
11827: works very similar to store/cstore, but all data is stored in a
11828: temporary location and can be reset using tmpreset, $storehash should
11829: be a hash reference, returns nothing on success
11830: 
11831: =item *
11832: 
11833: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
11834: similar to restore, but all data is stored in a temporary location and
11835: can be reset using tmpreset. Returns a hash of values on success,
11836: error string otherwise.
11837: 
11838: =item *
11839: 
11840: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
11841: deltes all keys for $symb form the temporary storage hash.
11842: 
11843: =item *
11844: 
11845: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
11846: reference filled in from namesp ($udom and $uname are optional)
11847: 
11848: =item *
11849: 
11850: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
11851: namesp ($udom and $uname are optional)
11852: 
11853: =item *
11854: 
11855: dump($namespace,$udom,$uname,$regexp,$range) : 
11856: dumps the complete (or key matching regexp) namespace into a hash
11857: ($udom, $uname, $regexp, $range are optional)
11858: 
11859: $range should be either an integer '100' (give me the first 100
11860:                                            matching records)
11861:               or be  two integers sperated by a - with no spaces
11862:                  '30-50' (give me the 30th through the 50th matching
11863:                           records)
11864: =item *
11865: 
11866: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
11867: $store can be a scalar, an array reference, or if the amount to be 
11868: incremented is > 1, a hash reference.
11869: 
11870: ($udom and $uname are optional)
11871: 
11872: =item *
11873: 
11874: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
11875: ($udom and $uname are optional)
11876: 
11877: =item *
11878: 
11879: cput($namespace,$storehash,$udom,$uname) : critical put
11880: ($udom and $uname are optional)
11881: 
11882: =item *
11883: 
11884: newput($namespace,$storehash,$udom,$uname) :
11885: 
11886: Attempts to store the items in the $storehash, but only if they don't
11887: currently exist, if this succeeds you can be certain that you have 
11888: successfully created a new key value pair in the $namespace db.
11889: 
11890: 
11891: Args:
11892:  $namespace: name of database to store values to
11893:  $storehash: hashref to store to the db
11894:  $udom: (optional) domain of user containing the db
11895:  $uname: (optional) name of user caontaining the db
11896: 
11897: Returns:
11898:  'ok' -> succeeded in storing all keys of $storehash
11899:  'key_exists: <key>' -> failed to anything out of $storehash, as at
11900:                         least <key> already existed in the db (other
11901:                         requested keys may also already exist)
11902:  'error: <msg>' -> unable to tie the DB or other error occurred
11903:  'con_lost' -> unable to contact request server
11904:  'refused' -> action was not allowed by remote machine
11905: 
11906: 
11907: =item *
11908: 
11909: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
11910: reference filled in from namesp (encrypts the return communication)
11911: ($udom and $uname are optional)
11912: 
11913: =item *
11914: 
11915: log($udom,$name,$home,$message) : write to permanent log for user; use
11916: critical subroutine
11917: 
11918: =item *
11919: 
11920: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
11921: array reference filled in from namespace found in domain level on either
11922: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
11923: 
11924: =item *
11925: 
11926: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
11927: domain level either on specified domain server ($uhome) or primary domain 
11928: server ($udom and $uhome are optional)
11929: 
11930: =item * 
11931: 
11932: get_domain_defaults($target_domain) : returns hash with defaults for
11933: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
11934: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
11935: or localauth), initial password or a kerberos realm, language (e.g., en-us).
11936: Values are retrieved from cache (if current), or from domain's configuration.db
11937: (if available), or lastly from values in lonTabs/dns_domain,tab, 
11938: or lonTabs/domain.tab. 
11939: 
11940: %domdefaults = &get_auth_defaults($target_domain);
11941: 
11942: =back
11943: 
11944: =head2 Network Status Functions
11945: 
11946: =over 4
11947: 
11948: =item *
11949: 
11950: dirlist() : return directory list based on URI (first arg).
11951: 
11952: Inputs: 1 required, 5 optional.
11953: 
11954: =over
11955: 
11956: =item 
11957: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
11958: 
11959: =item
11960: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
11961: 
11962: =item
11963: $username -  username of user/course to be listed. Extracted from $uri if absent. 
11964: 
11965: =item
11966: $getpropath - boolean: 1 if prepend path using &propath(). 
11967: 
11968: =item
11969: $getuserdir - boolean: 1 if prepend path for "userfiles".
11970: 
11971: =item 
11972: $alternateRoot - path to prepend in place of path from $uri.
11973: 
11974: =back
11975: 
11976: Returns: Array of up to two items.
11977: 
11978: =over
11979: 
11980: a reference to an array of files/subdirectories
11981: 
11982: =over
11983: 
11984: Each element in the array of files/subdirectories is a & separated list of
11985: item name and the result of running stat on the item.  If dirlist was requested
11986: for a file instead of a directory, the item name will be ''. For a directory 
11987: listing, if the item is a metadata file, the element will end &N&M 
11988: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
11989: default copyright set (1).  
11990: 
11991: =back
11992: 
11993: a scalar containing error condition (if encountered).
11994: 
11995: =over
11996: 
11997: =item 
11998: no_host (no homeserver identified for $username:$domain).
11999: 
12000: =item 
12001: no_such_host (server contacted for listing not identified as valid host).
12002: 
12003: =item 
12004: con_lost (connection to remote server failed).
12005: 
12006: =item 
12007: refused (invalid $username:$domain received on lond side).
12008: 
12009: =item 
12010: no_such_dir (directory at specified path on lond side does not exist). 
12011: 
12012: =item 
12013: empty (directory at specified path on lond side is empty).
12014: 
12015: =over
12016: 
12017: This is currently not encountered because the &ls3, &ls2, 
12018: &ls (_handler) routines on the lond side do not filter out
12019: . and .. from a directory listing. 
12020: 
12021: =back
12022: 
12023: =back
12024: 
12025: =back
12026: 
12027: =item *
12028: 
12029: spareserver() : find server with least workload from spare.tab
12030: 
12031: 
12032: =item *
12033: 
12034: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
12035: if there is no corresponding loncapa host.
12036: 
12037: =back
12038: 
12039: 
12040: =head2 Apache Request
12041: 
12042: =over 4
12043: 
12044: =item *
12045: 
12046: ssi($url,%hash) : server side include, does a complete request cycle on url to
12047: localhost, posts hash
12048: 
12049: =back
12050: 
12051: =head2 Data to String to Data
12052: 
12053: =over 4
12054: 
12055: =item *
12056: 
12057: hash2str(%hash) : convert a hash into a string complete with escaping and '='
12058: and '&' separators, supports elements that are arrayrefs and hashrefs
12059: 
12060: =item *
12061: 
12062: hashref2str($hashref) : convert a hashref into a string complete with
12063: escaping and '=' and '&' separators, supports elements that are
12064: arrayrefs and hashrefs
12065: 
12066: =item *
12067: 
12068: arrayref2str($arrayref) : convert an arrayref into a string complete
12069: with escaping and '&' separators, supports elements that are arrayrefs
12070: and hashrefs
12071: 
12072: =item *
12073: 
12074: str2hash($string) : convert string to hash using unescaping and
12075: splitting on '=' and '&', supports elements that are arrayrefs and
12076: hashrefs
12077: 
12078: =item *
12079: 
12080: str2array($string) : convert string to hash using unescaping and
12081: splitting on '&', supports elements that are arrayrefs and hashrefs
12082: 
12083: =back
12084: 
12085: =head2 Logging Routines
12086: 
12087: 
12088: These routines allow one to make log messages in the lonnet.log and
12089: lonnet.perm logfiles.
12090: 
12091: =over 4
12092: 
12093: =item *
12094: 
12095: logtouch() : make sure the logfile, lonnet.log, exists
12096: 
12097: =item *
12098: 
12099: logthis() : append message to the normal lonnet.log file, it gets
12100: preiodically rolled over and deleted.
12101: 
12102: =item *
12103: 
12104: logperm() : append a permanent message to lonnet.perm.log, this log
12105: file never gets deleted by any automated portion of the system, only
12106: messages of critical importance should go in here.
12107: 
12108: 
12109: =back
12110: 
12111: =head2 General File Helper Routines
12112: 
12113: =over 4
12114: 
12115: =item *
12116: 
12117: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
12118: (a) files in /uploaded
12119:   (i) If a local copy of the file exists - 
12120:       compares modification date of local copy with last-modified date for 
12121:       definitive version stored on home server for course. If local copy is 
12122:       stale, requests a new version from the home server and stores it. 
12123:       If the original has been removed from the home server, then local copy 
12124:       is unlinked.
12125:   (ii) If local copy does not exist -
12126:       requests the file from the home server and stores it. 
12127:   
12128:   If $caller is 'uploadrep':  
12129:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
12130:     for request for files originally uploaded via DOCS. 
12131:      - returns 'ok' if fresh local copy now available, -1 otherwise.
12132:   
12133:   Otherwise:
12134:      This indicates a call from the content generation phase of the request.
12135:      -  returns the entire contents of the file or -1.
12136:      
12137: (b) files in /res
12138:    - returns the entire contents of a file or -1; 
12139:    it properly subscribes to and replicates the file if neccessary.
12140: 
12141: 
12142: =item *
12143: 
12144: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
12145:                   reference
12146: 
12147: returns either a stat() list of data about the file or an empty list
12148: if the file doesn't exist or couldn't find out about it (connection
12149: problems or user unknown)
12150: 
12151: =item *
12152: 
12153: filelocation($dir,$file) : returns file system location of a file
12154: based on URI; meant to be "fairly clean" absolute reference, $dir is a
12155: directory that relative $file lookups are to looked in ($dir of /a/dir
12156: and a file of ../bob will become /a/bob)
12157: 
12158: =item *
12159: 
12160: hreflocation($dir,$file) : returns file system location or a URL; same as
12161: filelocation except for hrefs
12162: 
12163: =item *
12164: 
12165: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
12166: 
12167: =back
12168: 
12169: =head2 Usererfile file routines (/uploaded*)
12170: 
12171: =over 4
12172: 
12173: =item *
12174: 
12175: userfileupload(): main rotine for putting a file in a user or course's
12176:                   filespace, arguments are,
12177: 
12178:  formname - required - this is the name of the element in $env where the
12179:            filename, and the contents of the file to create/modifed exist
12180:            the filename is in $env{'form.'.$formname.'.filename'} and the
12181:            contents of the file is located in $env{'form.'.$formname}
12182:  context - if coursedoc, store the file in the course of the active role
12183:              of the current user; 
12184:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
12185:            if 'canceloverwrite': delete file in tmp/overwrites directory
12186:  subdir - required - subdirectory to put the file in under ../userfiles/
12187:          if undefined, it will be placed in "unknown"
12188: 
12189:  (This routine calls clean_filename() to remove any dangerous
12190:  characters from the filename, and then calls finuserfileupload() to
12191:  complete the transaction)
12192: 
12193:  returns either the url of the uploaded file (/uploaded/....) if successful
12194:  and /adm/notfound.html if unsuccessful
12195: 
12196: =item *
12197: 
12198: clean_filename(): routine for cleaing a filename up for storage in
12199:                  userfile space, argument is:
12200: 
12201:  filename - proposed filename
12202: 
12203: returns: the new clean filename
12204: 
12205: =item *
12206: 
12207: finishuserfileupload(): routine that creates and sends the file to
12208: userspace, probably shouldn't be called directly
12209: 
12210:   docuname: username or courseid of destination for the file
12211:   docudom: domain of user/course of destination for the file
12212:   formname: same as for userfileupload()
12213:   fname: filename (including subdirectories) for the file
12214:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
12215:   allfiles: reference to hash used to store objects found by parser
12216:   codebase: reference to hash used for codebases of java objects found by parser
12217:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
12218:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
12219:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
12220:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
12221:   context: if 'overwrite', will move the uploaded file from its temporary location to
12222:             userfiles to facilitate overwriting a previously uploaded file with same name.
12223:   mimetype: reference to scalar to accommodate mime type determined
12224:             from File::MMagic if $parser = parse.
12225: 
12226:  returns either the url of the uploaded file (/uploaded/....) if successful
12227:  and /adm/notfound.html if unsuccessful (or an error message if context 
12228:  was 'overwrite').
12229:  
12230: 
12231: =item *
12232: 
12233: renameuserfile(): renames an existing userfile to a new name
12234: 
12235:   Args:
12236:    docuname: username or courseid of destination for the file
12237:    docudom: domain of user/course of destination for the file
12238:    old: current file name (including any subdirs under userfiles)
12239:    new: desired file name (including any subdirs under userfiles)
12240: 
12241: =item *
12242: 
12243: mkdiruserfile(): creates a directory is a userfiles dir
12244: 
12245:   Args:
12246:    docuname: username or courseid of destination for the file
12247:    docudom: domain of user/course of destination for the file
12248:    dir: dir to create (including any subdirs under userfiles)
12249: 
12250: =item *
12251: 
12252: removeuserfile(): removes a file that exists in userfiles
12253: 
12254:   Args:
12255:    docuname: username or courseid of destination for the file
12256:    docudom: domain of user/course of destination for the file
12257:    fname: filname to delete (including any subdirs under userfiles)
12258: 
12259: =item *
12260: 
12261: removeuploadedurl(): convience function for removeuserfile()
12262: 
12263:   Args:
12264:    url:  a full /uploaded/... url to delete
12265: 
12266: =item * 
12267: 
12268: get_portfile_permissions():
12269:   Args:
12270:     domain: domain of user or course contain the portfolio files
12271:     user: name of user or num of course contain the portfolio files
12272:   Returns:
12273:     hashref of a dump of the proper file_permissions.db
12274:    
12275: 
12276: =item * 
12277: 
12278: get_access_controls():
12279: 
12280: Args:
12281:   current_permissions: the hash ref returned from get_portfile_permissions()
12282:   group: (optional) the group you want the files associated with
12283:   file: (optional) the file you want access info on
12284: 
12285: Returns:
12286:     a hash (keys are file names) of hashes containing
12287:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
12288:         values are XML containing access control settings (see below) 
12289: 
12290: Internal notes:
12291: 
12292:  access controls are stored in file_permissions.db as key=value pairs.
12293:     key -> path to file/file_name\0uniqueID:scope_end_start
12294:         where scope -> public,guest,course,group,domains or users.
12295:               end -> UNIX time for end of access (0 -> no end date)
12296:               start -> UNIX time for start of access
12297: 
12298:     value -> XML description of access control
12299:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
12300:             <start></start>
12301:             <end></end>
12302: 
12303:             <password></password>  for scope type = guest
12304: 
12305:             <domain></domain>     for scope type = course or group
12306:             <number></number>
12307:             <roles id="">
12308:              <role></role>
12309:              <access></access>
12310:              <section></section>
12311:              <group></group>
12312:             </roles>
12313: 
12314:             <dom></dom>         for scope type = domains
12315: 
12316:             <users>             for scope type = users
12317:              <user>
12318:               <uname></uname>
12319:               <udom></udom>
12320:              </user>
12321:             </users>
12322:            </scope> 
12323:               
12324:  Access data is also aggregated for each file in an additional key=value pair:
12325:  key -> path to file/file_name\0accesscontrol 
12326:  value -> reference to hash
12327:           hash contains key = value pairs
12328:           where key = uniqueID:scope_end_start
12329:                 value = UNIX time record was last updated
12330: 
12331:           Used to improve speed of look-ups of access controls for each file.  
12332:  
12333:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
12334: 
12335: modify_access_controls():
12336: 
12337: Modifies access controls for a portfolio file
12338: Args
12339: 1. file name
12340: 2. reference to hash of required changes,
12341: 3. domain
12342: 4. username
12343:   where domain,username are the domain of the portfolio owner 
12344:   (either a user or a course) 
12345: 
12346: Returns:
12347: 1. result of additions or updates ('ok' or 'error', with error message). 
12348: 2. result of deletions ('ok' or 'error', with error message).
12349: 3. reference to hash of any new or updated access controls.
12350: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
12351:    key = integer (inbound ID)
12352:    value = uniqueID  
12353: 
12354: =back
12355: 
12356: =head2 HTTP Helper Routines
12357: 
12358: =over 4
12359: 
12360: =item *
12361: 
12362: escape() : unpack non-word characters into CGI-compatible hex codes
12363: 
12364: =item *
12365: 
12366: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
12367: 
12368: =back
12369: 
12370: =head1 PRIVATE SUBROUTINES
12371: 
12372: =head2 Underlying communication routines (Shouldn't call)
12373: 
12374: =over 4
12375: 
12376: =item *
12377: 
12378: subreply() : tries to pass a message to lonc, returns con_lost if incapable
12379: 
12380: =item *
12381: 
12382: reply() : uses subreply to send a message to remote machine, logs all failures
12383: 
12384: =item *
12385: 
12386: critical() : passes a critical message to another server; if cannot
12387: get through then place message in connection buffer directory and
12388: returns con_delayed, if incapable of saving message, returns
12389: con_failed
12390: 
12391: =item *
12392: 
12393: reconlonc() : tries to reconnect lonc client processes.
12394: 
12395: =back
12396: 
12397: =head2 Resource Access Logging
12398: 
12399: =over 4
12400: 
12401: =item *
12402: 
12403: flushcourselogs() : flush (save) buffer logs and access logs
12404: 
12405: =item *
12406: 
12407: courselog($what) : save message for course in hash
12408: 
12409: =item *
12410: 
12411: courseacclog($what) : save message for course using &courselog().  Perform
12412: special processing for specific resource types (problems, exams, quizzes, etc).
12413: 
12414: =item *
12415: 
12416: goodbye() : flush course logs and log shutting down; it is called in srm.conf
12417: as a PerlChildExitHandler
12418: 
12419: =back
12420: 
12421: =head2 Other
12422: 
12423: =over 4
12424: 
12425: =item *
12426: 
12427: symblist($mapname,%newhash) : update symbolic storage links
12428: 
12429: =back
12430: 
12431: =cut
12432: 

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