File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1172.2.43: download - view: text, annotated - select for diffs
Wed Apr 16 16:21:24 2014 UTC (10 years, 2 months ago) by raeburn
Branches: version_2_11_X
- For 2.11
  - Backport 1.1255

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1172.2.43 2014/04/16 16:21:24 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: ###
   29: 
   30: =pod
   31: 
   32: =head1 NAME
   33: 
   34: Apache::lonnet.pm
   35: 
   36: =head1 SYNOPSIS
   37: 
   38: This file is an interface to the lonc processes of
   39: the LON-CAPA network as well as set of elaborated functions for handling information
   40: necessary for navigating through a given cluster of LON-CAPA machines within a
   41: domain. There are over 40 specialized functions in this module which handle the
   42: reading and transmission of metadata, user information (ids, names, environments, roles,
   43: logs), file information (storage, reading, directories, extensions, replication, embedded
   44: styles and descriptors), educational resources (course descriptions, section names and
   45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
   46: and from more descriptive phrases or explanations.
   47: 
   48: This is part of the LearningOnline Network with CAPA project
   49: described at http://www.lon-capa.org.
   50: 
   51: =head1 Package Variables
   52: 
   53: These are largely undocumented, so if you decipher one please note it here.
   54: 
   55: =over 4
   56: 
   57: =item $processmarker
   58: 
   59: Contains the time this process was started and this servers host id.
   60: 
   61: =item $dumpcount
   62: 
   63: Counts the number of times a message log flush has been attempted (regardless
   64: of success) by this process.  Used as part of the filename when messages are
   65: delayed.
   66: 
   67: =back
   68: 
   69: =cut
   70: 
   71: package Apache::lonnet;
   72: 
   73: use strict;
   74: use LWP::UserAgent();
   75: use HTTP::Date;
   76: use Image::Magick;
   77: 
   78: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
   79:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
   80:             %managerstab);
   81: 
   82: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
   83:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
   84:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
   85:     %courseownerbuf, %coursetypebuf,$locknum);
   86: 
   87: use IO::Socket;
   88: use GDBM_File;
   89: use HTML::LCParser;
   90: use Fcntl qw(:flock);
   91: use Storable qw(thaw nfreeze);
   92: use Time::HiRes qw( gettimeofday tv_interval );
   93: use Cache::Memcached;
   94: use Digest::MD5;
   95: use Math::Random;
   96: use File::MMagic;
   97: use LONCAPA qw(:DEFAULT :match);
   98: use LONCAPA::Configuration;
   99: use LONCAPA::lonmetadata;
  100: use LONCAPA::Lond;
  101: 
  102: use File::Copy;
  103: 
  104: my $readit;
  105: my $max_connection_retries = 10;     # Or some such value.
  106: 
  107: require Exporter;
  108: 
  109: our @ISA = qw (Exporter);
  110: our @EXPORT = qw(%env);
  111: 
  112: # ------------------------------------ Logging (parameters, docs, slots, roles)
  113: {
  114:     my $logid;
  115:     sub write_log {
  116: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
  117:         if ($context eq 'course') {
  118:             if (($cnum eq '') || ($cdom eq '')) {
  119:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  120:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  121:             }
  122:         }
  123: 	$logid ++;
  124:         my $now = time();
  125: 	my $id=$now.'00000'.$$.'00000'.$logid;
  126:         my $logentry = {
  127:                          $id => {
  128:                                   'exe_uname' => $env{'user.name'},
  129:                                   'exe_udom'  => $env{'user.domain'},
  130:                                   'exe_time'  => $now,
  131:                                   'exe_ip'    => $ENV{'REMOTE_ADDR'},
  132:                                   'delflag'   => $delflag,
  133:                                   'logentry'  => $storehash,
  134:                                   'uname'     => $uname,
  135:                                   'udom'      => $udom,
  136:                                 }
  137:                        };
  138:         return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
  139:     }
  140: }
  141: 
  142: sub logtouch {
  143:     my $execdir=$perlvar{'lonDaemons'};
  144:     unless (-e "$execdir/logs/lonnet.log") {	
  145: 	open(my $fh,">>$execdir/logs/lonnet.log");
  146: 	close $fh;
  147:     }
  148:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  149:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  150: }
  151: 
  152: sub logthis {
  153:     my $message=shift;
  154:     my $execdir=$perlvar{'lonDaemons'};
  155:     my $now=time;
  156:     my $local=localtime($now);
  157:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
  158: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
  159: 	print $fh $logstring;
  160: 	close($fh);
  161:     }
  162:     return 1;
  163: }
  164: 
  165: sub logperm {
  166:     my $message=shift;
  167:     my $execdir=$perlvar{'lonDaemons'};
  168:     my $now=time;
  169:     my $local=localtime($now);
  170:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
  171: 	print $fh "$now:$message:$local\n";
  172: 	close($fh);
  173:     }
  174:     return 1;
  175: }
  176: 
  177: sub create_connection {
  178:     my ($hostname,$lonid) = @_;
  179:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  180: 				     Type    => SOCK_STREAM,
  181: 				     Timeout => 10);
  182:     return 0 if (!$client);
  183:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
  184:     my $result = <$client>;
  185:     chomp($result);
  186:     return 1 if ($result eq 'done');
  187:     return 0;
  188: }
  189: 
  190: sub get_server_timezone {
  191:     my ($cnum,$cdom) = @_;
  192:     my $home=&homeserver($cnum,$cdom);
  193:     if ($home ne 'no_host') {
  194:         my $cachetime = 24*3600;
  195:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
  196:         if (defined($cached)) {
  197:             return $timezone;
  198:         } else {
  199:             my $timezone = &reply('servertimezone',$home);
  200:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
  201:         }
  202:     }
  203: }
  204: 
  205: sub get_server_distarch {
  206:     my ($lonhost,$ignore_cache) = @_;
  207:     if (defined($lonhost)) {
  208:         if (!defined(&hostname($lonhost))) {
  209:             return;
  210:         }
  211:         my $cachetime = 12*3600;
  212:         if (!$ignore_cache) {
  213:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
  214:             if (defined($cached)) {
  215:                 return $distarch;
  216:             }
  217:         }
  218:         my $rep = &reply('serverdistarch',$lonhost);
  219:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
  220:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
  221:                 $rep eq '') {
  222:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
  223:         }
  224:     }
  225:     return;
  226: }
  227: 
  228: sub get_server_loncaparev {
  229:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
  230:     if (defined($lonhost)) {
  231:         if (!defined(&hostname($lonhost))) {
  232:             undef($lonhost);
  233:         }
  234:     }
  235:     if (!defined($lonhost)) {
  236:         if (defined(&domain($dom,'primary'))) {
  237:             $lonhost=&domain($dom,'primary');
  238:             if ($lonhost eq 'no_host') {
  239:                 undef($lonhost);
  240:             }
  241:         }
  242:     }
  243:     if (defined($lonhost)) {
  244:         my $cachetime = 12*3600;
  245:         if (!$ignore_cache) {
  246:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
  247:             if (defined($cached)) {
  248:                 return $loncaparev;
  249:             }
  250:         }
  251:         my ($answer,$loncaparev);
  252:         my @ids=&current_machine_ids();
  253:         if (grep(/^\Q$lonhost\E$/,@ids)) {
  254:             $answer = $perlvar{'lonVersion'};
  255:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  256:                 $loncaparev = $1;
  257:             }
  258:         } else {
  259:             $answer = &reply('serverloncaparev',$lonhost);
  260:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
  261:                 if ($caller eq 'loncron') {
  262:                     my $ua=new LWP::UserAgent;
  263:                     $ua->timeout(4);
  264:                     my $protocol = $protocol{$lonhost};
  265:                     $protocol = 'http' if ($protocol ne 'https');
  266:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
  267:                     my $request=new HTTP::Request('GET',$url);
  268:                     my $response=$ua->request($request);
  269:                     unless ($response->is_error()) {
  270:                         my $content = $response->content;
  271:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
  272:                             $loncaparev = $1;
  273:                         }
  274:                     }
  275:                 } else {
  276:                     $loncaparev = $loncaparevs{$lonhost};
  277:                 }
  278:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  279:                 $loncaparev = $1;
  280:             }
  281:         }
  282:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
  283:     }
  284: }
  285: 
  286: sub get_server_homeID {
  287:     my ($hostname,$ignore_cache,$caller) = @_;
  288:     unless ($ignore_cache) {
  289:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
  290:         if (defined($cached)) {
  291:             return $serverhomeID;
  292:         }
  293:     }
  294:     my $cachetime = 12*3600;
  295:     my $serverhomeID;
  296:     if ($caller eq 'loncron') { 
  297:         my @machine_ids = &machine_ids($hostname);
  298:         foreach my $id (@machine_ids) {
  299:             my $response = &reply('serverhomeID',$id);
  300:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
  301:                 $serverhomeID = $response;
  302:                 last;
  303:             }
  304:         }
  305:         if ($serverhomeID eq '') {
  306:             $serverhomeID = $machine_ids[-1];
  307:         }
  308:     } else {
  309:         $serverhomeID = $serverhomeIDs{$hostname};
  310:     }
  311:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
  312: }
  313: 
  314: sub get_remote_globals {
  315:     my ($lonhost,$whathash,$ignore_cache) = @_;
  316:     my ($result,%returnhash,%whatneeded);
  317:     if (ref($whathash) eq 'HASH') {
  318:         foreach my $what (sort(keys(%{$whathash}))) {
  319:             my $hashid = $lonhost.'-'.$what;
  320:             my ($response,$cached);
  321:             unless ($ignore_cache) {
  322:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
  323:             }
  324:             if (defined($cached)) {
  325:                 $returnhash{$what} = $response;
  326:             } else {
  327:                 $whatneeded{$what} = 1;
  328:             }
  329:         }
  330:         if (keys(%whatneeded) == 0) {
  331:             $result = 'ok';
  332:         } else {
  333:             my $requested = &freeze_escape(\%whatneeded);
  334:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
  335:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  336:                 ($rep eq 'unknown_cmd')) {
  337:                 $result = $rep;
  338:             } else {
  339:                 $result = 'ok';
  340:                 my @pairs=split(/\&/,$rep);
  341:                 foreach my $item (@pairs) {
  342:                     my ($key,$value)=split(/=/,$item,2);
  343:                     my $what = &unescape($key);
  344:                     my $hashid = $lonhost.'-'.$what;
  345:                     $returnhash{$what}=&thaw_unescape($value);
  346:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
  347:                 }
  348:             }
  349:         }
  350:     }
  351:     return ($result,\%returnhash);
  352: }
  353: 
  354: sub remote_devalidate_cache {
  355:     my ($lonhost,$cachekeys) = @_;
  356:     my $items;
  357:     return unless (ref($cachekeys) eq 'ARRAY');
  358:     my $cachestr = join('&',@{$cachekeys});
  359:     return &reply('devalidatecache:'.&escape($cachestr),$lonhost);
  360: }
  361: 
  362: # -------------------------------------------------- Non-critical communication
  363: sub subreply {
  364:     my ($cmd,$server)=@_;
  365:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  366:     #
  367:     #  With loncnew process trimming, there's a timing hole between lonc server
  368:     #  process exit and the master server picking up the listen on the AF_UNIX
  369:     #  socket.  In that time interval, a lock file will exist:
  370: 
  371:     my $lockfile=$peerfile.".lock";
  372:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  373: 	sleep(1);
  374:     }
  375:     # At this point, either a loncnew parent is listening or an old lonc
  376:     # or loncnew child is listening so we can connect or everything's dead.
  377:     #
  378:     #   We'll give the connection a few tries before abandoning it.  If
  379:     #   connection is not possible, we'll con_lost back to the client.
  380:     #   
  381:     my $client;
  382:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  383: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  384: 				      Type    => SOCK_STREAM,
  385: 				      Timeout => 10);
  386: 	if ($client) {
  387: 	    last;		# Connected!
  388: 	} else {
  389: 	    &create_connection(&hostname($server),$server);
  390: 	}
  391:         sleep(1);		# Try again later if failed connection.
  392:     }
  393:     my $answer;
  394:     if ($client) {
  395: 	print $client "sethost:$server:$cmd\n";
  396: 	$answer=<$client>;
  397: 	if (!$answer) { $answer="con_lost"; }
  398: 	chomp($answer);
  399:     } else {
  400: 	$answer = 'con_lost';	# Failed connection.
  401:     }
  402:     return $answer;
  403: }
  404: 
  405: sub reply {
  406:     my ($cmd,$server)=@_;
  407:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  408:     my $answer=subreply($cmd,$server);
  409:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  410:        &logthis("<font color=\"blue\">WARNING:".
  411:                 " $cmd to $server returned $answer</font>");
  412:     }
  413:     return $answer;
  414: }
  415: 
  416: # ----------------------------------------------------------- Send USR1 to lonc
  417: 
  418: sub reconlonc {
  419:     my ($lonid) = @_;
  420:     my $hostname = &hostname($lonid);
  421:     if ($lonid) {
  422: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  423: 	if ($hostname && -e $peerfile) {
  424: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  425: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  426: 					     Type    => SOCK_STREAM,
  427: 					     Timeout => 10);
  428: 	    if ($client) {
  429: 		print $client ("reset_retries\n");
  430: 		my $answer=<$client>;
  431: 		#reset just this one.
  432: 	    }
  433: 	}
  434: 	return;
  435:     }
  436: 
  437:     &logthis("Trying to reconnect lonc");
  438:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  439:     if (open(my $fh,"<$loncfile")) {
  440: 	my $loncpid=<$fh>;
  441:         chomp($loncpid);
  442:         if (kill 0 => $loncpid) {
  443: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  444:             kill USR1 => $loncpid;
  445:             sleep 1;
  446:          } else {
  447: 	    &logthis(
  448:                "<font color=\"blue\">WARNING:".
  449:                " lonc at pid $loncpid not responding, giving up</font>");
  450:         }
  451:     } else {
  452: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  453:     }
  454: }
  455: 
  456: # ------------------------------------------------------ Critical communication
  457: 
  458: sub critical {
  459:     my ($cmd,$server)=@_;
  460:     unless (&hostname($server)) {
  461:         &logthis("<font color=\"blue\">WARNING:".
  462:                " Critical message to unknown server ($server)</font>");
  463:         return 'no_such_host';
  464:     }
  465:     my $answer=reply($cmd,$server);
  466:     if ($answer eq 'con_lost') {
  467: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
  468: 	my $answer=reply($cmd,$server);
  469:         if ($answer eq 'con_lost') {
  470:             my $now=time;
  471:             my $middlename=$cmd;
  472:             $middlename=substr($middlename,0,16);
  473:             $middlename=~s/\W//g;
  474:             my $dfilename=
  475:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  476:             $dumpcount++;
  477:             {
  478: 		my $dfh;
  479: 		if (open($dfh,">$dfilename")) {
  480: 		    print $dfh "$cmd\n"; 
  481: 		    close($dfh);
  482: 		}
  483:             }
  484:             sleep 2;
  485:             my $wcmd='';
  486:             {
  487: 		my $dfh;
  488: 		if (open($dfh,"<$dfilename")) {
  489: 		    $wcmd=<$dfh>; 
  490: 		    close($dfh);
  491: 		}
  492:             }
  493:             chomp($wcmd);
  494:             if ($wcmd eq $cmd) {
  495: 		&logthis("<font color=\"blue\">WARNING: ".
  496:                          "Connection buffer $dfilename: $cmd</font>");
  497:                 &logperm("D:$server:$cmd");
  498: 	        return 'con_delayed';
  499:             } else {
  500:                 &logthis("<font color=\"red\">CRITICAL:"
  501:                         ." Critical connection failed: $server $cmd</font>");
  502:                 &logperm("F:$server:$cmd");
  503:                 return 'con_failed';
  504:             }
  505:         }
  506:     }
  507:     return $answer;
  508: }
  509: 
  510: # ------------------------------------------- check if return value is an error
  511: 
  512: sub error {
  513:     my ($result) = @_;
  514:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  515: 	if ($2 == 2) { return undef; }
  516: 	return $1;
  517:     }
  518:     return undef;
  519: }
  520: 
  521: sub convert_and_load_session_env {
  522:     my ($lonidsdir,$handle)=@_;
  523:     my @profile;
  524:     {
  525: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  526: 	if (!$opened) {
  527: 	    return 0;
  528: 	}
  529: 	flock($idf,LOCK_SH);
  530: 	@profile=<$idf>;
  531: 	close($idf);
  532:     }
  533:     my %temp_env;
  534:     foreach my $line (@profile) {
  535: 	if ($line !~ m/=/) {
  536: 	    return 0;
  537: 	}
  538: 	chomp($line);
  539: 	my ($envname,$envvalue)=split(/=/,$line,2);
  540: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  541:     }
  542:     unlink("$lonidsdir/$handle.id");
  543:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  544: 	    0640)) {
  545: 	%disk_env = %temp_env;
  546: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  547: 	untie(%disk_env);
  548:     }
  549:     return 1;
  550: }
  551: 
  552: # ------------------------------------------- Transfer profile into environment
  553: my $env_loaded;
  554: sub transfer_profile_to_env {
  555:     my ($lonidsdir,$handle,$force_transfer) = @_;
  556:     if (!$force_transfer && $env_loaded) { return; } 
  557: 
  558:     if (!defined($lonidsdir)) {
  559: 	$lonidsdir = $perlvar{'lonIDsDir'};
  560:     }
  561:     if (!defined($handle)) {
  562:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  563:     }
  564: 
  565:     my $convert;
  566:     {
  567:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  568: 	if (!$opened) {
  569: 	    return;
  570: 	}
  571: 	flock($idf,LOCK_SH);
  572: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  573: 		&GDBM_READER(),0640)) {
  574: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  575: 	    untie(%disk_env);
  576: 	} else {
  577: 	    $convert = 1;
  578: 	}
  579:     }
  580:     if ($convert) {
  581: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  582: 	    &logthis("Failed to load session, or convert session.");
  583: 	}
  584:     }
  585: 
  586:     my %remove;
  587:     while ( my $envname = each(%env) ) {
  588:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  589:             if ($time < time-300) {
  590:                 $remove{$key}++;
  591:             }
  592:         }
  593:     }
  594: 
  595:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  596:     $env_loaded=1;
  597:     foreach my $expired_key (keys(%remove)) {
  598:         &delenv($expired_key);
  599:     }
  600: }
  601: 
  602: # ---------------------------------------------------- Check for valid session 
  603: sub check_for_valid_session {
  604:     my ($r,$name,$userhashref) = @_;
  605:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  606:     if ($name eq '') {
  607:         $name = 'lonID';
  608:     }
  609:     my $lonid=$cookies{$name};
  610:     return undef if (!$lonid);
  611: 
  612:     my $handle=&LONCAPA::clean_handle($lonid->value);
  613:     my $lonidsdir;
  614:     if ($name eq 'lonDAV') {
  615:         $lonidsdir=$r->dir_config('lonDAVsessDir');
  616:     } else {
  617:         $lonidsdir=$r->dir_config('lonIDsDir');
  618:     }
  619:     return undef if (!-e "$lonidsdir/$handle.id");
  620: 
  621:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  622:     return undef if (!$opened);
  623: 
  624:     flock($idf,LOCK_SH);
  625:     my %disk_env;
  626:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  627: 	    &GDBM_READER(),0640)) {
  628: 	return undef;	
  629:     }
  630: 
  631:     if (!defined($disk_env{'user.name'})
  632: 	|| !defined($disk_env{'user.domain'})) {
  633: 	return undef;
  634:     }
  635: 
  636:     if (ref($userhashref) eq 'HASH') {
  637:         $userhashref->{'name'} = $disk_env{'user.name'};
  638:         $userhashref->{'domain'} = $disk_env{'user.domain'};
  639:     }
  640: 
  641:     return $handle;
  642: }
  643: 
  644: sub timed_flock {
  645:     my ($file,$lock_type) = @_;
  646:     my $failed=0;
  647:     eval {
  648: 	local $SIG{__DIE__}='DEFAULT';
  649: 	local $SIG{ALRM}=sub {
  650: 	    $failed=1;
  651: 	    die("failed lock");
  652: 	};
  653: 	alarm(13);
  654: 	flock($file,$lock_type);
  655: 	alarm(0);
  656:     };
  657:     if ($failed) {
  658: 	return undef;
  659:     } else {
  660: 	return 1;
  661:     }
  662: }
  663: 
  664: # ---------------------------------------------------------- Append Environment
  665: 
  666: sub appenv {
  667:     my ($newenv,$roles) = @_;
  668:     if (ref($newenv) eq 'HASH') {
  669:         foreach my $key (keys(%{$newenv})) {
  670:             my $refused = 0;
  671: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  672:                 $refused = 1;
  673:                 if (ref($roles) eq 'ARRAY') {
  674:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
  675:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  676:                         $refused = 0;
  677:                     }
  678:                 }
  679:             }
  680:             if ($refused) {
  681:                 &logthis("<font color=\"blue\">WARNING: ".
  682:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  683:                          .'</font>');
  684: 	        delete($newenv->{$key});
  685:             } else {
  686:                 $env{$key}=$newenv->{$key};
  687:             }
  688:         }
  689:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
  690:         if ($opened
  691: 	    && &timed_flock($env_file,LOCK_EX)
  692: 	    &&
  693: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  694: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  695: 	    while (my ($key,$value) = each(%{$newenv})) {
  696: 	        $disk_env{$key} = $value;
  697: 	    }
  698: 	    untie(%disk_env);
  699:         }
  700:     }
  701:     return 'ok';
  702: }
  703: # ----------------------------------------------------- Delete from Environment
  704: 
  705: sub delenv {
  706:     my ($delthis,$regexp,$roles) = @_;
  707:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
  708:         my $refused = 1;
  709:         if (ref($roles) eq 'ARRAY') {
  710:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
  711:             if (grep(/^\Q$role\E$/,@{$roles})) {
  712:                 $refused = 0;
  713:             }
  714:         }
  715:         if ($refused) {
  716:             &logthis("<font color=\"blue\">WARNING: ".
  717:                      "Attempt to delete from environment ".$delthis);
  718:             return 'error';
  719:         }
  720:     }
  721:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  722:     if ($opened
  723: 	&& &timed_flock($env_file,LOCK_EX)
  724: 	&&
  725: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  726: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  727: 	foreach my $key (keys(%disk_env)) {
  728: 	    if ($regexp) {
  729:                 if ($key=~/^$delthis/) {
  730:                     delete($env{$key});
  731:                     delete($disk_env{$key});
  732:                 } 
  733:             } else {
  734:                 if ($key=~/^\Q$delthis\E/) {
  735: 		    delete($env{$key});
  736: 		    delete($disk_env{$key});
  737: 	        }
  738:             }
  739: 	}
  740: 	untie(%disk_env);
  741:     }
  742:     return 'ok';
  743: }
  744: 
  745: sub get_env_multiple {
  746:     my ($name) = @_;
  747:     my @values;
  748:     if (defined($env{$name})) {
  749:         # exists is it an array
  750:         if (ref($env{$name})) {
  751:             @values=@{ $env{$name} };
  752:         } else {
  753:             $values[0]=$env{$name};
  754:         }
  755:     }
  756:     return(@values);
  757: }
  758: 
  759: # ------------------------------------------------------------------- Locking
  760: 
  761: sub set_lock {
  762:     my ($text)=@_;
  763:     $locknum++;
  764:     my $id=$$.'-'.$locknum;
  765:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  766:              'session.lock.'.$id => $text});
  767:     return $id;
  768: }
  769: 
  770: sub get_locks {
  771:     my $num=0;
  772:     my %texts=();
  773:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  774:        if ($lock=~/\w/) {
  775:           $num++;
  776:           $texts{$lock}=$env{'session.lock.'.$lock};
  777:        }
  778:    }
  779:    return ($num,%texts);
  780: }
  781: 
  782: sub remove_lock {
  783:     my ($id)=@_;
  784:     my $newlocks='';
  785:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  786:        if (($lock=~/\w/) && ($lock ne $id)) {
  787:           $newlocks.=','.$lock;
  788:        }
  789:     }
  790:     &appenv({'session.locks' => $newlocks});
  791:     &delenv('session.lock.'.$id);
  792: }
  793: 
  794: sub remove_all_locks {
  795:     my $activelocks=$env{'session.locks'};
  796:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  797:        if ($lock=~/\w/) {
  798:           &remove_lock($lock);
  799:        }
  800:     }
  801: }
  802: 
  803: 
  804: # ------------------------------------------ Find out current server userload
  805: sub userload {
  806:     my $numusers=0;
  807:     {
  808: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  809: 	my $filename;
  810: 	my $curtime=time;
  811: 	while ($filename=readdir(LONIDS)) {
  812: 	    next if ($filename eq '.' || $filename eq '..');
  813: 	    next if ($filename =~ /publicuser_\d+\.id/);
  814: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  815: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  816: 	}
  817: 	closedir(LONIDS);
  818:     }
  819:     my $userloadpercent=0;
  820:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  821:     if ($maxuserload) {
  822: 	$userloadpercent=100*$numusers/$maxuserload;
  823:     }
  824:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  825:     return $userloadpercent;
  826: }
  827: 
  828: # ------------------------------ Find server with least workload from spare.tab
  829: 
  830: sub spareserver {
  831:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
  832:     my $spare_server;
  833:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  834:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  835:                                                      :  $userloadpercent;
  836:     my ($uint_dom,$remotesessions);
  837:     if (($udom ne '') && (&domain($udom) ne '')) {
  838:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
  839:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
  840:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
  841:         $remotesessions = $udomdefaults{'remotesessions'};
  842:     }
  843:     my $spareshash = &this_host_spares($udom);
  844:     if (ref($spareshash) eq 'HASH') {
  845:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  846:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  847:                 if ($uint_dom) {
  848:                     next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
  849:                                                  $try_server));
  850:                 }
  851: 	        ($spare_server, $lowest_load) =
  852: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
  853:             }
  854:         }
  855: 
  856:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
  857: 
  858:         if (!$found_server) {
  859:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
  860: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
  861:                     if ($uint_dom) {
  862:                         next unless (&spare_can_host($udom,$uint_dom,
  863:                                                      $remotesessions,$try_server));
  864:                     }
  865: 	            ($spare_server, $lowest_load) =
  866: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
  867:                 }
  868: 	    }
  869:         }
  870:     }
  871: 
  872:     if (!$want_server_name) {
  873:         my $protocol = 'http';
  874:         if ($protocol{$spare_server} eq 'https') {
  875:             $protocol = $protocol{$spare_server};
  876:         }
  877:         if (defined($spare_server)) {
  878:             my $hostname = &hostname($spare_server);
  879:             if (defined($hostname)) {
  880: 	        $spare_server = $protocol.'://'.$hostname;
  881:             }
  882:         }
  883:     }
  884:     return $spare_server;
  885: }
  886: 
  887: sub compare_server_load {
  888:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
  889: 
  890:     if ($required) {
  891:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
  892:         my $remoterev = &get_server_loncaparev(undef,$try_server);
  893:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
  894:         if (($major eq '' && $minor eq '') ||
  895:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
  896:             return ($spare_server,$lowest_load);
  897:         }
  898:     }
  899: 
  900:     my $loadans     = &reply('load',    $try_server);
  901:     my $userloadans = &reply('userload',$try_server);
  902: 
  903:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  904: 	return ($spare_server, $lowest_load); #didn't get a number from the server
  905:     }
  906: 
  907:     my $load;
  908:     if ($loadans =~ /\d/) {
  909: 	if ($userloadans =~ /\d/) {
  910: 	    #both are numbers, pick the bigger one
  911: 	    $load = ($loadans > $userloadans) ? $loadans 
  912: 		                              : $userloadans;
  913: 	} else {
  914: 	    $load = $loadans;
  915: 	}
  916:     } else {
  917: 	$load = $userloadans;
  918:     }
  919: 
  920:     if (($load =~ /\d/) && ($load < $lowest_load)) {
  921: 	$spare_server = $try_server;
  922: 	$lowest_load  = $load;
  923:     }
  924:     return ($spare_server,$lowest_load);
  925: }
  926: 
  927: # --------------------------- ask offload servers if user already has a session
  928: sub find_existing_session {
  929:     my ($udom,$uname) = @_;
  930:     my $spareshash = &this_host_spares($udom);
  931:     if (ref($spareshash) eq 'HASH') {
  932:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  933:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  934:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
  935:             }
  936:         }
  937:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
  938:             foreach my $try_server (@{ $spareshash->{'default'} }) {
  939:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
  940:             }
  941:         }
  942:     }
  943:     return;
  944: }
  945: 
  946: # -------------------------------- ask if server already has a session for user
  947: sub has_user_session {
  948:     my ($lonid,$udom,$uname) = @_;
  949:     my $result = &reply(join(':','userhassession',
  950: 			     map {&escape($_)} ($udom,$uname)),$lonid);
  951:     return 1 if ($result eq 'ok');
  952: 
  953:     return 0;
  954: }
  955: 
  956: # --------- determine least loaded server in a user's domain which allows login
  957: 
  958: sub choose_server {
  959:     my ($udom,$checkloginvia,$required) = @_;
  960:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
  961:     my %servers = &get_servers($udom);
  962:     my $lowest_load = 30000;
  963:     my ($login_host,$hostname,$portal_path,$isredirect);
  964:     foreach my $lonhost (keys(%servers)) {
  965:         my $loginvia;
  966:         if ($checkloginvia) {
  967:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
  968:             if ($loginvia) {
  969:                 my ($server,$path) = split(/:/,$loginvia);
  970:                 ($login_host, $lowest_load) =
  971:                     &compare_server_load($server, $login_host, $lowest_load, $required);
  972:                 if ($login_host eq $server) {
  973:                     $portal_path = $path;
  974:                     $isredirect = 1;
  975:                 }
  976:             } else {
  977:                 ($login_host, $lowest_load) =
  978:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
  979:                 if ($login_host eq $lonhost) {
  980:                     $portal_path = '';
  981:                     $isredirect = ''; 
  982:                 }
  983:             }
  984:         } else {
  985:             ($login_host, $lowest_load) =
  986:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
  987:         }
  988:     }
  989:     if ($login_host ne '') {
  990:         $hostname = &hostname($login_host);
  991:     }
  992:     return ($login_host,$hostname,$portal_path,$isredirect);
  993: }
  994: 
  995: # --------------------------------------------- Try to change a user's password
  996: 
  997: sub changepass {
  998:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
  999:     $currentpass = &escape($currentpass);
 1000:     $newpass     = &escape($newpass);
 1001:     my $lonhost = $perlvar{'lonHostID'};
 1002:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
 1003: 		       $server);
 1004:     if (! $answer) {
 1005: 	&logthis("No reply on password change request to $server ".
 1006: 		 "by $uname in domain $udom.");
 1007:     } elsif ($answer =~ "^ok") {
 1008:         &logthis("$uname in $udom successfully changed their password ".
 1009: 		 "on $server.");
 1010:     } elsif ($answer =~ "^pwchange_failure") {
 1011: 	&logthis("$uname in $udom was unable to change their password ".
 1012: 		 "on $server.  The action was blocked by either lcpasswd ".
 1013: 		 "or pwchange");
 1014:     } elsif ($answer =~ "^non_authorized") {
 1015:         &logthis("$uname in $udom did not get their password correct when ".
 1016: 		 "attempting to change it on $server.");
 1017:     } elsif ($answer =~ "^auth_mode_error") {
 1018:         &logthis("$uname in $udom attempted to change their password despite ".
 1019: 		 "not being locally or internally authenticated on $server.");
 1020:     } elsif ($answer =~ "^unknown_user") {
 1021:         &logthis("$uname in $udom attempted to change their password ".
 1022: 		 "on $server but were unable to because $server is not ".
 1023: 		 "their home server.");
 1024:     } elsif ($answer =~ "^refused") {
 1025: 	&logthis("$server refused to change $uname in $udom password because ".
 1026: 		 "it was sent an unencrypted request to change the password.");
 1027:     } elsif ($answer =~ "invalid_client") {
 1028:         &logthis("$server refused to change $uname in $udom password because ".
 1029:                  "it was a reset by e-mail originating from an invalid server.");
 1030:     }
 1031:     return $answer;
 1032: }
 1033: 
 1034: # ----------------------- Try to determine user's current authentication scheme
 1035: 
 1036: sub queryauthenticate {
 1037:     my ($uname,$udom)=@_;
 1038:     my $uhome=&homeserver($uname,$udom);
 1039:     if (!$uhome) {
 1040: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
 1041: 	return 'no_host';
 1042:     }
 1043:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
 1044:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
 1045: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1046:     }
 1047:     return $answer;
 1048: }
 1049: 
 1050: # --------- Try to authenticate user from domain's lib servers (first this one)
 1051: 
 1052: sub authenticate {
 1053:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
 1054:     $upass=&escape($upass);
 1055:     $uname= &LONCAPA::clean_username($uname);
 1056:     my $uhome=&homeserver($uname,$udom,1);
 1057:     my $newhome;
 1058:     if ((!$uhome) || ($uhome eq 'no_host')) {
 1059: # Maybe the machine was offline and only re-appeared again recently?
 1060:         &reconlonc();
 1061: # One more
 1062: 	$uhome=&homeserver($uname,$udom,1);
 1063:         if (($uhome eq 'no_host') && $checkdefauth) {
 1064:             if (defined(&domain($udom,'primary'))) {
 1065:                 $newhome=&domain($udom,'primary');
 1066:             }
 1067:             if ($newhome ne '') {
 1068:                 $uhome = $newhome;
 1069:             }
 1070:         }
 1071: 	if ((!$uhome) || ($uhome eq 'no_host')) {
 1072: 	    &logthis("User $uname at $udom is unknown in authenticate");
 1073: 	    return 'no_host';
 1074:         }
 1075:     }
 1076:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
 1077:     if ($answer eq 'authorized') {
 1078:         if ($newhome) {
 1079:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
 1080:             return 'no_account_on_host'; 
 1081:         } else {
 1082:             &logthis("User $uname at $udom authorized by $uhome");
 1083:             return $uhome;
 1084:         }
 1085:     }
 1086:     if ($answer eq 'non_authorized') {
 1087: 	&logthis("User $uname at $udom rejected by $uhome");
 1088: 	return 'no_host'; 
 1089:     }
 1090:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1091:     return 'no_host';
 1092: }
 1093: 
 1094: sub can_host_session {
 1095:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
 1096:     my $canhost = 1;
 1097:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
 1098:     if (ref($remotesessions) eq 'HASH') {
 1099:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
 1100:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
 1101:                 $canhost = 0;
 1102:             } else {
 1103:                 $canhost = 1;
 1104:             }
 1105:         }
 1106:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
 1107:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
 1108:                 $canhost = 1;
 1109:             } else {
 1110:                 $canhost = 0;
 1111:             }
 1112:         }
 1113:         if ($canhost) {
 1114:             if ($remotesessions->{'version'} ne '') {
 1115:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
 1116:                 if ($reqmajor ne '' && $reqminor ne '') {
 1117:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
 1118:                         my $major = $1;
 1119:                         my $minor = $2;
 1120:                         if (($major < $reqmajor ) ||
 1121:                             (($major == $reqmajor) && ($minor < $reqminor))) {
 1122:                             $canhost = 0;
 1123:                         }
 1124:                     } else {
 1125:                         $canhost = 0;
 1126:                     }
 1127:                 }
 1128:             }
 1129:         }
 1130:     }
 1131:     if ($canhost) {
 1132:         if (ref($hostedsessions) eq 'HASH') {
 1133:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1134:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 1135:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
 1136:                 if (($uint_dom ne '') && 
 1137:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
 1138:                     $canhost = 0;
 1139:                 } else {
 1140:                     $canhost = 1;
 1141:                 }
 1142:             }
 1143:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
 1144:                 if (($uint_dom ne '') && 
 1145:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
 1146:                     $canhost = 1;
 1147:                 } else {
 1148:                     $canhost = 0;
 1149:                 }
 1150:             }
 1151:         }
 1152:     }
 1153:     return $canhost;
 1154: }
 1155: 
 1156: sub spare_can_host {
 1157:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
 1158:     my $canhost=1;
 1159:     my @intdoms;
 1160:     my $internet_names = &Apache::lonnet::get_internet_names($try_server);
 1161:     if (ref($internet_names) eq 'ARRAY') {
 1162:         @intdoms = @{$internet_names};
 1163:     }
 1164:     unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1165:         my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
 1166:         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
 1167:         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
 1168:         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
 1169:         $canhost = &can_host_session($udom,$try_server,$remoterev,
 1170:                                      $remotesessions,
 1171:                                      $defdomdefaults{'hostedsessions'});
 1172:     }
 1173:     return $canhost;
 1174: }
 1175: 
 1176: sub this_host_spares {
 1177:     my ($dom) = @_;
 1178:     my ($dom_in_use,$lonhost_in_use,$result);
 1179:     my @hosts = &current_machine_ids();
 1180:     foreach my $lonhost (@hosts) {
 1181:         if (&host_domain($lonhost) eq $dom) {
 1182:             $dom_in_use = $dom;
 1183:             $lonhost_in_use = $lonhost;
 1184:             last;
 1185:         }
 1186:     }
 1187:     if ($dom_in_use ne '') {
 1188:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1189:     }
 1190:     if (ref($result) ne 'HASH') {
 1191:         $lonhost_in_use = $perlvar{'lonHostID'};
 1192:         $dom_in_use = &host_domain($lonhost_in_use);
 1193:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1194:         if (ref($result) ne 'HASH') {
 1195:             $result = \%spareid;
 1196:         }
 1197:     }
 1198:     return $result;
 1199: }
 1200: 
 1201: sub spares_for_offload  {
 1202:     my ($dom_in_use,$lonhost_in_use) = @_;
 1203:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
 1204:     if (defined($cached)) {
 1205:         return $result;
 1206:     } else {
 1207:         my $cachetime = 60*60*24;
 1208:         my %domconfig =
 1209:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
 1210:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1211:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
 1212:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
 1213:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
 1214:                 }
 1215:             }
 1216:         }
 1217:     }
 1218:     return;
 1219: }
 1220: 
 1221: sub get_lonbalancer_config {
 1222:     my ($servers) = @_;
 1223:     my ($currbalancer,$currtargets);
 1224:     if (ref($servers) eq 'HASH') {
 1225:         foreach my $server (keys(%{$servers})) {
 1226:             my %what = (
 1227:                          spareid => 1,
 1228:                          perlvar => 1,
 1229:                        );
 1230:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
 1231:             if ($result eq 'ok') {
 1232:                 if (ref($returnhash) eq 'HASH') {
 1233:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
 1234:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
 1235:                             $currbalancer = $server;
 1236:                             $currtargets = {};
 1237:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
 1238:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
 1239:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
 1240:                                 }
 1241:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
 1242:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
 1243:                                 }
 1244:                             }
 1245:                             last;
 1246:                         }
 1247:                     }
 1248:                 }
 1249:             }
 1250:         }
 1251:     }
 1252:     return ($currbalancer,$currtargets);
 1253: }
 1254: 
 1255: sub check_loadbalancing {
 1256:     my ($uname,$udom) = @_;
 1257:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
 1258:         $rule_in_effect,$offloadto,$otherserver);
 1259:     my $lonhost = $perlvar{'lonHostID'};
 1260:     my @hosts = &current_machine_ids();
 1261:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1262:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
 1263:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
 1264:     my $serverhomedom = &host_domain($lonhost);
 1265: 
 1266:     my $cachetime = 60*60*24;
 1267: 
 1268:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1269:         $dom_in_use = $udom;
 1270:         $homeintdom = 1;
 1271:     } else {
 1272:         $dom_in_use = $serverhomedom;
 1273:     }
 1274:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
 1275:     unless (defined($cached)) {
 1276:         my %domconfig =
 1277:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
 1278:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1279:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1280:         }
 1281:     }
 1282:     if (ref($result) eq 'HASH') {
 1283:         ($is_balancer,$currtargets,$currrules) =
 1284:             &check_balancer_result($result,@hosts);
 1285:         if ($is_balancer) {
 1286:             if (ref($currrules) eq 'HASH') {
 1287:                 if ($homeintdom) {
 1288:                     if ($uname ne '') {
 1289:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
 1290:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
 1291:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
 1292:                                 $rule_in_effect = $currrules->{'_LC_author'};
 1293:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
 1294:                                 $rule_in_effect = $currrules->{'_LC_adv'}
 1295:                             }
 1296:                         }
 1297:                         if ($rule_in_effect eq '') {
 1298:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
 1299:                             if ($userenv{'inststatus'} ne '') {
 1300:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
 1301:                                 my ($othertitle,$usertypes,$types) =
 1302:                                     &Apache::loncommon::sorted_inst_types($udom);
 1303:                                 if (ref($types) eq 'ARRAY') {
 1304:                                     foreach my $type (@{$types}) {
 1305:                                         if (grep(/^\Q$type\E$/,@statuses)) {
 1306:                                             if (exists($currrules->{$type})) {
 1307:                                                 $rule_in_effect = $currrules->{$type};
 1308:                                             }
 1309:                                         }
 1310:                                     }
 1311:                                 }
 1312:                             } else {
 1313:                                 if (exists($currrules->{'default'})) {
 1314:                                     $rule_in_effect = $currrules->{'default'};
 1315:                                 }
 1316:                             }
 1317:                         }
 1318:                     } else {
 1319:                         if (exists($currrules->{'default'})) {
 1320:                             $rule_in_effect = $currrules->{'default'};
 1321:                         }
 1322:                     }
 1323:                 } else {
 1324:                     if ($currrules->{'_LC_external'} ne '') {
 1325:                         $rule_in_effect = $currrules->{'_LC_external'};
 1326:                     }
 1327:                 }
 1328:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1329:                                                        $uname,$udom);
 1330:             }
 1331:         }
 1332:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
 1333:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
 1334:         unless (defined($cached)) {
 1335:             my %domconfig =
 1336:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
 1337:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1338:                 $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1339:             }
 1340:         }
 1341:         if (ref($result) eq 'HASH') {
 1342:             ($is_balancer,$currtargets,$currrules) =
 1343:                 &check_balancer_result($result,@hosts);
 1344:             if ($is_balancer) {
 1345:                 if (ref($currrules) eq 'HASH') {
 1346:                     if ($currrules->{'_LC_internetdom'} ne '') {
 1347:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
 1348:                     }
 1349:                 }
 1350:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1351:                                                        $uname,$udom);
 1352:             }
 1353:         } else {
 1354:             if ($perlvar{'lonBalancer'} eq 'yes') {
 1355:                 $is_balancer = 1;
 1356:                 $offloadto = &this_host_spares($dom_in_use);
 1357:             }
 1358:         }
 1359:     } else {
 1360:         if ($perlvar{'lonBalancer'} eq 'yes') {
 1361:             $is_balancer = 1;
 1362:             $offloadto = &this_host_spares($dom_in_use);
 1363:         }
 1364:     }
 1365:     if ($is_balancer) {
 1366:         my $lowest_load = 30000;
 1367:         if (ref($offloadto) eq 'HASH') {
 1368:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
 1369:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
 1370:                     ($otherserver,$lowest_load) =
 1371:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1372:                 }
 1373:             }
 1374:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
 1375: 
 1376:             if (!$found_server) {
 1377:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
 1378:                     foreach my $try_server (@{$offloadto->{'default'}}) {
 1379:                         ($otherserver,$lowest_load) =
 1380:                             &compare_server_load($try_server,$otherserver,$lowest_load);
 1381:                     }
 1382:                 }
 1383:             }
 1384:         } elsif (ref($offloadto) eq 'ARRAY') {
 1385:             if (@{$offloadto} == 1) {
 1386:                 $otherserver = $offloadto->[0];
 1387:             } elsif (@{$offloadto} > 1) {
 1388:                 foreach my $try_server (@{$offloadto}) {
 1389:                     ($otherserver,$lowest_load) =
 1390:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1391:                 }
 1392:             }
 1393:         }
 1394:         if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
 1395:             $is_balancer = 0;
 1396:             if ($uname ne '' && $udom ne '') {
 1397:                 if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
 1398: 
 1399:                     &appenv({'user.loadbalexempt'     => $lonhost,
 1400:                              'user.loadbalcheck.time' => time});
 1401:                 }
 1402:             }
 1403:         }
 1404:     }
 1405:     return ($is_balancer,$otherserver);
 1406: }
 1407: 
 1408: sub check_balancer_result {
 1409:     my ($result,@hosts) = @_;
 1410:     my ($is_balancer,$currtargets,$currrules);
 1411:     if (ref($result) eq 'HASH') {
 1412:         if ($result->{'lonhost'} ne '') {
 1413:             my $currbalancer = $result->{'lonhost'};
 1414:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
 1415:                 $is_balancer = 1;
 1416:                 $currtargets = $result->{'targets'};
 1417:                 $currrules = $result->{'rules'};
 1418:             }
 1419:         } else {
 1420:             foreach my $key (keys(%{$result})) {
 1421:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
 1422:                     (ref($result->{$key}) eq 'HASH')) {
 1423:                     $is_balancer = 1;
 1424:                     $currrules = $result->{$key}{'rules'};
 1425:                     $currtargets = $result->{$key}{'targets'};
 1426:                     last;
 1427:                 }
 1428:             }
 1429:         }
 1430:     }
 1431:     return ($is_balancer,$currtargets,$currrules);
 1432: }
 1433: 
 1434: sub get_loadbalancer_targets {
 1435:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
 1436:     my $offloadto;
 1437:     if ($rule_in_effect eq 'none') {
 1438:         return [$perlvar{'lonHostID'}];
 1439:     } elsif ($rule_in_effect eq '') {
 1440:         $offloadto = $currtargets;
 1441:     } else {
 1442:         if ($rule_in_effect eq 'homeserver') {
 1443:             my $homeserver = &homeserver($uname,$udom);
 1444:             if ($homeserver ne 'no_host') {
 1445:                 $offloadto = [$homeserver];
 1446:             }
 1447:         } elsif ($rule_in_effect eq 'externalbalancer') {
 1448:             my %domconfig =
 1449:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1450:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1451:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
 1452:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
 1453:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
 1454:                     }
 1455:                 }
 1456:             } else {
 1457:                 my %servers = &internet_dom_servers($udom);
 1458:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
 1459:                 if (&hostname($remotebalancer) ne '') {
 1460:                     $offloadto = [$remotebalancer];
 1461:                 }
 1462:             }
 1463:         } elsif (&hostname($rule_in_effect) ne '') {
 1464:             $offloadto = [$rule_in_effect];
 1465:         }
 1466:     }
 1467:     return $offloadto;
 1468: }
 1469: 
 1470: sub internet_dom_servers {
 1471:     my ($dom) = @_;
 1472:     my (%uniqservers,%servers);
 1473:     my $primaryserver = &hostname(&domain($dom,'primary'));
 1474:     my @machinedoms = &machine_domains($primaryserver);
 1475:     foreach my $mdom (@machinedoms) {
 1476:         my %currservers = %servers;
 1477:         my %server = &get_servers($mdom);
 1478:         %servers = (%currservers,%server);
 1479:     }
 1480:     my %by_hostname;
 1481:     foreach my $id (keys(%servers)) {
 1482:         push(@{$by_hostname{$servers{$id}}},$id);
 1483:     }
 1484:     foreach my $hostname (sort(keys(%by_hostname))) {
 1485:         if (@{$by_hostname{$hostname}} > 1) {
 1486:             my $match = 0;
 1487:             foreach my $id (@{$by_hostname{$hostname}}) {
 1488:                 if (&host_domain($id) eq $dom) {
 1489:                     $uniqservers{$id} = $hostname;
 1490:                     $match = 1;
 1491:                 }
 1492:             }
 1493:             unless ($match) {
 1494:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1495:             }
 1496:         } else {
 1497:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1498:         }
 1499:     }
 1500:     return %uniqservers;
 1501: }
 1502: 
 1503: # ---------------------- Find the homebase for a user from domain's lib servers
 1504: 
 1505: my %homecache;
 1506: sub homeserver {
 1507:     my ($uname,$udom,$ignoreBadCache)=@_;
 1508:     my $index="$uname:$udom";
 1509: 
 1510:     if (exists($homecache{$index})) { return $homecache{$index}; }
 1511: 
 1512:     my %servers = &get_servers($udom,'library');
 1513:     foreach my $tryserver (keys(%servers)) {
 1514:         next if ($ignoreBadCache ne 'true' && 
 1515: 		 exists($badServerCache{$tryserver}));
 1516: 
 1517: 	my $answer=reply("home:$udom:$uname",$tryserver);
 1518: 	if ($answer eq 'found') {
 1519: 	    delete($badServerCache{$tryserver}); 
 1520: 	    return $homecache{$index}=$tryserver;
 1521: 	} elsif ($answer eq 'no_host') {
 1522: 	    $badServerCache{$tryserver}=1;
 1523: 	}
 1524:     }    
 1525:     return 'no_host';
 1526: }
 1527: 
 1528: # ------------------------------------- Find the usernames behind a list of IDs
 1529: 
 1530: sub idget {
 1531:     my ($udom,@ids)=@_;
 1532:     my %returnhash=();
 1533:     
 1534:     my %servers = &get_servers($udom,'library');
 1535:     foreach my $tryserver (keys(%servers)) {
 1536: 	my $idlist=join('&',@ids);
 1537: 	$idlist=~tr/A-Z/a-z/; 
 1538: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
 1539: 	my @answer=();
 1540: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
 1541: 	    @answer=split(/\&/,$reply);
 1542: 	}                    ;
 1543: 	my $i;
 1544: 	for ($i=0;$i<=$#ids;$i++) {
 1545: 	    if ($answer[$i]) {
 1546: 		$returnhash{$ids[$i]}=$answer[$i];
 1547: 	    } 
 1548: 	}
 1549:     } 
 1550:     return %returnhash;
 1551: }
 1552: 
 1553: # ------------------------------------- Find the IDs behind a list of usernames
 1554: 
 1555: sub idrget {
 1556:     my ($udom,@unames)=@_;
 1557:     my %returnhash=();
 1558:     foreach my $uname (@unames) {
 1559:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
 1560:     }
 1561:     return %returnhash;
 1562: }
 1563: 
 1564: # ------------------------------- Store away a list of names and associated IDs
 1565: 
 1566: sub idput {
 1567:     my ($udom,%ids)=@_;
 1568:     my %servers=();
 1569:     foreach my $uname (keys(%ids)) {
 1570: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
 1571:         my $uhom=&homeserver($uname,$udom);
 1572:         if ($uhom ne 'no_host') {
 1573:             my $id=&escape($ids{$uname});
 1574:             $id=~tr/A-Z/a-z/;
 1575:             my $esc_unam=&escape($uname);
 1576: 	    if ($servers{$uhom}) {
 1577: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
 1578:             } else {
 1579:                 $servers{$uhom}=$id.'='.$esc_unam;
 1580:             }
 1581:         }
 1582:     }
 1583:     foreach my $server (keys(%servers)) {
 1584:         &critical('idput:'.$udom.':'.$servers{$server},$server);
 1585:     }
 1586: }
 1587: 
 1588: # ---------------------------------------- Delete unwanted IDs from ids.db file
 1589: 
 1590: sub iddel {
 1591:     my ($udom,$idshashref,$uhome)=@_;
 1592:     my %result=();
 1593:     unless (ref($idshashref) eq 'HASH') {
 1594:         return %result;
 1595:     }
 1596:     my %servers=();
 1597:     while (my ($id,$uname) = each(%{$idshashref})) {
 1598:         my $uhom;
 1599:         if ($uhome) {
 1600:             $uhom = $uhome;
 1601:         } else {
 1602:             $uhom=&homeserver($uname,$udom);
 1603:         }
 1604:         if ($uhom ne 'no_host') {
 1605:             if ($servers{$uhom}) {
 1606:                 $servers{$uhom}.='&'.&escape($id);
 1607:             } else {
 1608:                 $servers{$uhom}=&escape($id);
 1609:             }
 1610:         }
 1611:     }
 1612:     foreach my $server (keys(%servers)) {
 1613:         $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
 1614:     }
 1615:     return %result;
 1616: }
 1617: 
 1618: # ------------------------------dump from db file owned by domainconfig user
 1619: sub dump_dom {
 1620:     my ($namespace, $udom, $regexp) = @_;
 1621: 
 1622:     $udom ||= $env{'user.domain'};
 1623: 
 1624:     return () unless $udom;
 1625: 
 1626:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
 1627: }
 1628: 
 1629: # ------------------------------------------ get items from domain db files   
 1630: 
 1631: sub get_dom {
 1632:     my ($namespace,$storearr,$udom,$uhome)=@_;
 1633:     my $items='';
 1634:     foreach my $item (@$storearr) {
 1635:         $items.=&escape($item).'&';
 1636:     }
 1637:     $items=~s/\&$//;
 1638:     if (!$udom) {
 1639:         $udom=$env{'user.domain'};
 1640:         if (defined(&domain($udom,'primary'))) {
 1641:             $uhome=&domain($udom,'primary');
 1642:         } else {
 1643:             undef($uhome);
 1644:         }
 1645:     } else {
 1646:         if (!$uhome) {
 1647:             if (defined(&domain($udom,'primary'))) {
 1648:                 $uhome=&domain($udom,'primary');
 1649:             }
 1650:         }
 1651:     }
 1652:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1653:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 1654:         my %returnhash;
 1655:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 1656:             return %returnhash;
 1657:         }
 1658:         my @pairs=split(/\&/,$rep);
 1659:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 1660:             return @pairs;
 1661:         }
 1662:         my $i=0;
 1663:         foreach my $item (@$storearr) {
 1664:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 1665:             $i++;
 1666:         }
 1667:         return %returnhash;
 1668:     } else {
 1669:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 1670:     }
 1671: }
 1672: 
 1673: # -------------------------------------------- put items in domain db files 
 1674: 
 1675: sub put_dom {
 1676:     my ($namespace,$storehash,$udom,$uhome)=@_;
 1677:     if (!$udom) {
 1678:         $udom=$env{'user.domain'};
 1679:         if (defined(&domain($udom,'primary'))) {
 1680:             $uhome=&domain($udom,'primary');
 1681:         } else {
 1682:             undef($uhome);
 1683:         }
 1684:     } else {
 1685:         if (!$uhome) {
 1686:             if (defined(&domain($udom,'primary'))) {
 1687:                 $uhome=&domain($udom,'primary');
 1688:             }
 1689:         }
 1690:     } 
 1691:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1692:         my $items='';
 1693:         foreach my $item (keys(%$storehash)) {
 1694:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 1695:         }
 1696:         $items=~s/\&$//;
 1697:         return &reply("putdom:$udom:$namespace:$items",$uhome);
 1698:     } else {
 1699:         &logthis("put_dom failed - no homeserver and/or domain");
 1700:     }
 1701: }
 1702: 
 1703: # --------------------- newput for items in db file owned by domainconfig user
 1704: sub newput_dom {
 1705:     my ($namespace,$storehash,$udom) = @_;
 1706:     my $result;
 1707:     if (!$udom) {
 1708:         $udom=$env{'user.domain'};
 1709:     }
 1710:     if ($udom) {
 1711:         my $uname = &get_domainconfiguser($udom);
 1712:         $result = &newput($namespace,$storehash,$udom,$uname);
 1713:     }
 1714:     return $result;
 1715: }
 1716: 
 1717: # --------------------- delete for items in db file owned by domainconfig user
 1718: sub del_dom {
 1719:     my ($namespace,$storearr,$udom)=@_;
 1720:     if (ref($storearr) eq 'ARRAY') {
 1721:         if (!$udom) {
 1722:             $udom=$env{'user.domain'};
 1723:         }
 1724:         if ($udom) {
 1725:             my $uname = &get_domainconfiguser($udom); 
 1726:             return &del($namespace,$storearr,$udom,$uname);
 1727:         }
 1728:     }
 1729: }
 1730: 
 1731: # ----------------------------------construct domainconfig user for a domain 
 1732: sub get_domainconfiguser {
 1733:     my ($udom) = @_;
 1734:     return $udom.'-domainconfig';
 1735: }
 1736: 
 1737: sub retrieve_inst_usertypes {
 1738:     my ($udom) = @_;
 1739:     my (%returnhash,@order);
 1740:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 1741:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 1742:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 1743:         %returnhash = %{$domdefs{'inststatustypes'}};
 1744:         @order = @{$domdefs{'inststatusorder'}};
 1745:     } else {
 1746:         if (defined(&domain($udom,'primary'))) {
 1747:             my $uhome=&domain($udom,'primary');
 1748:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 1749:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 1750:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
 1751:                 return (\%returnhash,\@order);
 1752:             }
 1753:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 1754:             my @pairs=split(/\&/,$hashitems);
 1755:             foreach my $item (@pairs) {
 1756:                 my ($key,$value)=split(/=/,$item,2);
 1757:                 $key = &unescape($key);
 1758:                 next if ($key =~ /^error: 2 /);
 1759:                 $returnhash{$key}=&thaw_unescape($value);
 1760:             }
 1761:             my @esc_order = split(/\&/,$orderitems);
 1762:             foreach my $item (@esc_order) {
 1763:                 push(@order,&unescape($item));
 1764:             }
 1765:         } else {
 1766:             &logthis("get_dom failed - no primary domain server for $udom");
 1767:         }
 1768:     }
 1769:     return (\%returnhash,\@order);
 1770: }
 1771: 
 1772: sub is_domainimage {
 1773:     my ($url) = @_;
 1774:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
 1775:         if (&domain($1) ne '') {
 1776:             return '1';
 1777:         }
 1778:     }
 1779:     return;
 1780: }
 1781: 
 1782: sub inst_directory_query {
 1783:     my ($srch) = @_;
 1784:     my $udom = $srch->{'srchdomain'};
 1785:     my %results;
 1786:     my $homeserver = &domain($udom,'primary');
 1787:     my $outcome;
 1788:     if ($homeserver ne '') {
 1789: 	my $queryid=&reply("querysend:instdirsearch:".
 1790: 			   &escape($srch->{'srchby'}).':'.
 1791: 			   &escape($srch->{'srchterm'}).':'.
 1792: 			   &escape($srch->{'srchtype'}),$homeserver);
 1793: 	my $host=&hostname($homeserver);
 1794: 	if ($queryid !~/^\Q$host\E\_/) {
 1795: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1796: 	    return;
 1797: 	}
 1798: 	my $response = &get_query_reply($queryid);
 1799: 	my $maxtries = 5;
 1800: 	my $tries = 1;
 1801: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1802: 	    $response = &get_query_reply($queryid);
 1803: 	    $tries ++;
 1804: 	}
 1805: 
 1806:         if (!&error($response) && $response ne 'refused') {
 1807:             if ($response eq 'unavailable') {
 1808:                 $outcome = $response;
 1809:             } else {
 1810:                 $outcome = 'ok';
 1811:                 my @matches = split(/\n/,$response);
 1812:                 foreach my $match (@matches) {
 1813:                     my ($key,$value) = split(/=/,$match);
 1814:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 1815:                 }
 1816:             }
 1817:         }
 1818:     }
 1819:     return ($outcome,%results);
 1820: }
 1821: 
 1822: sub usersearch {
 1823:     my ($srch) = @_;
 1824:     my $dom = $srch->{'srchdomain'};
 1825:     my %results;
 1826:     my %libserv = &all_library();
 1827:     my $query = 'usersearch';
 1828:     foreach my $tryserver (keys(%libserv)) {
 1829:         if (&host_domain($tryserver) eq $dom) {
 1830:             my $host=&hostname($tryserver);
 1831:             my $queryid=
 1832:                 &reply("querysend:".&escape($query).':'.
 1833:                        &escape($srch->{'srchby'}).':'.
 1834:                        &escape($srch->{'srchtype'}).':'.
 1835:                        &escape($srch->{'srchterm'}),$tryserver);
 1836:             if ($queryid !~/^\Q$host\E\_/) {
 1837:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 1838:                 next;
 1839:             }
 1840:             my $reply = &get_query_reply($queryid);
 1841:             my $maxtries = 1;
 1842:             my $tries = 1;
 1843:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 1844:                 $reply = &get_query_reply($queryid);
 1845:                 $tries ++;
 1846:             }
 1847:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 1848:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 1849:             } else {
 1850:                 my @matches;
 1851:                 if ($reply =~ /\n/) {
 1852:                     @matches = split(/\n/,$reply);
 1853:                 } else {
 1854:                     @matches = split(/\&/,$reply);
 1855:                 }
 1856:                 foreach my $match (@matches) {
 1857:                     my ($uname,$udom,%userhash);
 1858:                     foreach my $entry (split(/:/,$match)) {
 1859:                         my ($key,$value) =
 1860:                             map {&unescape($_);} split(/=/,$entry);
 1861:                         $userhash{$key} = $value;
 1862:                         if ($key eq 'username') {
 1863:                             $uname = $value;
 1864:                         } elsif ($key eq 'domain') {
 1865:                             $udom = $value;
 1866:                         }
 1867:                     }
 1868:                     $results{$uname.':'.$udom} = \%userhash;
 1869:                 }
 1870:             }
 1871:         }
 1872:     }
 1873:     return %results;
 1874: }
 1875: 
 1876: sub get_instuser {
 1877:     my ($udom,$uname,$id) = @_;
 1878:     my $homeserver = &domain($udom,'primary');
 1879:     my ($outcome,%results);
 1880:     if ($homeserver ne '') {
 1881:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 1882:                            &escape($id).':'.&escape($udom),$homeserver);
 1883:         my $host=&hostname($homeserver);
 1884:         if ($queryid !~/^\Q$host\E\_/) {
 1885:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1886:             return;
 1887:         }
 1888:         my $response = &get_query_reply($queryid);
 1889:         my $maxtries = 5;
 1890:         my $tries = 1;
 1891:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1892:             $response = &get_query_reply($queryid);
 1893:             $tries ++;
 1894:         }
 1895:         if (!&error($response) && $response ne 'refused') {
 1896:             if ($response eq 'unavailable') {
 1897:                 $outcome = $response;
 1898:             } else {
 1899:                 $outcome = 'ok';
 1900:                 my @matches = split(/\n/,$response);
 1901:                 foreach my $match (@matches) {
 1902:                     my ($key,$value) = split(/=/,$match);
 1903:                     $results{&unescape($key)} = &thaw_unescape($value);
 1904:                 }
 1905:             }
 1906:         }
 1907:     }
 1908:     my %userinfo;
 1909:     if (ref($results{$uname}) eq 'HASH') {
 1910:         %userinfo = %{$results{$uname}};
 1911:     } 
 1912:     return ($outcome,%userinfo);
 1913: }
 1914: 
 1915: sub inst_rulecheck {
 1916:     my ($udom,$uname,$id,$item,$rules) = @_;
 1917:     my %returnhash;
 1918:     if ($udom ne '') {
 1919:         if (ref($rules) eq 'ARRAY') {
 1920:             @{$rules} = map {&escape($_);} (@{$rules});
 1921:             my $rulestr = join(':',@{$rules});
 1922:             my $homeserver=&domain($udom,'primary');
 1923:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1924:                 my $response;
 1925:                 if ($item eq 'username') {                
 1926:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 1927:                                               ':'.&escape($uname).':'.$rulestr,
 1928:                                               $homeserver));
 1929:                 } elsif ($item eq 'id') {
 1930:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 1931:                                               ':'.&escape($id).':'.$rulestr,
 1932:                                               $homeserver));
 1933:                 } elsif ($item eq 'selfcreate') {
 1934:                     $response=&unescape(&reply('instselfcreatecheck:'.
 1935:                                                &escape($udom).':'.&escape($uname).
 1936:                                               ':'.$rulestr,$homeserver));
 1937:                 }
 1938:                 if ($response ne 'refused') {
 1939:                     my @pairs=split(/\&/,$response);
 1940:                     foreach my $item (@pairs) {
 1941:                         my ($key,$value)=split(/=/,$item,2);
 1942:                         $key = &unescape($key);
 1943:                         next if ($key =~ /^error: 2 /);
 1944:                         $returnhash{$key}=&thaw_unescape($value);
 1945:                     }
 1946:                 }
 1947:             }
 1948:         }
 1949:     }
 1950:     return %returnhash;
 1951: }
 1952: 
 1953: sub inst_userrules {
 1954:     my ($udom,$check) = @_;
 1955:     my (%ruleshash,@ruleorder);
 1956:     if ($udom ne '') {
 1957:         my $homeserver=&domain($udom,'primary');
 1958:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1959:             my $response;
 1960:             if ($check eq 'id') {
 1961:                 $response=&reply('instidrules:'.&escape($udom),
 1962:                                  $homeserver);
 1963:             } elsif ($check eq 'email') {
 1964:                 $response=&reply('instemailrules:'.&escape($udom),
 1965:                                  $homeserver);
 1966:             } else {
 1967:                 $response=&reply('instuserrules:'.&escape($udom),
 1968:                                  $homeserver);
 1969:             }
 1970:             if (($response ne 'refused') && ($response ne 'error') && 
 1971:                 ($response ne 'unknown_cmd') && 
 1972:                 ($response ne 'no_such_host')) {
 1973:                 my ($hashitems,$orderitems) = split(/:/,$response);
 1974:                 my @pairs=split(/\&/,$hashitems);
 1975:                 foreach my $item (@pairs) {
 1976:                     my ($key,$value)=split(/=/,$item,2);
 1977:                     $key = &unescape($key);
 1978:                     next if ($key =~ /^error: 2 /);
 1979:                     $ruleshash{$key}=&thaw_unescape($value);
 1980:                 }
 1981:                 my @esc_order = split(/\&/,$orderitems);
 1982:                 foreach my $item (@esc_order) {
 1983:                     push(@ruleorder,&unescape($item));
 1984:                 }
 1985:             }
 1986:         }
 1987:     }
 1988:     return (\%ruleshash,\@ruleorder);
 1989: }
 1990: 
 1991: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 1992: 
 1993: sub get_domain_defaults {
 1994:     my ($domain,$ignore_cache) = @_;
 1995:     return if (($domain eq '') || ($domain eq 'public'));
 1996:     my $cachetime = 60*60*24;
 1997:     unless ($ignore_cache) {
 1998:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 1999:         if (defined($cached)) {
 2000:             if (ref($result) eq 'HASH') {
 2001:                 return %{$result};
 2002:             }
 2003:         }
 2004:     }
 2005:     my %domdefaults;
 2006:     my %domconfig =
 2007:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 2008:                                   'requestcourses','inststatus',
 2009:                                   'coursedefaults','usersessions',
 2010:                                   'requestauthor','selfenrollment'],$domain);
 2011:     my @coursetypes = ('official','unofficial','community','textbook');
 2012:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 2013:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 2014:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 2015:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 2016:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 2017:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 2018:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
 2019:     } else {
 2020:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 2021:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 2022:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 2023:     }
 2024:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 2025:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 2026:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 2027:         } else {
 2028:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 2029:         }
 2030:         my @usertools = ('aboutme','blog','webdav','portfolio');
 2031:         foreach my $item (@usertools) {
 2032:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 2033:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 2034:             }
 2035:         }
 2036:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
 2037:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
 2038:         }
 2039:     }
 2040:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 2041:         foreach my $item ('official','unofficial','community','textbook') {
 2042:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 2043:         }
 2044:     }
 2045:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
 2046:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
 2047:     }
 2048:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 2049:         foreach my $item ('inststatustypes','inststatusorder') {
 2050:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 2051:         }
 2052:     }
 2053:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 2054:         foreach my $type (@coursetypes) {
 2055:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
 2056:                 unless ($type eq 'community') {
 2057:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
 2058:                 }
 2059:             }
 2060:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
 2061:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
 2062:             }
 2063:         }
 2064:     }
 2065:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 2066:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 2067:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 2068:         }
 2069:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 2070:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 2071:         }
 2072:     }
 2073:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
 2074:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
 2075:             my @settings = ('types','registered','enroll_dates','access_dates','section',
 2076:                             'approval','limit');
 2077:             foreach my $type (@coursetypes) {
 2078:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
 2079:                     my @mgrdc = ();
 2080:                     foreach my $item (@settings) {
 2081:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
 2082:                             push(@mgrdc,$item);
 2083:                         }
 2084:                     }
 2085:                     if (@mgrdc) {
 2086:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
 2087:                     }
 2088:                 }
 2089:             }
 2090:         }
 2091:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
 2092:             foreach my $type (@coursetypes) {
 2093:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
 2094:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
 2095:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
 2096:                     }
 2097:                 }
 2098:             }
 2099:         }
 2100:     }
 2101:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
 2102:     return %domdefaults;
 2103: }
 2104: 
 2105: # --------------------------------------------------- Assign a key to a student
 2106: 
 2107: sub assign_access_key {
 2108: #
 2109: # a valid key looks like uname:udom#comments
 2110: # comments are being appended
 2111: #
 2112:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 2113:     $kdom=
 2114:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 2115:     $knum=
 2116:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 2117:     $cdom=
 2118:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2119:     $cnum=
 2120:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2121:     $udom=$env{'user.name'} unless (defined($udom));
 2122:     $uname=$env{'user.domain'} unless (defined($uname));
 2123:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 2124:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 2125:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 2126:                                                   # assigned to this person
 2127:                                                   # - this should not happen,
 2128:                                                   # unless something went wrong
 2129:                                                   # the first time around
 2130: # ready to assign
 2131:         $logentry=$1.'; '.$logentry;
 2132:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 2133:                                                  $kdom,$knum) eq 'ok') {
 2134: # key now belongs to user
 2135: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 2136:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 2137:                 &appenv({'environment.'.$envkey => $ckey});
 2138:                 return 'ok';
 2139:             } else {
 2140:                 return 
 2141:   'error: Count not permanently assign key, will need to be re-entered later.';
 2142: 	    }
 2143:         } else {
 2144:             return 'error: Could not assign key, try again later.';
 2145:         }
 2146:     } elsif (!$existing{$ckey}) {
 2147: # the key does not exist
 2148: 	return 'error: The key does not exist';
 2149:     } else {
 2150: # the key is somebody else's
 2151: 	return 'error: The key is already in use';
 2152:     }
 2153: }
 2154: 
 2155: # ------------------------------------------ put an additional comment on a key
 2156: 
 2157: sub comment_access_key {
 2158: #
 2159: # a valid key looks like uname:udom#comments
 2160: # comments are being appended
 2161: #
 2162:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 2163:     $cdom=
 2164:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2165:     $cnum=
 2166:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2167:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2168:     if ($existing{$ckey}) {
 2169:         $existing{$ckey}.='; '.$logentry;
 2170: # ready to assign
 2171:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 2172:                                                  $cdom,$cnum) eq 'ok') {
 2173: 	    return 'ok';
 2174:         } else {
 2175: 	    return 'error: Count not store comment.';
 2176:         }
 2177:     } else {
 2178: # the key does not exist
 2179: 	return 'error: The key does not exist';
 2180:     }
 2181: }
 2182: 
 2183: # ------------------------------------------------------ Generate a set of keys
 2184: 
 2185: sub generate_access_keys {
 2186:     my ($number,$cdom,$cnum,$logentry)=@_;
 2187:     $cdom=
 2188:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2189:     $cnum=
 2190:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2191:     unless (&allowed('mky',$cdom)) { return 0; }
 2192:     unless (($cdom) && ($cnum)) { return 0; }
 2193:     if ($number>10000) { return 0; }
 2194:     sleep(2); # make sure don't get same seed twice
 2195:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 2196:     my $total=0;
 2197:     for (my $i=1;$i<=$number;$i++) {
 2198:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 2199:                   sprintf("%lx",int(100000*rand)).'-'.
 2200:                   sprintf("%lx",int(100000*rand));
 2201:        $newkey=~s/1/g/g; # folks mix up 1 and l
 2202:        $newkey=~s/0/h/g; # and also 0 and O
 2203:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 2204:        if ($existing{$newkey}) {
 2205:            $i--;
 2206:        } else {
 2207: 	  if (&put('accesskeys',
 2208:               { $newkey => '# generated '.localtime().
 2209:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 2210:                            '; '.$logentry },
 2211: 		   $cdom,$cnum) eq 'ok') {
 2212:               $total++;
 2213: 	  }
 2214:        }
 2215:     }
 2216:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 2217:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 2218:     return $total;
 2219: }
 2220: 
 2221: # ------------------------------------------------------- Validate an accesskey
 2222: 
 2223: sub validate_access_key {
 2224:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 2225:     $cdom=
 2226:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2227:     $cnum=
 2228:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2229:     $udom=$env{'user.domain'} unless (defined($udom));
 2230:     $uname=$env{'user.name'} unless (defined($uname));
 2231:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2232:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 2233: }
 2234: 
 2235: # ------------------------------------- Find the section of student in a course
 2236: sub devalidate_getsection_cache {
 2237:     my ($udom,$unam,$courseid)=@_;
 2238:     my $hashid="$udom:$unam:$courseid";
 2239:     &devalidate_cache_new('getsection',$hashid);
 2240: }
 2241: 
 2242: sub courseid_to_courseurl {
 2243:     my ($courseid) = @_;
 2244:     #already url style courseid
 2245:     return $courseid if ($courseid =~ m{^/});
 2246: 
 2247:     if (exists($env{'course.'.$courseid.'.num'})) {
 2248: 	my $cnum = $env{'course.'.$courseid.'.num'};
 2249: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 2250: 	return "/$cdom/$cnum";
 2251:     }
 2252: 
 2253:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 2254:     if (exists($courseinfo{'num'})) {
 2255: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 2256:     }
 2257: 
 2258:     return undef;
 2259: }
 2260: 
 2261: sub getsection {
 2262:     my ($udom,$unam,$courseid)=@_;
 2263:     my $cachetime=1800;
 2264: 
 2265:     my $hashid="$udom:$unam:$courseid";
 2266:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 2267:     if (defined($cached)) { return $result; }
 2268: 
 2269:     my %Pending; 
 2270:     my %Expired;
 2271:     #
 2272:     # Each role can either have not started yet (pending), be active, 
 2273:     #    or have expired.
 2274:     #
 2275:     # If there is an active role, we are done.
 2276:     #
 2277:     # If there is more than one role which has not started yet, 
 2278:     #     choose the one which will start sooner
 2279:     # If there is one role which has not started yet, return it.
 2280:     #
 2281:     # If there is more than one expired role, choose the one which ended last.
 2282:     # If there is a role which has expired, return it.
 2283:     #
 2284:     $courseid = &courseid_to_courseurl($courseid);
 2285:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 2286:     foreach my $key (keys(%roleshash)) {
 2287:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 2288:         my $section=$1;
 2289:         if ($key eq $courseid.'_st') { $section=''; }
 2290:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 2291:         my $now=time;
 2292:         if (defined($end) && $end && ($now > $end)) {
 2293:             $Expired{$end}=$section;
 2294:             next;
 2295:         }
 2296:         if (defined($start) && $start && ($now < $start)) {
 2297:             $Pending{$start}=$section;
 2298:             next;
 2299:         }
 2300:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 2301:     }
 2302:     #
 2303:     # Presumedly there will be few matching roles from the above
 2304:     # loop and the sorting time will be negligible.
 2305:     if (scalar(keys(%Pending))) {
 2306:         my ($time) = sort {$a <=> $b} keys(%Pending);
 2307:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 2308:     } 
 2309:     if (scalar(keys(%Expired))) {
 2310:         my @sorted = sort {$a <=> $b} keys(%Expired);
 2311:         my $time = pop(@sorted);
 2312:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 2313:     }
 2314:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 2315: }
 2316: 
 2317: sub save_cache {
 2318:     &purge_remembered();
 2319:     #&Apache::loncommon::validate_page();
 2320:     undef(%env);
 2321:     undef($env_loaded);
 2322: }
 2323: 
 2324: my $to_remember=-1;
 2325: my %remembered;
 2326: my %accessed;
 2327: my $kicks=0;
 2328: my $hits=0;
 2329: sub make_key {
 2330:     my ($name,$id) = @_;
 2331:     if (length($id) > 65 
 2332: 	&& length(&escape($id)) > 200) {
 2333: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 2334:     }
 2335:     return &escape($name.':'.$id);
 2336: }
 2337: 
 2338: sub devalidate_cache_new {
 2339:     my ($name,$id,$debug) = @_;
 2340:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 2341:     $id=&make_key($name,$id);
 2342:     $memcache->delete($id);
 2343:     delete($remembered{$id});
 2344:     delete($accessed{$id});
 2345: }
 2346: 
 2347: sub is_cached_new {
 2348:     my ($name,$id,$debug) = @_;
 2349:     $id=&make_key($name,$id);
 2350:     if (exists($remembered{$id})) {
 2351: 	if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
 2352: 	$accessed{$id}=[&gettimeofday()];
 2353: 	$hits++;
 2354: 	return ($remembered{$id},1);
 2355:     }
 2356:     my $value = $memcache->get($id);
 2357:     if (!(defined($value))) {
 2358: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 2359: 	return (undef,undef);
 2360:     }
 2361:     if ($value eq '__undef__') {
 2362: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 2363: 	$value=undef;
 2364:     }
 2365:     &make_room($id,$value,$debug);
 2366:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 2367:     return ($value,1);
 2368: }
 2369: 
 2370: sub do_cache_new {
 2371:     my ($name,$id,$value,$time,$debug) = @_;
 2372:     $id=&make_key($name,$id);
 2373:     my $setvalue=$value;
 2374:     if (!defined($setvalue)) {
 2375: 	$setvalue='__undef__';
 2376:     }
 2377:     if (!defined($time) ) {
 2378: 	$time=600;
 2379:     }
 2380:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 2381:     my $result = $memcache->set($id,$setvalue,$time);
 2382:     if (! $result) {
 2383: 	&logthis("caching of id -> $id  failed");
 2384: 	$memcache->disconnect_all();
 2385:     }
 2386:     # need to make a copy of $value
 2387:     &make_room($id,$value,$debug);
 2388:     return $value;
 2389: }
 2390: 
 2391: sub make_room {
 2392:     my ($id,$value,$debug)=@_;
 2393: 
 2394:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
 2395:                                     : $value;
 2396:     if ($to_remember<0) { return; }
 2397:     $accessed{$id}=[&gettimeofday()];
 2398:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 2399:     my $to_kick;
 2400:     my $max_time=0;
 2401:     foreach my $other (keys(%accessed)) {
 2402: 	if (&tv_interval($accessed{$other}) > $max_time) {
 2403: 	    $to_kick=$other;
 2404: 	    $max_time=&tv_interval($accessed{$other});
 2405: 	}
 2406:     }
 2407:     delete($remembered{$to_kick});
 2408:     delete($accessed{$to_kick});
 2409:     $kicks++;
 2410:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 2411:     return;
 2412: }
 2413: 
 2414: sub purge_remembered {
 2415:     #&logthis("Tossing ".scalar(keys(%remembered)));
 2416:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 2417:     undef(%remembered);
 2418:     undef(%accessed);
 2419: }
 2420: # ------------------------------------- Read an entry from a user's environment
 2421: 
 2422: sub userenvironment {
 2423:     my ($udom,$unam,@what)=@_;
 2424:     my $items;
 2425:     foreach my $item (@what) {
 2426:         $items.=&escape($item).'&';
 2427:     }
 2428:     $items=~s/\&$//;
 2429:     my %returnhash=();
 2430:     my $uhome = &homeserver($unam,$udom);
 2431:     unless ($uhome eq 'no_host') {
 2432:         my @answer=split(/\&/, 
 2433:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 2434:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 2435:             return %returnhash;
 2436:         }
 2437:         my $i;
 2438:         for ($i=0;$i<=$#what;$i++) {
 2439: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 2440:         }
 2441:     }
 2442:     return %returnhash;
 2443: }
 2444: 
 2445: # ---------------------------------------------------------- Get a studentphoto
 2446: sub studentphoto {
 2447:     my ($udom,$unam,$ext) = @_;
 2448:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2449:     if (defined($env{'request.course.id'})) {
 2450:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 2451:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 2452:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 2453:             } else {
 2454:                 my ($result,$perm_reqd)=
 2455: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2456:                 if ($result eq 'ok') {
 2457:                     if (!($perm_reqd eq 'yes')) {
 2458:                         return(&retrievestudentphoto($udom,$unam,$ext));
 2459:                     }
 2460:                 }
 2461:             }
 2462:         }
 2463:     } else {
 2464:         my ($result,$perm_reqd) = 
 2465: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2466:         if ($result eq 'ok') {
 2467:             if (!($perm_reqd eq 'yes')) {
 2468:                 return(&retrievestudentphoto($udom,$unam,$ext));
 2469:             }
 2470:         }
 2471:     }
 2472:     return '/adm/lonKaputt/lonlogo_broken.gif';
 2473: }
 2474: 
 2475: sub retrievestudentphoto {
 2476:     my ($udom,$unam,$ext,$type) = @_;
 2477:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2478:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 2479:     if ($ret eq 'ok') {
 2480:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 2481:         if ($type eq 'thumbnail') {
 2482:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 2483:         }
 2484:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 2485:         return $tokenurl;
 2486:     } else {
 2487:         if ($type eq 'thumbnail') {
 2488:             return '/adm/lonKaputt/genericstudent_tn.gif';
 2489:         } else { 
 2490:             return '/adm/lonKaputt/lonlogo_broken.gif';
 2491:         }
 2492:     }
 2493: }
 2494: 
 2495: # -------------------------------------------------------------------- New chat
 2496: 
 2497: sub chatsend {
 2498:     my ($newentry,$anon,$group)=@_;
 2499:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 2500:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2501:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 2502:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 2503: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 2504: 		   &escape($newentry)).':'.$group,$chome);
 2505: }
 2506: 
 2507: # ------------------------------------------ Find current version of a resource
 2508: 
 2509: sub getversion {
 2510:     my $fname=&clutter(shift);
 2511:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
 2512:     return &currentversion(&filelocation('',$fname));
 2513: }
 2514: 
 2515: sub currentversion {
 2516:     my $fname=shift;
 2517:     my $author=$fname;
 2518:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2519:     my ($udom,$uname)=split(/\//,$author);
 2520:     my $home=&homeserver($uname,$udom);
 2521:     if ($home eq 'no_host') { 
 2522:         return -1; 
 2523:     }
 2524:     my $answer=&reply("currentversion:$fname",$home);
 2525:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 2526: 	return -1;
 2527:     }
 2528:     return $answer;
 2529: }
 2530: 
 2531: #
 2532: # Return special version number of resource if set by override, empty otherwise
 2533: #
 2534: sub usedversion {
 2535:     my $fname=shift;
 2536:     unless ($fname) { $fname=$env{'request.uri'}; }
 2537:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 2538:     if ($urlversion) { return $urlversion; }
 2539:     return '';
 2540: }
 2541: 
 2542: # ----------------------------- Subscribe to a resource, return URL if possible
 2543: 
 2544: sub subscribe {
 2545:     my $fname=shift;
 2546:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 2547:     $fname=~s/[\n\r]//g;
 2548:     my $author=$fname;
 2549:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2550:     my ($udom,$uname)=split(/\//,$author);
 2551:     my $home=homeserver($uname,$udom);
 2552:     if ($home eq 'no_host') {
 2553:         return 'not_found';
 2554:     }
 2555:     my $answer=reply("sub:$fname",$home);
 2556:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 2557: 	$answer.=' by '.$home;
 2558:     }
 2559:     return $answer;
 2560: }
 2561:     
 2562: # -------------------------------------------------------------- Replicate file
 2563: 
 2564: sub repcopy {
 2565:     my $filename=shift;
 2566:     $filename=~s/\/+/\//g;
 2567:     my $londocroot = $perlvar{'lonDocRoot'};
 2568:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 2569:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
 2570:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 2571: 	$filename=~m{^/*(uploaded|editupload)/}) {
 2572: 	return &repcopy_userfile($filename);
 2573:     }
 2574:     $filename=~s/[\n\r]//g;
 2575:     my $transname="$filename.in.transfer";
 2576: # FIXME: this should flock
 2577:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 2578:     my $remoteurl=subscribe($filename);
 2579:     if ($remoteurl =~ /^con_lost by/) {
 2580: 	   &logthis("Subscribe returned $remoteurl: $filename");
 2581:            return 'unavailable';
 2582:     } elsif ($remoteurl eq 'not_found') {
 2583: 	   #&logthis("Subscribe returned not_found: $filename");
 2584: 	   return 'not_found';
 2585:     } elsif ($remoteurl =~ /^rejected by/) {
 2586: 	   &logthis("Subscribe returned $remoteurl: $filename");
 2587:            return 'forbidden';
 2588:     } elsif ($remoteurl eq 'directory') {
 2589:            return 'ok';
 2590:     } else {
 2591:         my $author=$filename;
 2592:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2593:         my ($udom,$uname)=split(/\//,$author);
 2594:         my $home=homeserver($uname,$udom);
 2595:         unless ($home eq $perlvar{'lonHostID'}) {
 2596:            my @parts=split(/\//,$filename);
 2597:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 2598:            if ($path ne "$londocroot/res") {
 2599:                &logthis("Malconfiguration for replication: $filename");
 2600: 	       return 'bad_request';
 2601:            }
 2602:            my $count;
 2603:            for ($count=5;$count<$#parts;$count++) {
 2604:                $path.="/$parts[$count]";
 2605:                if ((-e $path)!=1) {
 2606: 		   mkdir($path,0777);
 2607:                }
 2608:            }
 2609:            my $ua=new LWP::UserAgent;
 2610:            my $request=new HTTP::Request('GET',"$remoteurl");
 2611:            my $response=$ua->request($request,$transname);
 2612:            if ($response->is_error()) {
 2613: 	       unlink($transname);
 2614:                my $message=$response->status_line;
 2615:                &logthis("<font color=\"blue\">WARNING:"
 2616:                        ." LWP get: $message: $filename</font>");
 2617:                return 'unavailable';
 2618:            } else {
 2619: 	       if ($remoteurl!~/\.meta$/) {
 2620:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 2621:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 2622:                   if ($mresponse->is_error()) {
 2623: 		      unlink($filename.'.meta');
 2624:                       &logthis(
 2625:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 2626:                   }
 2627: 	       }
 2628:                rename($transname,$filename);
 2629:                return 'ok';
 2630:            }
 2631:        }
 2632:     }
 2633: }
 2634: 
 2635: # ------------------------------------------------ Get server side include body
 2636: sub ssi_body {
 2637:     my ($filelink,%form)=@_;
 2638:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 2639:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 2640:     }
 2641:     my $output='';
 2642:     my $response;
 2643:     if ($filelink=~/^https?\:/) {
 2644:        ($output,$response)=&externalssi($filelink);
 2645:     } else {
 2646:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 2647:        $filelink .= 'inhibitmenu=yes';
 2648:        ($output,$response)=&ssi($filelink,%form);
 2649:     }
 2650:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 2651:     $output=~s/^.*?\<body[^\>]*\>//si;
 2652:     $output=~s/\<\/body\s*\>.*?$//si;
 2653:     if (wantarray) {
 2654:         return ($output, $response);
 2655:     } else {
 2656:         return $output;
 2657:     }
 2658: }
 2659: 
 2660: # --------------------------------------------------------- Server Side Include
 2661: 
 2662: sub absolute_url {
 2663:     my ($host_name) = @_;
 2664:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 2665:     if ($host_name eq '') {
 2666: 	$host_name = $ENV{'SERVER_NAME'};
 2667:     }
 2668:     return $protocol.$host_name;
 2669: }
 2670: 
 2671: #
 2672: #   Server side include.
 2673: # Parameters:
 2674: #  fn     Possibly encrypted resource name/id.
 2675: #  form   Hash that describes how the rendering should be done
 2676: #         and other things.
 2677: # Returns:
 2678: #   Scalar context: The content of the response.
 2679: #   Array context:  2 element list of the content and the full response object.
 2680: #     
 2681: sub ssi {
 2682: 
 2683:     my ($fn,%form)=@_;
 2684:     my $ua=new LWP::UserAgent;
 2685:     my $request;
 2686: 
 2687:     $form{'no_update_last_known'}=1;
 2688:     &Apache::lonenc::check_encrypt(\$fn);
 2689:     if (%form) {
 2690:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 2691:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
 2692:     } else {
 2693:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 2694:     }
 2695: 
 2696:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 2697:     my $response= $ua->request($request);
 2698:     if (wantarray) {
 2699: 	return ($response->content, $response);
 2700:     } else {
 2701: 	return $response->content;
 2702:     }
 2703: }
 2704: 
 2705: sub externalssi {
 2706:     my ($url)=@_;
 2707:     my $ua=new LWP::UserAgent;
 2708:     my $request=new HTTP::Request('GET',$url);
 2709:     my $response=$ua->request($request);
 2710:     if (wantarray) {
 2711:         return ($response->content, $response);
 2712:     } else {
 2713:         return $response->content;
 2714:     }
 2715: }
 2716: 
 2717: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 2718: 
 2719: sub allowuploaded {
 2720:     my ($srcurl,$url)=@_;
 2721:     $url=&clutter(&declutter($url));
 2722:     my $dir=$url;
 2723:     $dir=~s/\/[^\/]+$//;
 2724:     my %httpref=();
 2725:     my $httpurl=&hreflocation('',$url);
 2726:     $httpref{'httpref.'.$httpurl}=$srcurl;
 2727:     &Apache::lonnet::appenv(\%httpref);
 2728: }
 2729: 
 2730: #
 2731: # Determine if the current user should be able to edit a particular resource,
 2732: # when viewing in course context.
 2733: # (a) When viewing resource used to determine if "Edit" item is included in
 2734: #     Functions.
 2735: # (b) When displaying folder contents in course editor, used to determine if
 2736: #     "Edit" link will be displayed alongside resource.
 2737: #
 2738: #  input: six args -- filename (decluttered), course number, course domain,
 2739: #                   url, symb (if registered) and group (if this is a group
 2740: #                   item -- e.g., bulletin board, group page etc.).
 2741: #  output: array of five scalars --
 2742: #          $cfile -- url for file editing if editable on current server
 2743: #          $home -- homeserver of resource (i.e., for author if published,
 2744: #                                           or course if uploaded.).
 2745: #          $switchserver --  1 if server switch will be needed.
 2746: #          $forceedit -- 1 if icon/link should be to go to edit mode
 2747: #          $forceview -- 1 if icon/link should be to go to view mode
 2748: #
 2749: 
 2750: sub can_edit_resource {
 2751:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
 2752:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
 2753: #
 2754: # For aboutme pages user can only edit his/her own.
 2755: #
 2756:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
 2757:         my ($sdom,$sname) = ($1,$2);
 2758:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
 2759:             $home = $env{'user.home'};
 2760:             $cfile = $resurl;
 2761:             if ($env{'form.forceedit'}) {
 2762:                 $forceview = 1;
 2763:             } else {
 2764:                 $forceedit = 1;
 2765:             }
 2766:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
 2767:         } else {
 2768:             return;
 2769:         }
 2770:     }
 2771: 
 2772:     if ($env{'request.course.id'}) {
 2773:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
 2774:         if ($group ne '') {
 2775: # if this is a group homepage or group bulletin board, check group privs
 2776:             my $allowed = 0;
 2777:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
 2778:                 if ((&allowed('mdg',$env{'request.course.id'}.
 2779:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 2780:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 2781:                     $allowed = 1;
 2782:                 }
 2783:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
 2784:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 2785:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 2786:                     $allowed = 1;
 2787:                 }
 2788:             }
 2789:             if ($allowed) {
 2790:                 $home=&homeserver($cnum,$cdom);
 2791:                 if ($env{'form.forceedit'}) {
 2792:                     $forceview = 1;
 2793:                 } else {
 2794:                     $forceedit = 1;
 2795:                 }
 2796:                 $cfile = $resurl;
 2797:             } else {
 2798:                 return;
 2799:             }
 2800:         } else {
 2801:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
 2802:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
 2803:                     return;
 2804:                 }
 2805:             } elsif (!$crsedit) {
 2806: #
 2807: # No edit allowed where CC has switched to student role.
 2808: #
 2809:                 return;
 2810:             }
 2811:         }
 2812:     }
 2813: 
 2814:     if ($file ne '') {
 2815:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
 2816:             if (&is_course_upload($file,$cnum,$cdom)) {
 2817:                 $uploaded = 1;
 2818:                 $incourse = 1;
 2819:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
 2820:                     $cfile = &hreflocation('',$file);
 2821:                     if ($env{'form.forceedit'}) {
 2822:                         $forceview = 1;
 2823:                     } else {
 2824:                         $forceedit = 1;
 2825:                     }
 2826:                 }
 2827:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
 2828:                 $incourse = 1;
 2829:                 if ($env{'form.forceedit'}) {
 2830:                     $forceview = 1;
 2831:                 } else {
 2832:                     $forceedit = 1;
 2833:                 }
 2834:                 $cfile = $resurl;
 2835:             } elsif (($resurl ne '') && (&is_on_map($resurl))) {
 2836:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
 2837:                     $incourse = 1;
 2838:                     if ($env{'form.forceedit'}) {
 2839:                         $forceview = 1;
 2840:                     } else {
 2841:                         $forceedit = 1;
 2842:                     }
 2843:                     $cfile = $resurl;
 2844:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
 2845:                     $incourse = 1;
 2846:                     $cfile = $resurl.'/smpedit';
 2847:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
 2848:                     $incourse = 1;
 2849:                     if ($env{'form.forceedit'}) {
 2850:                         $forceview = 1;
 2851:                     } else {
 2852:                         $forceedit = 1;
 2853:                     }
 2854:                     $cfile = $resurl;
 2855:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 2856:                     $incourse = 1;
 2857:                     if ($env{'form.forceedit'}) {
 2858:                         $forceview = 1;
 2859:                     } else {
 2860:                         $forceedit = 1;
 2861:                     }
 2862:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 2863:                 }
 2864:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
 2865:                 my $template = '/res/lib/templates/simpleproblem.problem';
 2866:                 if (&is_on_map($template)) {
 2867:                     $incourse = 1;
 2868:                     $forceview = 1;
 2869:                     $cfile = $template;
 2870:                 }
 2871:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 2872:                     $incourse = 1;
 2873:                     if ($env{'form.forceedit'}) {
 2874:                         $forceview = 1;
 2875:                     } else {
 2876:                         $forceedit = 1;
 2877:                     }
 2878:                     $cfile = $resurl;
 2879:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
 2880:                 $incourse = 1;
 2881:                 $forceview = 1;
 2882:                 if ($symb) {
 2883:                     my ($map,$id,$res)=&decode_symb($symb);
 2884:                     $env{'request.symb'} = $symb;
 2885:                     $cfile = &clutter($res);
 2886:                 } else {
 2887:                     $cfile = $env{'form.suppurl'};
 2888:                     $cfile =~ s{^http://}{};
 2889:                     $cfile = '/adm/wrapper/ext/'.$cfile;
 2890:                 }
 2891:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 2892:                 if ($env{'form.forceedit'}) {
 2893:                     $forceview = 1;
 2894:                 } else {
 2895:                     $forceedit = 1;
 2896:                 }
 2897:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 2898:             }
 2899:         }
 2900:         if ($uploaded || $incourse) {
 2901:             $home=&homeserver($cnum,$cdom);
 2902:         } elsif ($file !~ m{/$}) {
 2903:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
 2904:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
 2905:             # Check that the user has permission to edit this resource
 2906:             my $setpriv = 1;
 2907:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
 2908:             if (defined($cfudom)) {
 2909:                 $home=&homeserver($cfuname,$cfudom);
 2910:                 $cfile=$file;
 2911:             }
 2912:         }
 2913:         if (($cfile ne '') && (!$incourse || $uploaded) &&
 2914:             (($home ne '') && ($home ne 'no_host'))) {
 2915:             my @ids=&current_machine_ids();
 2916:             unless (grep(/^\Q$home\E$/,@ids)) {
 2917:                 $switchserver=1;
 2918:             }
 2919:         }
 2920:     }
 2921:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
 2922: }
 2923: 
 2924: sub is_course_upload {
 2925:     my ($file,$cnum,$cdom) = @_;
 2926:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
 2927:     $uploadpath =~ s{^\/}{};
 2928:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
 2929:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
 2930:         return 1;
 2931:     }
 2932:     return;
 2933: }
 2934: 
 2935: sub in_course {
 2936:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
 2937:     if ($hideprivileged) {
 2938:         my $skipuser;
 2939:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
 2940:         my @possdoms = ($cdom);
 2941:         if ($coursehash{'checkforpriv'}) {
 2942:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 2943:         }
 2944:         if (&privileged($uname,$udom,\@possdoms)) {
 2945:             $skipuser = 1;
 2946:             if ($coursehash{'nothideprivileged'}) {
 2947:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2948:                     my $user;
 2949:                     if ($item =~ /:/) {
 2950:                         $user = $item;
 2951:                     } else {
 2952:                         $user = join(':',split(/[\@]/,$item));
 2953:                     }
 2954:                     if ($user eq $uname.':'.$udom) {
 2955:                         undef($skipuser);
 2956:                         last;
 2957:                     }
 2958:                 }
 2959:             }
 2960:             if ($skipuser) {
 2961:                 return 0;
 2962:             }
 2963:         }
 2964:     }
 2965:     $type ||= 'any';
 2966:     if (!defined($cdom) || !defined($cnum)) {
 2967:         my $cid  = $env{'request.course.id'};
 2968:         $cdom = $env{'course.'.$cid.'.domain'};
 2969:         $cnum = $env{'course.'.$cid.'.num'};
 2970:     }
 2971:     my $typesref;
 2972:     if (($type eq 'any') || ($type eq 'all')) {
 2973:         $typesref = ['active','previous','future'];
 2974:     } elsif ($type eq 'previous' || $type eq 'future') {
 2975:         $typesref = [$type];
 2976:     }
 2977:     my %roles = &get_my_roles($uname,$udom,'userroles',
 2978:                               $typesref,undef,[$cdom]);
 2979:     my ($tmp) = keys(%roles);
 2980:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
 2981:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
 2982:     if (@course_roles > 0) {
 2983:         return 1;
 2984:     }
 2985:     return 0;
 2986: }
 2987: 
 2988: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 2989: # input: action, courseID, current domain, intended
 2990: #        path to file, source of file, instruction to parse file for objects,
 2991: #        ref to hash for embedded objects,
 2992: #        ref to hash for codebase of java objects.
 2993: #        reference to scalar to accommodate mime type determined
 2994: #          from File::MMagic if $parser = parse.
 2995: #
 2996: # output: url to file (if action was uploaddoc), 
 2997: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 2998: #
 2999: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 3000: # course.
 3001: #
 3002: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3003: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 3004: #          course's home server.
 3005: #
 3006: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 3007: #          be copied from $source (current location) to 
 3008: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3009: #         and will then be copied to
 3010: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 3011: #         course's home server.
 3012: #
 3013: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3014: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 3015: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3016: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 3017: #         in course's home server.
 3018: #
 3019: 
 3020: sub process_coursefile {
 3021:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 3022:         $mimetype)=@_;
 3023:     my $fetchresult;
 3024:     my $home=&homeserver($docuname,$docudom);
 3025:     if ($action eq 'propagate') {
 3026:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3027: 			     $home);
 3028:     } else {
 3029:         my $fpath = '';
 3030:         my $fname = $file;
 3031:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3032:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3033:         my $filepath = &build_filepath($fpath);
 3034:         if ($action eq 'copy') {
 3035:             if ($source eq '') {
 3036:                 $fetchresult = 'no source file';
 3037:                 return $fetchresult;
 3038:             } else {
 3039:                 my $destination = $filepath.'/'.$fname;
 3040:                 rename($source,$destination);
 3041:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3042:                                  $home);
 3043:             }
 3044:         } elsif ($action eq 'uploaddoc') {
 3045:             open(my $fh,'>'.$filepath.'/'.$fname);
 3046:             print $fh $env{'form.'.$source};
 3047:             close($fh);
 3048:             if ($parser eq 'parse') {
 3049:                 my $mm = new File::MMagic;
 3050:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 3051:                 if ($type eq 'text/html') {
 3052:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 3053:                     unless ($parse_result eq 'ok') {
 3054:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 3055:                     }
 3056:                 }
 3057:                 if (ref($mimetype)) {
 3058:                     $$mimetype = $type;
 3059:                 } 
 3060:             }
 3061:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3062:                                  $home);
 3063:             if ($fetchresult eq 'ok') {
 3064:                 return '/uploaded/'.$fpath.'/'.$fname;
 3065:             } else {
 3066:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3067:                         ' to host '.$home.': '.$fetchresult);
 3068:                 return '/adm/notfound.html';
 3069:             }
 3070:         }
 3071:     }
 3072:     unless ( $fetchresult eq 'ok') {
 3073:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3074:              ' to host '.$home.': '.$fetchresult);
 3075:     }
 3076:     return $fetchresult;
 3077: }
 3078: 
 3079: sub build_filepath {
 3080:     my ($fpath) = @_;
 3081:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 3082:     unless ($fpath eq '') {
 3083:         my @parts=split('/',$fpath);
 3084:         foreach my $part (@parts) {
 3085:             $filepath.= '/'.$part;
 3086:             if ((-e $filepath)!=1) {
 3087:                 mkdir($filepath,0777);
 3088:             }
 3089:         }
 3090:     }
 3091:     return $filepath;
 3092: }
 3093: 
 3094: sub store_edited_file {
 3095:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 3096:     my $file = $primary_url;
 3097:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 3098:     my $fpath = '';
 3099:     my $fname = $file;
 3100:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3101:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3102:     my $filepath = &build_filepath($fpath);
 3103:     open(my $fh,'>'.$filepath.'/'.$fname);
 3104:     print $fh $content;
 3105:     close($fh);
 3106:     my $home=&homeserver($docuname,$docudom);
 3107:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3108: 			  $home);
 3109:     if ($$fetchresult eq 'ok') {
 3110:         return '/uploaded/'.$fpath.'/'.$fname;
 3111:     } else {
 3112:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3113: 		 ' to host '.$home.': '.$$fetchresult);
 3114:         return '/adm/notfound.html';
 3115:     }
 3116: }
 3117: 
 3118: sub clean_filename {
 3119:     my ($fname,$args)=@_;
 3120: # Replace Windows backslashes by forward slashes
 3121:     $fname=~s/\\/\//g;
 3122:     if (!$args->{'keep_path'}) {
 3123:         # Get rid of everything but the actual filename
 3124: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 3125:     }
 3126: # Replace spaces by underscores
 3127:     $fname=~s/\s+/\_/g;
 3128: # Replace all other weird characters by nothing
 3129:     $fname=~s{[^/\w\.\-]}{}g;
 3130: # Replace all .\d. sequences with _\d. so they no longer look like version
 3131: # numbers
 3132:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 3133:     return $fname;
 3134: }
 3135: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 3136: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 3137: # image with the same aspect ratio as the original, but with dimensions which do 
 3138: # not exceed $resizewidth and $resizeheight.
 3139:  
 3140: sub resizeImage {
 3141:     my ($img_path,$resizewidth,$resizeheight) = @_;
 3142:     my $ima = Image::Magick->new;
 3143:     my $resized;
 3144:     if (-e $img_path) {
 3145:         $ima->Read($img_path);
 3146:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 3147:             my $width = $ima->Get('width');
 3148:             my $height = $ima->Get('height');
 3149:             if ($width > $resizewidth) {
 3150: 	        my $factor = $width/$resizewidth;
 3151:                 my $newheight = $height/$factor;
 3152:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 3153:                 $resized = 1;
 3154:             }
 3155:         }
 3156:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 3157:             my $width = $ima->Get('width');
 3158:             my $height = $ima->Get('height');
 3159:             if ($height > $resizeheight) {
 3160:                 my $factor = $height/$resizeheight;
 3161:                 my $newwidth = $width/$factor;
 3162:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 3163:                 $resized = 1;
 3164:             }
 3165:         }
 3166:         if ($resized) {
 3167:             $ima->Write($img_path);
 3168:         }
 3169:     }
 3170:     return;
 3171: }
 3172: 
 3173: # --------------- Take an uploaded file and put it into the userfiles directory
 3174: # input: $formname - the contents of the file are in $env{"form.$formname"}
 3175: #                    the desired filename is in $env{"form.$formname.filename"}
 3176: #        $context - possible values: coursedoc, existingfile, overwrite, 
 3177: #                                    canceloverwrite, or ''. 
 3178: #                   if 'coursedoc': upload to the current course
 3179: #                   if 'existingfile': write file to tmp/overwrites directory 
 3180: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 3181: #                   $context is passed as argument to &finishuserfileupload
 3182: #        $subdir - directory in userfile to store the file into
 3183: #        $parser - instruction to parse file for objects ($parser = parse)    
 3184: #        $allfiles - reference to hash for embedded objects
 3185: #        $codebase - reference to hash for codebase of java objects
 3186: #        $desuname - username for permanent storage of uploaded file
 3187: #        $dsetudom - domain for permanaent storage of uploaded file
 3188: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 3189: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 3190: #        $resizewidth - width (pixels) to which to resize uploaded image
 3191: #        $resizeheight - height (pixels) to which to resize uploaded image
 3192: #        $mimetype - reference to scalar to accommodate mime type determined
 3193: #                    from File::MMagic.
 3194: # 
 3195: # output: url of file in userspace, or error: <message> 
 3196: #             or /adm/notfound.html if failure to upload occurse
 3197: 
 3198: sub userfileupload {
 3199:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 3200:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 3201:     if (!defined($subdir)) { $subdir='unknown'; }
 3202:     my $fname=$env{'form.'.$formname.'.filename'};
 3203:     $fname=&clean_filename($fname);
 3204:     # See if there is anything left
 3205:     unless ($fname) { return 'error: no uploaded file'; }
 3206:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 3207:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 3208:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 3209:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3210:         my $now = time;
 3211:         my $filepath;
 3212:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 3213:              $filepath = 'tmp/helprequests/'.$now;
 3214:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 3215:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 3216:                          '_'.$env{'user.domain'}.'/pending';
 3217:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3218:             my ($docuname,$docudom);
 3219:             if ($destudom) {
 3220:                 $docudom = $destudom;
 3221:             } else {
 3222:                 $docudom = $env{'user.domain'};
 3223:             }
 3224:             if ($destuname) {
 3225:                 $docuname = $destuname;
 3226:             } else {
 3227:                 $docuname = $env{'user.name'};
 3228:             }
 3229:             if (exists($env{'form.group'})) {
 3230:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3231:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3232:             }
 3233:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 3234:             if ($context eq 'canceloverwrite') {
 3235:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 3236:                 if (-e  $tempfile) {
 3237:                     my @info = stat($tempfile);
 3238:                     if ($info[9] eq $env{'form.timestamp'}) {
 3239:                         unlink($tempfile);
 3240:                     }
 3241:                 }
 3242:                 return;
 3243:             }
 3244:         }
 3245:         # Create the directory if not present
 3246:         my @parts=split(/\//,$filepath);
 3247:         my $fullpath = $perlvar{'lonDaemons'};
 3248:         for (my $i=0;$i<@parts;$i++) {
 3249:             $fullpath .= '/'.$parts[$i];
 3250:             if ((-e $fullpath)!=1) {
 3251:                 mkdir($fullpath,0777);
 3252:             }
 3253:         }
 3254:         open(my $fh,'>'.$fullpath.'/'.$fname);
 3255:         print $fh $env{'form.'.$formname};
 3256:         close($fh);
 3257:         if ($context eq 'existingfile') {
 3258:             my @info = stat($fullpath.'/'.$fname);
 3259:             return ($fullpath.'/'.$fname,$info[9]);
 3260:         } else {
 3261:             return $fullpath.'/'.$fname;
 3262:         }
 3263:     }
 3264:     if ($subdir eq 'scantron') {
 3265:         $fname = 'scantron_orig_'.$fname;
 3266:     } else {
 3267:         $fname="$subdir/$fname";
 3268:     }
 3269:     if ($context eq 'coursedoc') {
 3270: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3271: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3272:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 3273:             return &finishuserfileupload($docuname,$docudom,
 3274: 					 $formname,$fname,$parser,$allfiles,
 3275: 					 $codebase,$thumbwidth,$thumbheight,
 3276:                                          $resizewidth,$resizeheight,$context,$mimetype);
 3277:         } else {
 3278:             if ($env{'form.folder'}) {
 3279:                 $fname=$env{'form.folder'}.'/'.$fname;
 3280:             }
 3281:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 3282: 				       $fname,$formname,$parser,
 3283: 				       $allfiles,$codebase,$mimetype);
 3284:         }
 3285:     } elsif (defined($destuname)) {
 3286:         my $docuname=$destuname;
 3287:         my $docudom=$destudom;
 3288: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3289: 				     $parser,$allfiles,$codebase,
 3290:                                      $thumbwidth,$thumbheight,
 3291:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3292:     } else {
 3293:         my $docuname=$env{'user.name'};
 3294:         my $docudom=$env{'user.domain'};
 3295:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
 3296:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3297:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3298:         }
 3299: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3300: 				     $parser,$allfiles,$codebase,
 3301:                                      $thumbwidth,$thumbheight,
 3302:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3303:     }
 3304: }
 3305: 
 3306: sub finishuserfileupload {
 3307:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 3308:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 3309:     my $path=$docudom.'/'.$docuname.'/';
 3310:     my $filepath=$perlvar{'lonDocRoot'};
 3311:   
 3312:     my ($fnamepath,$file,$fetchthumb);
 3313:     $file=$fname;
 3314:     if ($fname=~m|/|) {
 3315:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 3316: 	$path.=$fnamepath.'/';
 3317:     }
 3318:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 3319:     my $count;
 3320:     for ($count=4;$count<=$#parts;$count++) {
 3321:         $filepath.="/$parts[$count]";
 3322:         if ((-e $filepath)!=1) {
 3323: 	    mkdir($filepath,0777);
 3324:         }
 3325:     }
 3326: 
 3327: # Save the file
 3328:     {
 3329: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 3330: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 3331: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 3332: 	    return '/adm/notfound.html';
 3333: 	}
 3334:         if ($context eq 'overwrite') {
 3335:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 3336:             my $target = $filepath.'/'.$file;
 3337:             if (-e $source) {
 3338:                 my @info = stat($source);
 3339:                 if ($info[9] eq $env{'form.timestamp'}) {   
 3340:                     unless (&File::Copy::move($source,$target)) {
 3341:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 3342:                         return "Moving from $source failed";
 3343:                     }
 3344:                 } else {
 3345:                     return "Temporary file: $source had unexpected date/time for last modification";
 3346:                 }
 3347:             } else {
 3348:                 return "Temporary file: $source missing";
 3349:             }
 3350:         } elsif (!print FH ($env{'form.'.$formname})) {
 3351: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 3352: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 3353: 	    return '/adm/notfound.html';
 3354: 	}
 3355: 	close(FH);
 3356:         if ($resizewidth && $resizeheight) {
 3357:             my $mm = new File::MMagic;
 3358:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 3359:             if ($mime_type =~ m{^image/}) {
 3360: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 3361:             }  
 3362: 	}
 3363:     }
 3364:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 3365:         if (ref($mimetype)) {
 3366:             if ($$mimetype eq '') {
 3367:                 my $mm = new File::MMagic;
 3368:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 3369:                 $$mimetype = $type;
 3370:             }
 3371:         }
 3372:     }
 3373:     if ($parser eq 'parse') {
 3374:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 3375:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 3376:                                                        $allfiles,$codebase);
 3377:             unless ($parse_result eq 'ok') {
 3378:                 &logthis('Failed to parse '.$filepath.$file.
 3379: 	   	         ' for embedded media: '.$parse_result); 
 3380:             }
 3381:         }
 3382:     }
 3383:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 3384:         my $input = $filepath.'/'.$file;
 3385:         my $output = $filepath.'/'.'tn-'.$file;
 3386:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 3387:         system("convert -sample $thumbsize $input $output");
 3388:         if (-e $filepath.'/'.'tn-'.$file) {
 3389:             $fetchthumb  = 1; 
 3390:         }
 3391:     }
 3392:  
 3393: # Notify homeserver to grep it
 3394: #
 3395:     my $docuhome=&homeserver($docuname,$docudom);	
 3396:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 3397:     if ($fetchresult eq 'ok') {
 3398:         if ($fetchthumb) {
 3399:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 3400:             if ($thumbresult ne 'ok') {
 3401:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 3402:                          $docuhome.': '.$thumbresult);
 3403:             }
 3404:         }
 3405: #
 3406: # Return the URL to it
 3407:         return '/uploaded/'.$path.$file;
 3408:     } else {
 3409:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 3410: 		 ': '.$fetchresult);
 3411:         return '/adm/notfound.html';
 3412:     }
 3413: }
 3414: 
 3415: sub extract_embedded_items {
 3416:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 3417:     my @state = ();
 3418:     my (%lastids,%related,%shockwave,%flashvars);
 3419:     my %javafiles = (
 3420:                       codebase => '',
 3421:                       code => '',
 3422:                       archive => ''
 3423:                     );
 3424:     my %mediafiles = (
 3425:                       src => '',
 3426:                       movie => '',
 3427:                      );
 3428:     my $p;
 3429:     if ($content) {
 3430:         $p = HTML::LCParser->new($content);
 3431:     } else {
 3432:         $p = HTML::LCParser->new($fullpath);
 3433:     }
 3434:     while (my $t=$p->get_token()) {
 3435: 	if ($t->[0] eq 'S') {
 3436: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 3437: 	    push(@state, $tagname);
 3438:             if (lc($tagname) eq 'allow') {
 3439:                 &add_filetype($allfiles,$attr->{'src'},'src');
 3440:             }
 3441: 	    if (lc($tagname) eq 'img') {
 3442: 		&add_filetype($allfiles,$attr->{'src'},'src');
 3443: 	    }
 3444: 	    if (lc($tagname) eq 'a') {
 3445:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
 3446: 		    &add_filetype($allfiles,$attr->{'href'},'href');
 3447:                 }
 3448: 	    }
 3449:             if (lc($tagname) eq 'script') {
 3450:                 my $src;
 3451:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 3452:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 3453:                 } else {
 3454:                     if ($attr->{'src'} ne '') {
 3455:                         $src = $attr->{'src'};
 3456:                         &add_filetype($allfiles,$src,'src');
 3457:                     }
 3458:                 }
 3459:                 my $text = $p->get_trimmed_text();
 3460:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 3461:                     my @swfargs = split(/,/,$1);
 3462:                     foreach my $item (@swfargs) {
 3463:                         $item =~ s/["']//g;
 3464:                         $item =~ s/^\s+//;
 3465:                         $item =~ s/\s+$//;
 3466:                     }
 3467:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 3468:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 3469:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 3470:                         } else {
 3471:                             $related{$swfargs[0]} = [$swfargs[2]];
 3472:                         }
 3473:                     }
 3474:                 }
 3475:             }
 3476:             if (lc($tagname) eq 'link') {
 3477:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 3478:                     &add_filetype($allfiles,$attr->{'href'},'href');
 3479:                 }
 3480:             }
 3481: 	    if (lc($tagname) eq 'object' ||
 3482: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 3483: 		foreach my $item (keys(%javafiles)) {
 3484: 		    $javafiles{$item} = '';
 3485: 		}
 3486:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 3487:                     $lastids{lc($tagname)} = $attr->{'id'};
 3488:                 }
 3489: 	    }
 3490: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 3491: 		my $name = lc($attr->{'name'});
 3492: 		foreach my $item (keys(%javafiles)) {
 3493: 		    if ($name eq $item) {
 3494: 			$javafiles{$item} = $attr->{'value'};
 3495: 			last;
 3496: 		    }
 3497: 		}
 3498:                 my $pathfrom;
 3499: 		foreach my $item (keys(%mediafiles)) {
 3500: 		    if ($name eq $item) {
 3501:                         $pathfrom = $attr->{'value'};
 3502:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 3503: 			&add_filetype($allfiles,$pathfrom,$name);
 3504: 			last;
 3505: 		    }
 3506: 		}
 3507:                 if ($name eq 'flashvars') {
 3508:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 3509:                 }
 3510:                 if ($pathfrom ne '') {
 3511:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 3512:                                          $pathfrom);
 3513:                 }
 3514: 	    }
 3515: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 3516: 		foreach my $item (keys(%javafiles)) {
 3517: 		    if ($attr->{$item}) {
 3518: 			$javafiles{$item} = $attr->{$item};
 3519: 			last;
 3520: 		    }
 3521: 		}
 3522: 		foreach my $item (keys(%mediafiles)) {
 3523: 		    if ($attr->{$item}) {
 3524: 			&add_filetype($allfiles,$attr->{$item},$item);
 3525: 			last;
 3526: 		    }
 3527: 		}
 3528:                 if (lc($tagname) eq 'embed') {
 3529:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 3530:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 3531:                                              $attr->{'src'});
 3532:                     }
 3533:                 }
 3534: 	    }
 3535:             if (lc($tagname) eq 'iframe') {
 3536:                 my $src = $attr->{'src'} ;
 3537:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
 3538:                     &add_filetype($allfiles,$src,'src');
 3539:                 } elsif ($src =~ m{^/}) {
 3540:                     if ($env{'request.course.id'}) {
 3541:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3542:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3543:                         my $url = &hreflocation('',$fullpath);
 3544:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
 3545:                             my $relpath = $1;
 3546:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
 3547:                                 &add_filetype($allfiles,$1,'src');
 3548:                             }
 3549:                         }
 3550:                     }
 3551:                 }
 3552:             }
 3553:             if ($t->[4] =~ m{/>$}) {
 3554:                 pop(@state);
 3555:             }
 3556: 	} elsif ($t->[0] eq 'E') {
 3557: 	    my ($tagname) = ($t->[1]);
 3558: 	    if ($javafiles{'codebase'} ne '') {
 3559: 		$javafiles{'codebase'} .= '/';
 3560: 	    }  
 3561: 	    if (lc($tagname) eq 'applet' ||
 3562: 		lc($tagname) eq 'object' ||
 3563: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 3564: 		) {
 3565: 		foreach my $item (keys(%javafiles)) {
 3566: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 3567: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 3568: 			&add_filetype($allfiles,$file,$item);
 3569: 		    }
 3570: 		}
 3571: 	    } 
 3572: 	    pop @state;
 3573: 	}
 3574:     }
 3575:     foreach my $id (sort(keys(%flashvars))) {
 3576:         if ($shockwave{$id} ne '') {
 3577:             my @pairs = split(/\&/,$flashvars{$id});
 3578:             foreach my $pair (@pairs) {
 3579:                 my ($key,$value) = split(/\=/,$pair);
 3580:                 if ($key eq 'thumb') {
 3581:                     &add_filetype($allfiles,$value,$key);
 3582:                 } elsif ($key eq 'content') {
 3583:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 3584:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 3585:                     if ($ext ne '') {
 3586:                         &add_filetype($allfiles,$path.$value,$ext);
 3587:                     }
 3588:                 }
 3589:             }
 3590:         }
 3591:     }
 3592:     return 'ok';
 3593: }
 3594: 
 3595: sub add_filetype {
 3596:     my ($allfiles,$file,$type)=@_;
 3597:     if (exists($allfiles->{$file})) {
 3598: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 3599: 	    push(@{$allfiles->{$file}}, &escape($type));
 3600: 	}
 3601:     } else {
 3602: 	@{$allfiles->{$file}} = (&escape($type));
 3603:     }
 3604: }
 3605: 
 3606: sub embedded_dependency {
 3607:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 3608:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 3609:         if (($identifier ne '') &&
 3610:             (ref($related->{$identifier}) eq 'ARRAY') &&
 3611:             ($pathfrom ne '')) {
 3612:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 3613:             foreach my $dep (@{$related->{$identifier}}) {
 3614:                 &add_filetype($allfiles,$path.$dep,'object');
 3615:             }
 3616:         }
 3617:     }
 3618:     return;
 3619: }
 3620: 
 3621: sub removeuploadedurl {
 3622:     my ($url)=@_;	
 3623:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 3624:     return &removeuserfile($uname,$udom,$fname);
 3625: }
 3626: 
 3627: sub removeuserfile {
 3628:     my ($docuname,$docudom,$fname)=@_;
 3629:     my $home=&homeserver($docuname,$docudom);    
 3630:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 3631:     if ($result eq 'ok') {	
 3632:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 3633:             my $metafile = $fname.'.meta';
 3634:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 3635: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 3636:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 3637:             my $sqlresult = 
 3638:                 &update_portfolio_table($docuname,$docudom,$file,
 3639:                                         'portfolio_metadata',$group,
 3640:                                         'delete');
 3641:         }
 3642:     }
 3643:     return $result;
 3644: }
 3645: 
 3646: sub mkdiruserfile {
 3647:     my ($docuname,$docudom,$dir)=@_;
 3648:     my $home=&homeserver($docuname,$docudom);
 3649:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 3650: }
 3651: 
 3652: sub renameuserfile {
 3653:     my ($docuname,$docudom,$old,$new)=@_;
 3654:     my $home=&homeserver($docuname,$docudom);
 3655:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 3656:                         &escape("$old").':'.&escape("$new"),$home);
 3657:     if ($result eq 'ok') {
 3658:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 3659:             my $oldmeta = $old.'.meta';
 3660:             my $newmeta = $new.'.meta';
 3661:             my $metaresult = 
 3662:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 3663: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 3664:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 3665:             my $sqlresult = 
 3666:                 &update_portfolio_table($docuname,$docudom,$file,
 3667:                                         'portfolio_metadata',$group,
 3668:                                         'delete');
 3669:         }
 3670:     }
 3671:     return $result;
 3672: }
 3673: 
 3674: # ------------------------------------------------------------------------- Log
 3675: 
 3676: sub log {
 3677:     my ($dom,$nam,$hom,$what)=@_;
 3678:     return critical("log:$dom:$nam:$what",$hom);
 3679: }
 3680: 
 3681: # ------------------------------------------------------------------ Course Log
 3682: #
 3683: # This routine flushes several buffers of non-mission-critical nature
 3684: #
 3685: 
 3686: sub flushcourselogs {
 3687:     &logthis('Flushing log buffers');
 3688: #
 3689: # course logs
 3690: # This is a log of all transactions in a course, which can be used
 3691: # for data mining purposes
 3692: #
 3693: # It also collects the courseid database, which lists last transaction
 3694: # times and course titles for all courseids
 3695: #
 3696:     my %courseidbuffer=();
 3697:     foreach my $crsid (keys(%courselogs)) {
 3698:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 3699: 		          &escape($courselogs{$crsid}),
 3700: 		          $coursehombuf{$crsid}) eq 'ok') {
 3701: 	    delete $courselogs{$crsid};
 3702:         } else {
 3703:             &logthis('Failed to flush log buffer for '.$crsid);
 3704:             if (length($courselogs{$crsid})>40000) {
 3705:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 3706:                         " exceeded maximum size, deleting.</font>");
 3707:                delete $courselogs{$crsid};
 3708:             }
 3709:         }
 3710:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 3711:             'description' => $coursedescrbuf{$crsid},
 3712:             'inst_code'    => $courseinstcodebuf{$crsid},
 3713:             'type'        => $coursetypebuf{$crsid},
 3714:             'owner'       => $courseownerbuf{$crsid},
 3715:         };
 3716:     }
 3717: #
 3718: # Write course id database (reverse lookup) to homeserver of courses 
 3719: # Is used in pickcourse
 3720: #
 3721:     foreach my $crs_home (keys(%courseidbuffer)) {
 3722:         my $response = &courseidput(&host_domain($crs_home),
 3723:                                     $courseidbuffer{$crs_home},
 3724:                                     $crs_home,'timeonly');
 3725:     }
 3726: #
 3727: # File accesses
 3728: # Writes to the dynamic metadata of resources to get hit counts, etc.
 3729: #
 3730:     foreach my $entry (keys(%accesshash)) {
 3731:         if ($entry =~ /___count$/) {
 3732:             my ($dom,$name);
 3733:             ($dom,$name,undef)=
 3734: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 3735:             if (! defined($dom) || $dom eq '' || 
 3736:                 ! defined($name) || $name eq '') {
 3737:                 my $cid = $env{'request.course.id'};
 3738:                 $dom  = $env{'request.'.$cid.'.domain'};
 3739:                 $name = $env{'request.'.$cid.'.num'};
 3740:             }
 3741:             my $value = $accesshash{$entry};
 3742:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 3743:             my %temphash=($url => $value);
 3744:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 3745:             if ($result eq 'ok') {
 3746:                 delete $accesshash{$entry};
 3747:             }
 3748:         } else {
 3749:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 3750:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 3751:             my %temphash=($entry => $accesshash{$entry});
 3752:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 3753:                 delete $accesshash{$entry};
 3754:             }
 3755:         }
 3756:     }
 3757: #
 3758: # Roles
 3759: # Reverse lookup of user roles for course faculty/staff and co-authorship
 3760: #
 3761:     foreach my $entry (keys(%userrolehash)) {
 3762:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 3763: 	    split(/\:/,$entry);
 3764:         if (&Apache::lonnet::put('nohist_userroles',
 3765:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 3766:                 $rudom,$runame) eq 'ok') {
 3767: 	    delete $userrolehash{$entry};
 3768:         }
 3769:     }
 3770: #
 3771: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 3772: #
 3773:     my %domrolebuffer = ();
 3774:     foreach my $entry (keys(%domainrolehash)) {
 3775:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 3776:         if ($domrolebuffer{$rudom}) {
 3777:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 3778:                       '='.&escape($domainrolehash{$entry});
 3779:         } else {
 3780:             $domrolebuffer{$rudom}.=&escape($entry).
 3781:                       '='.&escape($domainrolehash{$entry});
 3782:         }
 3783:         delete $domainrolehash{$entry};
 3784:     }
 3785:     foreach my $dom (keys(%domrolebuffer)) {
 3786: 	my %servers = &get_servers($dom,'library');
 3787: 	foreach my $tryserver (keys(%servers)) {
 3788: 	    unless (&reply('domroleput:'.$dom.':'.
 3789: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 3790: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 3791: 	    }
 3792:         }
 3793:     }
 3794:     $dumpcount++;
 3795: }
 3796: 
 3797: sub courselog {
 3798:     my $what=shift;
 3799:     $what=time.':'.$what;
 3800:     unless ($env{'request.course.id'}) { return ''; }
 3801:     $coursedombuf{$env{'request.course.id'}}=
 3802:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 3803:     $coursenumbuf{$env{'request.course.id'}}=
 3804:        $env{'course.'.$env{'request.course.id'}.'.num'};
 3805:     $coursehombuf{$env{'request.course.id'}}=
 3806:        $env{'course.'.$env{'request.course.id'}.'.home'};
 3807:     $coursedescrbuf{$env{'request.course.id'}}=
 3808:        $env{'course.'.$env{'request.course.id'}.'.description'};
 3809:     $courseinstcodebuf{$env{'request.course.id'}}=
 3810:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 3811:     $courseownerbuf{$env{'request.course.id'}}=
 3812:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 3813:     $coursetypebuf{$env{'request.course.id'}}=
 3814:        $env{'course.'.$env{'request.course.id'}.'.type'};
 3815:     if (defined $courselogs{$env{'request.course.id'}}) {
 3816: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 3817:     } else {
 3818: 	$courselogs{$env{'request.course.id'}}.=$what;
 3819:     }
 3820:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 3821: 	&flushcourselogs();
 3822:     }
 3823: }
 3824: 
 3825: sub courseacclog {
 3826:     my $fnsymb=shift;
 3827:     unless ($env{'request.course.id'}) { return ''; }
 3828:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 3829:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 3830:         $what.=':POST';
 3831:         # FIXME: Probably ought to escape things....
 3832: 	foreach my $key (keys(%env)) {
 3833:             if ($key=~/^form\.(.*)/) {
 3834:                 my $formitem = $1;
 3835:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 3836:                     $what.=':'.$formitem.'='.$env{$key};
 3837:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 3838:                     $what.=':'.$formitem.'='.$env{$key};
 3839:                 }
 3840:             }
 3841:         }
 3842:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 3843:         # FIXME: We should not be depending on a form parameter that someone
 3844:         # editing lonsearchcat.pm might change in the future.
 3845:         if ($env{'form.phase'} eq 'course_search') {
 3846:             $what.= ':POST';
 3847:             # FIXME: Probably ought to escape things....
 3848:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 3849:                                  'crsdiscuss') {
 3850:                 $what.=':'.$element.'='.$env{'form.'.$element};
 3851:             }
 3852:         }
 3853:     }
 3854:     &courselog($what);
 3855: }
 3856: 
 3857: sub countacc {
 3858:     my $url=&declutter(shift);
 3859:     return if (! defined($url) || $url eq '');
 3860:     unless ($env{'request.course.id'}) { return ''; }
 3861: #
 3862: # Mark that this url was used in this course
 3863: #
 3864:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 3865: #
 3866: # Increase the access count for this resource in this child process
 3867: #
 3868:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 3869:     $accesshash{$key}++;
 3870: }
 3871: 
 3872: sub linklog {
 3873:     my ($from,$to)=@_;
 3874:     $from=&declutter($from);
 3875:     $to=&declutter($to);
 3876:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 3877:     $accesshash{$to.'___'.$from.'___goto'}=1;
 3878: }
 3879: 
 3880: sub statslog {
 3881:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 3882:     if ($users<2) { return; }
 3883:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 3884:             'course'       => $env{'request.course.id'},
 3885:             'sections'     => '"all"',
 3886:             'num_students' => $users,
 3887:             'part'         => $part,
 3888:             'symb'         => $symb,
 3889:             'mean_tries'   => $av_attempts,
 3890:             'deg_of_diff'  => $degdiff});
 3891:     foreach my $key (keys(%dynstore)) {
 3892:         $accesshash{$key}=$dynstore{$key};
 3893:     }
 3894: }
 3895:   
 3896: sub userrolelog {
 3897:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 3898:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
 3899:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 3900:        $userrolehash
 3901:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 3902:                     =$tend.':'.$tstart;
 3903:     }
 3904:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
 3905:        $userrolehash
 3906:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 3907:                     =$tend.':'.$tstart;
 3908:     }
 3909:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
 3910:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 3911:        $domainrolehash
 3912:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 3913:                     = $tend.':'.$tstart;
 3914:     }
 3915: }
 3916: 
 3917: sub courserolelog {
 3918:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 3919:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 3920:         my $cdom = $1;
 3921:         my $cnum = $2;
 3922:         my $sec = $3;
 3923:         my $namespace = 'rolelog';
 3924:         my %storehash = (
 3925:                            role    => $trole,
 3926:                            start   => $tstart,
 3927:                            end     => $tend,
 3928:                            selfenroll => $selfenroll,
 3929:                            context    => $context,
 3930:                         );
 3931:         if ($trole eq 'gr') {
 3932:             $namespace = 'groupslog';
 3933:             $storehash{'group'} = $sec;
 3934:         } else {
 3935:             $storehash{'section'} = $sec;
 3936:         }
 3937:         &write_log('course',$namespace,\%storehash,$delflag,$username,
 3938:                    $domain,$cnum,$cdom);
 3939:         if (($trole ne 'st') || ($sec ne '')) {
 3940:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 3941:         }
 3942:     }
 3943:     return;
 3944: }
 3945: 
 3946: sub domainrolelog {
 3947:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 3948:     if ($area =~ m{^/($match_domain)/$}) {
 3949:         my $cdom = $1;
 3950:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
 3951:         my $namespace = 'rolelog';
 3952:         my %storehash = (
 3953:                            role    => $trole,
 3954:                            start   => $tstart,
 3955:                            end     => $tend,
 3956:                            context => $context,
 3957:                         );
 3958:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
 3959:                    $domain,$domconfiguser,$cdom);
 3960:     }
 3961:     return;
 3962: 
 3963: }
 3964: 
 3965: sub coauthorrolelog {
 3966:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 3967:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
 3968:         my $audom = $1;
 3969:         my $auname = $2;
 3970:         my $namespace = 'rolelog';
 3971:         my %storehash = (
 3972:                            role    => $trole,
 3973:                            start   => $tstart,
 3974:                            end     => $tend,
 3975:                            context => $context,
 3976:                         );
 3977:         &write_log('author',$namespace,\%storehash,$delflag,$username,
 3978:                    $domain,$auname,$audom);
 3979:     }
 3980:     return;
 3981: }
 3982: 
 3983: sub get_course_adv_roles {
 3984:     my ($cid,$codes) = @_;
 3985:     $cid=$env{'request.course.id'} unless (defined($cid));
 3986:     my %coursehash=&coursedescription($cid);
 3987:     my $crstype = &Apache::loncommon::course_type($cid);
 3988:     my %nothide=();
 3989:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3990:         if ($user !~ /:/) {
 3991: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 3992:         } else {
 3993:             $nothide{$user}=1;
 3994:         }
 3995:     }
 3996:     my @possdoms = ($coursehash{'domain'});
 3997:     if ($coursehash{'checkforpriv'}) {
 3998:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 3999:     }
 4000:     my %returnhash=();
 4001:     my %dumphash=
 4002:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 4003:     my $now=time;
 4004:     my %privileged;
 4005:     foreach my $entry (keys(%dumphash)) {
 4006: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 4007:         if (($tstart) && ($tstart<0)) { next; }
 4008:         if (($tend) && ($tend<$now)) { next; }
 4009:         if (($tstart) && ($now<$tstart)) { next; }
 4010:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 4011: 	if ($username eq '' || $domain eq '') { next; }
 4012:         if ((&privileged($username,$domain,\@possdoms)) &&
 4013:             (!$nothide{$username.':'.$domain})) { next; }
 4014: 	if ($role eq 'cr') { next; }
 4015:         if ($codes) {
 4016:             if ($section) { $role .= ':'.$section; }
 4017:             if ($returnhash{$role}) {
 4018:                 $returnhash{$role}.=','.$username.':'.$domain;
 4019:             } else {
 4020:                 $returnhash{$role}=$username.':'.$domain;
 4021:             }
 4022:         } else {
 4023:             my $key=&plaintext($role,$crstype);
 4024:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 4025:             if ($returnhash{$key}) {
 4026: 	        $returnhash{$key}.=','.$username.':'.$domain;
 4027:             } else {
 4028:                 $returnhash{$key}=$username.':'.$domain;
 4029:             }
 4030:         }
 4031:     }
 4032:     return %returnhash;
 4033: }
 4034: 
 4035: sub get_my_roles {
 4036:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 4037:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 4038:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 4039:     my (%dumphash,%nothide);
 4040:     if ($context eq 'userroles') {
 4041:         %dumphash = &dump('roles',$udom,$uname);
 4042:     } else {
 4043:         %dumphash = &dump('nohist_userroles',$udom,$uname);
 4044:         if ($hidepriv) {
 4045:             my %coursehash=&coursedescription($udom.'_'.$uname);
 4046:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 4047:                 if ($user !~ /:/) {
 4048:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 4049:                 } else {
 4050:                     $nothide{$user} = 1;
 4051:                 }
 4052:             }
 4053:         }
 4054:     }
 4055:     my %returnhash=();
 4056:     my $now=time;
 4057:     my %privileged;
 4058:     foreach my $entry (keys(%dumphash)) {
 4059:         my ($role,$tend,$tstart);
 4060:         if ($context eq 'userroles') {
 4061:             next if ($entry =~ /^rolesdef/);
 4062: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 4063:         } else {
 4064:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 4065:         }
 4066:         if (($tstart) && ($tstart<0)) { next; }
 4067:         my $status = 'active';
 4068:         if (($tend) && ($tend<=$now)) {
 4069:             $status = 'previous';
 4070:         } 
 4071:         if (($tstart) && ($now<$tstart)) {
 4072:             $status = 'future';
 4073:         }
 4074:         if (ref($types) eq 'ARRAY') {
 4075:             if (!grep(/^\Q$status\E$/,@{$types})) {
 4076:                 next;
 4077:             } 
 4078:         } else {
 4079:             if ($status ne 'active') {
 4080:                 next;
 4081:             }
 4082:         }
 4083:         my ($rolecode,$username,$domain,$section,$area);
 4084:         if ($context eq 'userroles') {
 4085:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
 4086:             (undef,$domain,$username,$section) = split(/\//,$area);
 4087:         } else {
 4088:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 4089:         }
 4090:         if (ref($roledoms) eq 'ARRAY') {
 4091:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 4092:                 next;
 4093:             }
 4094:         }
 4095:         if (ref($roles) eq 'ARRAY') {
 4096:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 4097:                 if ($role =~ /^cr\//) {
 4098:                     if (!grep(/^cr$/,@{$roles})) {
 4099:                         next;
 4100:                     }
 4101:                 } elsif ($role =~ /^gr\//) {
 4102:                     if (!grep(/^gr$/,@{$roles})) {
 4103:                         next;
 4104:                     }
 4105:                 } else {
 4106:                     next;
 4107:                 }
 4108:             }
 4109:         }
 4110:         if ($hidepriv) {
 4111:             my @privroles = ('dc','su');
 4112:             if ($context eq 'userroles') {
 4113:                 next if (grep(/^\Q$role\E$/,@privroles));
 4114:             } else {
 4115:                 my $possdoms = [$domain];
 4116:                 if (ref($roledoms) eq 'ARRAY') {
 4117:                    push(@{$possdoms},@{$roledoms});
 4118:                 }
 4119:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
 4120:                     if (!$nothide{$username.':'.$domain}) {
 4121:                         next;
 4122:                     }
 4123:                 }
 4124:             }
 4125:         }
 4126:         if ($withsec) {
 4127:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 4128:                 $tstart.':'.$tend;
 4129:         } else {
 4130:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 4131:         }
 4132:     }
 4133:     return %returnhash;
 4134: }
 4135: 
 4136: # ----------------------------------------------------- Frontpage Announcements
 4137: #
 4138: #
 4139: 
 4140: sub postannounce {
 4141:     my ($server,$text)=@_;
 4142:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 4143:     unless ($text=~/\w/) { $text=''; }
 4144:     return &reply('setannounce:'.&escape($text),$server);
 4145: }
 4146: 
 4147: sub getannounce {
 4148: 
 4149:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 4150: 	my $announcement='';
 4151: 	while (my $line = <$fh>) { $announcement .= $line; }
 4152: 	close($fh);
 4153: 	if ($announcement=~/\w/) { 
 4154: 	    return 
 4155:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 4156:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 4157: 	} else {
 4158: 	    return '';
 4159: 	}
 4160:     } else {
 4161: 	return '';
 4162:     }
 4163: }
 4164: 
 4165: # ---------------------------------------------------------- Course ID routines
 4166: # Deal with domain's nohist_courseid.db files
 4167: #
 4168: 
 4169: sub courseidput {
 4170:     my ($domain,$storehash,$coursehome,$caller) = @_;
 4171:     return unless (ref($storehash) eq 'HASH');
 4172:     my $outcome;
 4173:     if ($caller eq 'timeonly') {
 4174:         my $cids = '';
 4175:         foreach my $item (keys(%$storehash)) {
 4176:             $cids.=&escape($item).'&';
 4177:         }
 4178:         $cids=~s/\&$//;
 4179:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 4180:                           $coursehome);       
 4181:     } else {
 4182:         my $items = '';
 4183:         foreach my $item (keys(%$storehash)) {
 4184:             $items.= &escape($item).'='.
 4185:                      &freeze_escape($$storehash{$item}).'&';
 4186:         }
 4187:         $items=~s/\&$//;
 4188:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 4189:                           $coursehome);
 4190:     }
 4191:     if ($outcome eq 'unknown_cmd') {
 4192:         my $what;
 4193:         foreach my $cid (keys(%$storehash)) {
 4194:             $what .= &escape($cid).'=';
 4195:             foreach my $item ('description','inst_code','owner','type') {
 4196:                 $what .= &escape($storehash->{$cid}{$item}).':';
 4197:             }
 4198:             $what =~ s/\:$/&/;
 4199:         }
 4200:         $what =~ s/\&$//;  
 4201:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 4202:     } else {
 4203:         return $outcome;
 4204:     }
 4205: }
 4206: 
 4207: sub courseiddump {
 4208:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 4209:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 4210:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 4211:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
 4212:         $hasuniquecode)=@_;
 4213:     my $as_hash = 1;
 4214:     my %returnhash;
 4215:     if (!$domfilter) { $domfilter=''; }
 4216:     my %libserv = &all_library();
 4217:     foreach my $tryserver (keys(%libserv)) {
 4218:         if ( (  $hostidflag == 1 
 4219: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 4220: 	     || (!defined($hostidflag)) ) {
 4221: 
 4222: 	    if (($domfilter eq '') ||
 4223: 		(&host_domain($tryserver) eq $domfilter)) {
 4224:                 my $rep;
 4225:                 if (grep { $_ eq $tryserver } &current_machine_ids()) {
 4226:                     $rep = &LONCAPA::Lond::dump_course_id_handler(
 4227:                         join(":", (&host_domain($tryserver), $sincefilter,
 4228:                                 &escape($descfilter), &escape($instcodefilter),
 4229:                                 &escape($ownerfilter), &escape($coursefilter),
 4230:                                 &escape($typefilter), &escape($regexp_ok),
 4231:                                 $as_hash, &escape($selfenrollonly),
 4232:                                 &escape($catfilter), $showhidden, $caller,
 4233:                                 &escape($cloner), &escape($cc_clone), $cloneonly,
 4234:                                 &escape($createdbefore), &escape($createdafter),
 4235:                                 &escape($creationcontext), $domcloner, $hasuniquecode)));
 4236:                 } else {
 4237:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
 4238:                              $sincefilter.':'.&escape($descfilter).':'.
 4239:                              &escape($instcodefilter).':'.&escape($ownerfilter).
 4240:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
 4241:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
 4242:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
 4243:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
 4244:                              &escape($cc_clone).':'.$cloneonly.':'.
 4245:                              &escape($createdbefore).':'.&escape($createdafter).':'.
 4246:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode,
 4247:                              $tryserver);
 4248:                 }
 4249: 
 4250:                 my @pairs=split(/\&/,$rep);
 4251:                 foreach my $item (@pairs) {
 4252:                     my ($key,$value)=split(/\=/,$item,2);
 4253:                     $key = &unescape($key);
 4254:                     next if ($key =~ /^error: 2 /);
 4255:                     my $result = &thaw_unescape($value);
 4256:                     if (ref($result) eq 'HASH') {
 4257:                         $returnhash{$key}=$result;
 4258:                     } else {
 4259:                         my @responses = split(/:/,$value);
 4260:                         my @items = ('description','inst_code','owner','type');
 4261:                         for (my $i=0; $i<@responses; $i++) {
 4262:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 4263:                         }
 4264:                     }
 4265:                 }
 4266:             }
 4267:         }
 4268:     }
 4269:     return %returnhash;
 4270: }
 4271: 
 4272: sub courselastaccess {
 4273:     my ($cdom,$cnum,$hostidref) = @_;
 4274:     my %returnhash;
 4275:     if ($cdom && $cnum) {
 4276:         my $chome = &homeserver($cnum,$cdom);
 4277:         if ($chome ne 'no_host') {
 4278:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 4279:             &extract_lastaccess(\%returnhash,$rep);
 4280:         }
 4281:     } else {
 4282:         if (!$cdom) { $cdom=''; }
 4283:         my %libserv = &all_library();
 4284:         foreach my $tryserver (keys(%libserv)) {
 4285:             if (ref($hostidref) eq 'ARRAY') {
 4286:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 4287:             } 
 4288:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 4289:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 4290:                 &extract_lastaccess(\%returnhash,$rep);
 4291:             }
 4292:         }
 4293:     }
 4294:     return %returnhash;
 4295: }
 4296: 
 4297: sub extract_lastaccess {
 4298:     my ($returnhash,$rep) = @_;
 4299:     if (ref($returnhash) eq 'HASH') {
 4300:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 4301:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 4302:                  $rep eq '') {
 4303:             my @pairs=split(/\&/,$rep);
 4304:             foreach my $item (@pairs) {
 4305:                 my ($key,$value)=split(/\=/,$item,2);
 4306:                 $key = &unescape($key);
 4307:                 next if ($key =~ /^error: 2 /);
 4308:                 $returnhash->{$key} = &thaw_unescape($value);
 4309:             }
 4310:         }
 4311:     }
 4312:     return;
 4313: }
 4314: 
 4315: # ---------------------------------------------------------- DC e-mail
 4316: 
 4317: sub dcmailput {
 4318:     my ($domain,$msgid,$message,$server)=@_;
 4319:     my $status = &Apache::lonnet::critical(
 4320:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 4321:        &escape($message),$server);
 4322:     return $status;
 4323: }
 4324: 
 4325: sub dcmaildump {
 4326:     my ($dom,$startdate,$enddate,$senders) = @_;
 4327:     my %returnhash=();
 4328: 
 4329:     if (defined(&domain($dom,'primary'))) {
 4330:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 4331:                                                          &escape($enddate).':';
 4332: 	my @esc_senders=map { &escape($_)} @$senders;
 4333: 	$cmd.=&escape(join('&',@esc_senders));
 4334: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 4335:             my ($key,$value) = split(/\=/,$line,2);
 4336:             if (($key) && ($value)) {
 4337:                 $returnhash{&unescape($key)} = &unescape($value);
 4338:             }
 4339:         }
 4340:     }
 4341:     return %returnhash;
 4342: }
 4343: # ---------------------------------------------------------- Domain roles
 4344: 
 4345: sub get_domain_roles {
 4346:     my ($dom,$roles,$startdate,$enddate)=@_;
 4347:     if ((!defined($startdate)) || ($startdate eq '')) {
 4348:         $startdate = '.';
 4349:     }
 4350:     if ((!defined($enddate)) || ($enddate eq '')) {
 4351:         $enddate = '.';
 4352:     }
 4353:     my $rolelist;
 4354:     if (ref($roles) eq 'ARRAY') {
 4355:         $rolelist = join('&',@{$roles});
 4356:     }
 4357:     my %personnel = ();
 4358: 
 4359:     my %servers = &get_servers($dom,'library');
 4360:     foreach my $tryserver (keys(%servers)) {
 4361: 	%{$personnel{$tryserver}}=();
 4362: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 4363: 					    &escape($startdate).':'.
 4364: 					    &escape($enddate).':'.
 4365: 					    &escape($rolelist), $tryserver))) {
 4366: 	    my ($key,$value) = split(/\=/,$line,2);
 4367: 	    if (($key) && ($value)) {
 4368: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 4369: 	    }
 4370: 	}
 4371:     }
 4372:     return %personnel;
 4373: }
 4374: 
 4375: # ----------------------------------------------------------- Interval timing 
 4376: 
 4377: {
 4378: # Caches needed for speedup of navmaps
 4379: # We don't want to cache this for very long at all (5 seconds at most)
 4380: # 
 4381: # The user for whom we cache
 4382: my $cachedkey='';
 4383: # The cached times for this user
 4384: my %cachedtimes=();
 4385: # When this was last done
 4386: my $cachedtime=();
 4387: 
 4388: sub load_all_first_access {
 4389:     my ($uname,$udom)=@_;
 4390:     if (($cachedkey eq $uname.':'.$udom) &&
 4391:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
 4392:         return;
 4393:     }
 4394:     $cachedtime=time;
 4395:     $cachedkey=$uname.':'.$udom;
 4396:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 4397: }
 4398: 
 4399: sub get_first_access {
 4400:     my ($type,$argsymb,$argmap)=@_;
 4401:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 4402:     if ($argsymb) { $symb=$argsymb; }
 4403:     my ($map,$id,$res)=&decode_symb($symb);
 4404:     if ($argmap) { $map = $argmap; }
 4405:     if ($type eq 'course') {
 4406: 	$res='course';
 4407:     } elsif ($type eq 'map') {
 4408: 	$res=&symbread($map);
 4409:     } else {
 4410: 	$res=$symb;
 4411:     }
 4412:     &load_all_first_access($uname,$udom);
 4413:     return $cachedtimes{"$courseid\0$res"};
 4414: }
 4415: 
 4416: sub set_first_access {
 4417:     my ($type,$interval)=@_;
 4418:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 4419:     my ($map,$id,$res)=&decode_symb($symb);
 4420:     if ($type eq 'course') {
 4421: 	$res='course';
 4422:     } elsif ($type eq 'map') {
 4423: 	$res=&symbread($map);
 4424:     } else {
 4425: 	$res=$symb;
 4426:     }
 4427:     $cachedkey='';
 4428:     my $firstaccess=&get_first_access($type,$symb,$map);
 4429:     if (!$firstaccess) {
 4430:         my $start = time;
 4431: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 4432:                           $udom,$uname);
 4433:         if ($putres eq 'ok') {
 4434:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 4435:                  $udom,$uname); 
 4436:             &appenv(
 4437:                      {
 4438:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 4439:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 4440:                      }
 4441:                   );
 4442:         }
 4443:         return $putres;
 4444:     }
 4445:     return 'already_set';
 4446: }
 4447: }
 4448: 
 4449: sub checkout {
 4450:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
 4451:     my $now=time;
 4452:     my $lonhost=$perlvar{'lonHostID'};
 4453:     my $infostr=&escape(
 4454:                  'CHECKOUTTOKEN&'.
 4455:                  $tuname.'&'.
 4456:                  $tudom.'&'.
 4457:                  $tcrsid.'&'.
 4458:                  $symb.'&'.
 4459:                  $now.'&'.$ENV{'REMOTE_ADDR'});
 4460:     my $token=&reply('tmpput:'.$infostr,$lonhost);
 4461:     if ($token=~/^error\:/) {
 4462:         &logthis("<font color=\"blue\">WARNING: ".
 4463:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
 4464:                  "</font>");
 4465:         return '';
 4466:     }
 4467: 
 4468:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
 4469:     $token=~tr/a-z/A-Z/;
 4470: 
 4471:     my %infohash=('resource.0.outtoken' => $token,
 4472:                   'resource.0.checkouttime' => $now,
 4473:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
 4474: 
 4475:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 4476:        return '';
 4477:     } else {
 4478:         &logthis("<font color=\"blue\">WARNING: ".
 4479:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
 4480:                  "</font>");
 4481:     }
 4482: 
 4483:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 4484:                          &escape('Checkout '.$infostr.' - '.
 4485:                                                  $token)) ne 'ok') {
 4486:         return '';
 4487:     } else {
 4488:         &logthis("<font color=\"blue\">WARNING: ".
 4489:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
 4490:                  "</font>");
 4491:     }
 4492:     return $token;
 4493: }
 4494: 
 4495: # ------------------------------------------------------------ Check in an item
 4496: 
 4497: sub checkin {
 4498:     my $token=shift;
 4499:     my $now=time;
 4500:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
 4501:     $lonhost=~tr/A-Z/a-z/;
 4502:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
 4503:     $dtoken=~s/\W/\_/g;
 4504:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
 4505:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
 4506: 
 4507:     unless (($tuname) && ($tudom)) {
 4508:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
 4509:         return '';
 4510:     }
 4511: 
 4512:     unless (&allowed('mgr',$tcrsid)) {
 4513:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
 4514:                  $env{'user.name'}.' - '.$env{'user.domain'});
 4515:         return '';
 4516:     }
 4517: 
 4518:     my %infohash=('resource.0.intoken' => $token,
 4519:                   'resource.0.checkintime' => $now,
 4520:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
 4521: 
 4522:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 4523:        return '';
 4524:     }
 4525: 
 4526:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 4527:                          &escape('Checkin - '.$token)) ne 'ok') {
 4528:         return '';
 4529:     }
 4530: 
 4531:     return ($symb,$tuname,$tudom,$tcrsid);
 4532: }
 4533: 
 4534: # --------------------------------------------- Set Expire Date for Spreadsheet
 4535: 
 4536: sub expirespread {
 4537:     my ($uname,$udom,$stype,$usymb)=@_;
 4538:     my $cid=$env{'request.course.id'}; 
 4539:     if ($cid) {
 4540:        my $now=time;
 4541:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 4542:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 4543:                             $env{'course.'.$cid.'.num'}.
 4544: 	        	    ':nohist_expirationdates:'.
 4545:                             &escape($key).'='.$now,
 4546:                             $env{'course.'.$cid.'.home'})
 4547:     }
 4548:     return 'ok';
 4549: }
 4550: 
 4551: # ----------------------------------------------------- Devalidate Spreadsheets
 4552: 
 4553: sub devalidate {
 4554:     my ($symb,$uname,$udom)=@_;
 4555:     my $cid=$env{'request.course.id'}; 
 4556:     if ($cid) {
 4557:         # delete the stored spreadsheets for
 4558:         # - the student level sheet of this user in course's homespace
 4559:         # - the assessment level sheet for this resource 
 4560:         #   for this user in user's homespace
 4561: 	# - current conditional state info
 4562: 	my $key=$uname.':'.$udom.':';
 4563:         my $status=
 4564: 	    &del('nohist_calculatedsheets',
 4565: 		 [$key.'studentcalc:'],
 4566: 		 $env{'course.'.$cid.'.domain'},
 4567: 		 $env{'course.'.$cid.'.num'})
 4568: 		.' '.
 4569: 	    &del('nohist_calculatedsheets_'.$cid,
 4570: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 4571:         unless ($status eq 'ok ok') {
 4572:            &logthis('Could not devalidate spreadsheet '.
 4573:                     $uname.' at '.$udom.' for '.
 4574: 		    $symb.': '.$status);
 4575:         }
 4576: 	&delenv('user.state.'.$cid);
 4577:     }
 4578: }
 4579: 
 4580: sub get_scalar {
 4581:     my ($string,$end) = @_;
 4582:     my $value;
 4583:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 4584: 	$value = $1;
 4585:     } elsif ($$string =~ s/^([^&]*?)&//) {
 4586: 	$value = $1;
 4587:     }
 4588:     return &unescape($value);
 4589: }
 4590: 
 4591: sub array2str {
 4592:   my (@array) = @_;
 4593:   my $result=&arrayref2str(\@array);
 4594:   $result=~s/^__ARRAY_REF__//;
 4595:   $result=~s/__END_ARRAY_REF__$//;
 4596:   return $result;
 4597: }
 4598: 
 4599: sub arrayref2str {
 4600:   my ($arrayref) = @_;
 4601:   my $result='__ARRAY_REF__';
 4602:   foreach my $elem (@$arrayref) {
 4603:     if(ref($elem) eq 'ARRAY') {
 4604:       $result.=&arrayref2str($elem).'&';
 4605:     } elsif(ref($elem) eq 'HASH') {
 4606:       $result.=&hashref2str($elem).'&';
 4607:     } elsif(ref($elem)) {
 4608:       #print("Got a ref of ".(ref($elem))." skipping.");
 4609:     } else {
 4610:       $result.=&escape($elem).'&';
 4611:     }
 4612:   }
 4613:   $result=~s/\&$//;
 4614:   $result .= '__END_ARRAY_REF__';
 4615:   return $result;
 4616: }
 4617: 
 4618: sub hash2str {
 4619:   my (%hash) = @_;
 4620:   my $result=&hashref2str(\%hash);
 4621:   $result=~s/^__HASH_REF__//;
 4622:   $result=~s/__END_HASH_REF__$//;
 4623:   return $result;
 4624: }
 4625: 
 4626: sub hashref2str {
 4627:   my ($hashref)=@_;
 4628:   my $result='__HASH_REF__';
 4629:   foreach my $key (sort(keys(%$hashref))) {
 4630:     if (ref($key) eq 'ARRAY') {
 4631:       $result.=&arrayref2str($key).'=';
 4632:     } elsif (ref($key) eq 'HASH') {
 4633:       $result.=&hashref2str($key).'=';
 4634:     } elsif (ref($key)) {
 4635:       $result.='=';
 4636:       #print("Got a ref of ".(ref($key))." skipping.");
 4637:     } else {
 4638: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 4639:     }
 4640: 
 4641:     if(ref($hashref->{$key}) eq 'ARRAY') {
 4642:       $result.=&arrayref2str($hashref->{$key}).'&';
 4643:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 4644:       $result.=&hashref2str($hashref->{$key}).'&';
 4645:     } elsif(ref($hashref->{$key})) {
 4646:        $result.='&';
 4647:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 4648:     } else {
 4649:       $result.=&escape($hashref->{$key}).'&';
 4650:     }
 4651:   }
 4652:   $result=~s/\&$//;
 4653:   $result .= '__END_HASH_REF__';
 4654:   return $result;
 4655: }
 4656: 
 4657: sub str2hash {
 4658:     my ($string)=@_;
 4659:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 4660:     return %$hash;
 4661: }
 4662: 
 4663: sub str2hashref {
 4664:   my ($string) = @_;
 4665: 
 4666:   my %hash;
 4667: 
 4668:   if($string !~ /^__HASH_REF__/) {
 4669:       if (! ($string eq '' || !defined($string))) {
 4670: 	  $hash{'error'}='Not hash reference';
 4671:       }
 4672:       return (\%hash, $string);
 4673:   }
 4674: 
 4675:   $string =~ s/^__HASH_REF__//;
 4676: 
 4677:   while($string !~ /^__END_HASH_REF__/) {
 4678:       #key
 4679:       my $key='';
 4680:       if($string =~ /^__HASH_REF__/) {
 4681:           ($key, $string)=&str2hashref($string);
 4682:           if(defined($key->{'error'})) {
 4683:               $hash{'error'}='Bad data';
 4684:               return (\%hash, $string);
 4685:           }
 4686:       } elsif($string =~ /^__ARRAY_REF__/) {
 4687:           ($key, $string)=&str2arrayref($string);
 4688:           if($key->[0] eq 'Array reference error') {
 4689:               $hash{'error'}='Bad data';
 4690:               return (\%hash, $string);
 4691:           }
 4692:       } else {
 4693:           $string =~ s/^(.*?)=//;
 4694: 	  $key=&unescape($1);
 4695:       }
 4696:       $string =~ s/^=//;
 4697: 
 4698:       #value
 4699:       my $value='';
 4700:       if($string =~ /^__HASH_REF__/) {
 4701:           ($value, $string)=&str2hashref($string);
 4702:           if(defined($value->{'error'})) {
 4703:               $hash{'error'}='Bad data';
 4704:               return (\%hash, $string);
 4705:           }
 4706:       } elsif($string =~ /^__ARRAY_REF__/) {
 4707:           ($value, $string)=&str2arrayref($string);
 4708:           if($value->[0] eq 'Array reference error') {
 4709:               $hash{'error'}='Bad data';
 4710:               return (\%hash, $string);
 4711:           }
 4712:       } else {
 4713: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 4714:       }
 4715:       $string =~ s/^&//;
 4716: 
 4717:       $hash{$key}=$value;
 4718:   }
 4719: 
 4720:   $string =~ s/^__END_HASH_REF__//;
 4721: 
 4722:   return (\%hash, $string);
 4723: }
 4724: 
 4725: sub str2array {
 4726:     my ($string)=@_;
 4727:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 4728:     return @$array;
 4729: }
 4730: 
 4731: sub str2arrayref {
 4732:   my ($string) = @_;
 4733:   my @array;
 4734: 
 4735:   if($string !~ /^__ARRAY_REF__/) {
 4736:       if (! ($string eq '' || !defined($string))) {
 4737: 	  $array[0]='Array reference error';
 4738:       }
 4739:       return (\@array, $string);
 4740:   }
 4741: 
 4742:   $string =~ s/^__ARRAY_REF__//;
 4743: 
 4744:   while($string !~ /^__END_ARRAY_REF__/) {
 4745:       my $value='';
 4746:       if($string =~ /^__HASH_REF__/) {
 4747:           ($value, $string)=&str2hashref($string);
 4748:           if(defined($value->{'error'})) {
 4749:               $array[0] ='Array reference error';
 4750:               return (\@array, $string);
 4751:           }
 4752:       } elsif($string =~ /^__ARRAY_REF__/) {
 4753:           ($value, $string)=&str2arrayref($string);
 4754:           if($value->[0] eq 'Array reference error') {
 4755:               $array[0] ='Array reference error';
 4756:               return (\@array, $string);
 4757:           }
 4758:       } else {
 4759: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 4760:       }
 4761:       $string =~ s/^&//;
 4762: 
 4763:       push(@array, $value);
 4764:   }
 4765: 
 4766:   $string =~ s/^__END_ARRAY_REF__//;
 4767: 
 4768:   return (\@array, $string);
 4769: }
 4770: 
 4771: # -------------------------------------------------------------------Temp Store
 4772: 
 4773: sub tmpreset {
 4774:   my ($symb,$namespace,$domain,$stuname) = @_;
 4775:   if (!$symb) {
 4776:     $symb=&symbread();
 4777:     if (!$symb) { $symb= $env{'request.url'}; }
 4778:   }
 4779:   $symb=escape($symb);
 4780: 
 4781:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4782:   $namespace=~s/\//\_/g;
 4783:   $namespace=~s/\W//g;
 4784: 
 4785:   if (!$domain) { $domain=$env{'user.domain'}; }
 4786:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4787:   if ($domain eq 'public' && $stuname eq 'public') {
 4788:       $stuname=$ENV{'REMOTE_ADDR'};
 4789:   }
 4790:   my $path=LONCAPA::tempdir();
 4791:   my %hash;
 4792:   if (tie(%hash,'GDBM_File',
 4793: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4794: 	  &GDBM_WRCREAT(),0640)) {
 4795:     foreach my $key (keys(%hash)) {
 4796:       if ($key=~ /:$symb/) {
 4797: 	delete($hash{$key});
 4798:       }
 4799:     }
 4800:   }
 4801: }
 4802: 
 4803: sub tmpstore {
 4804:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4805: 
 4806:   if (!$symb) {
 4807:     $symb=&symbread();
 4808:     if (!$symb) { $symb= $env{'request.url'}; }
 4809:   }
 4810:   $symb=escape($symb);
 4811: 
 4812:   if (!$namespace) {
 4813:     # I don't think we would ever want to store this for a course.
 4814:     # it seems this will only be used if we don't have a course.
 4815:     #$namespace=$env{'request.course.id'};
 4816:     #if (!$namespace) {
 4817:       $namespace=$env{'request.state'};
 4818:     #}
 4819:   }
 4820:   $namespace=~s/\//\_/g;
 4821:   $namespace=~s/\W//g;
 4822:   if (!$domain) { $domain=$env{'user.domain'}; }
 4823:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4824:   if ($domain eq 'public' && $stuname eq 'public') {
 4825:       $stuname=$ENV{'REMOTE_ADDR'};
 4826:   }
 4827:   my $now=time;
 4828:   my %hash;
 4829:   my $path=LONCAPA::tempdir();
 4830:   if (tie(%hash,'GDBM_File',
 4831: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4832: 	  &GDBM_WRCREAT(),0640)) {
 4833:     $hash{"version:$symb"}++;
 4834:     my $version=$hash{"version:$symb"};
 4835:     my $allkeys=''; 
 4836:     foreach my $key (keys(%$storehash)) {
 4837:       $allkeys.=$key.':';
 4838:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 4839:     }
 4840:     $hash{"$version:$symb:timestamp"}=$now;
 4841:     $allkeys.='timestamp';
 4842:     $hash{"$version:keys:$symb"}=$allkeys;
 4843:     if (untie(%hash)) {
 4844:       return 'ok';
 4845:     } else {
 4846:       return "error:$!";
 4847:     }
 4848:   } else {
 4849:     return "error:$!";
 4850:   }
 4851: }
 4852: 
 4853: # -----------------------------------------------------------------Temp Restore
 4854: 
 4855: sub tmprestore {
 4856:   my ($symb,$namespace,$domain,$stuname) = @_;
 4857: 
 4858:   if (!$symb) {
 4859:     $symb=&symbread();
 4860:     if (!$symb) { $symb= $env{'request.url'}; }
 4861:   }
 4862:   $symb=escape($symb);
 4863: 
 4864:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4865: 
 4866:   if (!$domain) { $domain=$env{'user.domain'}; }
 4867:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4868:   if ($domain eq 'public' && $stuname eq 'public') {
 4869:       $stuname=$ENV{'REMOTE_ADDR'};
 4870:   }
 4871:   my %returnhash;
 4872:   $namespace=~s/\//\_/g;
 4873:   $namespace=~s/\W//g;
 4874:   my %hash;
 4875:   my $path=LONCAPA::tempdir();
 4876:   if (tie(%hash,'GDBM_File',
 4877: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4878: 	  &GDBM_READER(),0640)) {
 4879:     my $version=$hash{"version:$symb"};
 4880:     $returnhash{'version'}=$version;
 4881:     my $scope;
 4882:     for ($scope=1;$scope<=$version;$scope++) {
 4883:       my $vkeys=$hash{"$scope:keys:$symb"};
 4884:       my @keys=split(/:/,$vkeys);
 4885:       my $key;
 4886:       $returnhash{"$scope:keys"}=$vkeys;
 4887:       foreach $key (@keys) {
 4888: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4889: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4890:       }
 4891:     }
 4892:     if (!(untie(%hash))) {
 4893:       return "error:$!";
 4894:     }
 4895:   } else {
 4896:     return "error:$!";
 4897:   }
 4898:   return %returnhash;
 4899: }
 4900: 
 4901: # ----------------------------------------------------------------------- Store
 4902: 
 4903: sub store {
 4904:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4905:     my $home='';
 4906: 
 4907:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4908: 
 4909:     $symb=&symbclean($symb);
 4910:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 4911: 
 4912:     if (!$domain) { $domain=$env{'user.domain'}; }
 4913:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4914: 
 4915:     &devalidate($symb,$stuname,$domain);
 4916: 
 4917:     $symb=escape($symb);
 4918:     if (!$namespace) { 
 4919:        unless ($namespace=$env{'request.course.id'}) { 
 4920:           return ''; 
 4921:        } 
 4922:     }
 4923:     if (!$home) { $home=$env{'user.home'}; }
 4924: 
 4925:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 4926:     $$storehash{'host'}=$perlvar{'lonHostID'};
 4927: 
 4928:     my $namevalue='';
 4929:     foreach my $key (keys(%$storehash)) {
 4930:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4931:     }
 4932:     $namevalue=~s/\&$//;
 4933:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 4934:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 4935: }
 4936: 
 4937: # -------------------------------------------------------------- Critical Store
 4938: 
 4939: sub cstore {
 4940:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4941:     my $home='';
 4942: 
 4943:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4944: 
 4945:     $symb=&symbclean($symb);
 4946:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 4947: 
 4948:     if (!$domain) { $domain=$env{'user.domain'}; }
 4949:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4950: 
 4951:     &devalidate($symb,$stuname,$domain);
 4952: 
 4953:     $symb=escape($symb);
 4954:     if (!$namespace) { 
 4955:        unless ($namespace=$env{'request.course.id'}) { 
 4956:           return ''; 
 4957:        } 
 4958:     }
 4959:     if (!$home) { $home=$env{'user.home'}; }
 4960: 
 4961:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 4962:     $$storehash{'host'}=$perlvar{'lonHostID'};
 4963: 
 4964:     my $namevalue='';
 4965:     foreach my $key (keys(%$storehash)) {
 4966:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4967:     }
 4968:     $namevalue=~s/\&$//;
 4969:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 4970:     return critical
 4971:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 4972: }
 4973: 
 4974: # --------------------------------------------------------------------- Restore
 4975: 
 4976: sub restore {
 4977:     my ($symb,$namespace,$domain,$stuname) = @_;
 4978:     my $home='';
 4979: 
 4980:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4981: 
 4982:     if (!$symb) {
 4983:         return if ($namespace eq 'courserequests');
 4984:         unless ($symb=escape(&symbread())) { return ''; }
 4985:     } else {
 4986:         unless ($namespace eq 'courserequests') {
 4987:             $symb=&escape(&symbclean($symb));
 4988:         }
 4989:     }
 4990:     if (!$namespace) { 
 4991:        unless ($namespace=$env{'request.course.id'}) { 
 4992:           return ''; 
 4993:        } 
 4994:     }
 4995:     if (!$domain) { $domain=$env{'user.domain'}; }
 4996:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4997:     if (!$home) { $home=$env{'user.home'}; }
 4998:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 4999: 
 5000:     my %returnhash=();
 5001:     foreach my $line (split(/\&/,$answer)) {
 5002: 	my ($name,$value)=split(/\=/,$line);
 5003:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 5004:     }
 5005:     my $version;
 5006:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 5007:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 5008:           $returnhash{$item}=$returnhash{$version.':'.$item};
 5009:        }
 5010:     }
 5011:     return %returnhash;
 5012: }
 5013: 
 5014: # ---------------------------------------------------------- Course Description
 5015: #
 5016: #  
 5017: 
 5018: sub coursedescription {
 5019:     my ($courseid,$args)=@_;
 5020:     $courseid=~s/^\///;
 5021:     $courseid=~s/\_/\//g;
 5022:     my ($cdomain,$cnum)=split(/\//,$courseid);
 5023:     my $chome=&homeserver($cnum,$cdomain);
 5024:     my $normalid=$cdomain.'_'.$cnum;
 5025:     # need to always cache even if we get errors otherwise we keep 
 5026:     # trying and trying and trying to get the course description.
 5027:     my %envhash=();
 5028:     my %returnhash=();
 5029:     
 5030:     my $expiretime=600;
 5031:     if ($env{'request.course.id'} eq $normalid) {
 5032: 	$expiretime=120;
 5033:     }
 5034: 
 5035:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 5036:     if (!$args->{'freshen_cache'}
 5037: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 5038: 	foreach my $key (keys(%env)) {
 5039: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 5040: 	    my ($setting) = $1;
 5041: 	    $returnhash{$setting} = $env{$key};
 5042: 	}
 5043: 	return %returnhash;
 5044:     }
 5045: 
 5046:     # get the data again
 5047: 
 5048:     if (!$args->{'one_time'}) {
 5049: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 5050:     }
 5051: 
 5052:     if ($chome ne 'no_host') {
 5053:        %returnhash=&dump('environment',$cdomain,$cnum);
 5054:        if (!exists($returnhash{'con_lost'})) {
 5055: 	   my $username = $env{'user.name'}; # Defult username
 5056: 	   if(defined $args->{'user'}) {
 5057: 	       $username = $args->{'user'};
 5058: 	   }
 5059:            $returnhash{'home'}= $chome;
 5060: 	   $returnhash{'domain'} = $cdomain;
 5061: 	   $returnhash{'num'} = $cnum;
 5062:            if (!defined($returnhash{'type'})) {
 5063:                $returnhash{'type'} = 'Course';
 5064:            }
 5065:            while (my ($name,$value) = each %returnhash) {
 5066:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 5067:            }
 5068:            $returnhash{'url'}=&clutter($returnhash{'url'});
 5069:            $returnhash{'fn'}=LONCAPA::tempdir() .
 5070: 	       $username.'_'.$cdomain.'_'.$cnum;
 5071:            $envhash{'course.'.$normalid.'.home'}=$chome;
 5072:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 5073:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 5074:        }
 5075:     }
 5076:     if (!$args->{'one_time'}) {
 5077: 	&appenv(\%envhash);
 5078:     }
 5079:     return %returnhash;
 5080: }
 5081: 
 5082: sub update_released_required {
 5083:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 5084:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 5085:         $cid = $env{'request.course.id'};
 5086:         $cdom = $env{'course.'.$cid.'.domain'};
 5087:         $cnum = $env{'course.'.$cid.'.num'};
 5088:         $chome = $env{'course.'.$cid.'.home'};
 5089:     }
 5090:     if ($needsrelease) {
 5091:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 5092:         my $needsupdate;
 5093:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 5094:             $needsupdate = 1;
 5095:         } else {
 5096:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 5097:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 5098:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 5099:                 $needsupdate = 1;
 5100:             }
 5101:         }
 5102:         if ($needsupdate) {
 5103:             my %needshash = (
 5104:                              'internal.releaserequired' => $needsrelease,
 5105:                             );
 5106:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 5107:             if ($putresult eq 'ok') {
 5108:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 5109:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 5110:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 5111:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 5112:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 5113:                 }
 5114:             }
 5115:         }
 5116:     }
 5117:     return;
 5118: }
 5119: 
 5120: # -------------------------------------------------See if a user is privileged
 5121: 
 5122: sub privileged {
 5123:     my ($username,$domain,$possdomains,$possroles)=@_;
 5124:     my $now = time;
 5125:     my $roles;
 5126:     if (ref($possroles) eq 'ARRAY') {
 5127:         $roles = $possroles;
 5128:     } else {
 5129:         $roles = ['dc','su'];
 5130:     }
 5131:     if (ref($possdomains) eq 'ARRAY') {
 5132:         my %privileged = &privileged_by_domain($possdomains,$roles);
 5133:         foreach my $dom (@{$possdomains}) {
 5134:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
 5135:                 (ref($privileged{$dom}) eq 'HASH')) {
 5136:                 foreach my $role (@{$roles}) {
 5137:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 5138:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
 5139:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
 5140:                             return 1 unless (($end && $end < $now) ||
 5141:                                              ($start && $start > $now));
 5142:                         }
 5143:                     }
 5144:                 }
 5145:             }
 5146:         }
 5147:     } else {
 5148:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
 5149:         my $now = time;
 5150: 
 5151:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
 5152:             my ($trole, $tend, $tstart) = split(/_/, $role);
 5153:             if (grep(/^\Q$trole\E$/,@{$roles})) {
 5154:                 return 1 unless ($tend && $tend < $now)
 5155:                         or ($tstart && $tstart > $now);
 5156:             }
 5157:         }
 5158:     }
 5159:     return 0;
 5160: }
 5161: 
 5162: sub privileged_by_domain {
 5163:     my ($domains,$roles) = @_;
 5164:     my %privileged = ();
 5165:     my $cachetime = 60*60*24;
 5166:     my $now = time;
 5167:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
 5168:         return %privileged;
 5169:     }
 5170:     foreach my $dom (@{$domains}) {
 5171:         next if (ref($privileged{$dom}) eq 'HASH');
 5172:         my $needroles;
 5173:         foreach my $role (@{$roles}) {
 5174:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
 5175:             if (defined($cached)) {
 5176:                 if (ref($result) eq 'HASH') {
 5177:                     $privileged{$dom}{$role} = $result;
 5178:                 }
 5179:             } else {
 5180:                 $needroles = 1;
 5181:             }
 5182:         }
 5183:         if ($needroles) {
 5184:             my %dompersonnel = &get_domain_roles($dom,$roles);
 5185:             $privileged{$dom} = {};
 5186:             foreach my $server (keys(%dompersonnel)) {
 5187:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 5188:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
 5189:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
 5190:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
 5191:                         next if ($end && $end < $now);
 5192:                         $privileged{$dom}{$trole}{$uname.':'.$udom} =
 5193:                             $dompersonnel{$server}{$item};
 5194:                     }
 5195:                 }
 5196:             }
 5197:             if (ref($privileged{$dom}) eq 'HASH') {
 5198:                 foreach my $role (@{$roles}) {
 5199:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 5200:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
 5201:                     } else {
 5202:                         my %hash = ();
 5203:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
 5204:                     }
 5205:                 }
 5206:             }
 5207:         }
 5208:     }
 5209:     return %privileged;
 5210: }
 5211: 
 5212: # -------------------------------------------------------- Get user privileges
 5213: 
 5214: sub rolesinit {
 5215:     my ($domain, $username) = @_;
 5216:     my %userroles = ('user.login.time' => time);
 5217:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 5218: 
 5219:     # firstaccess and timerinterval are related to timed maps/resources. 
 5220:     # also, blocking can be triggered by an activating timer
 5221:     # it's saved in the user's %env.
 5222:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 5223:     my %timerinterval = &dump('timerinterval', $domain, $username);
 5224:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 5225:         %timerintchk, %timerintenv);
 5226: 
 5227:     foreach my $key (keys(%firstaccess)) {
 5228:         my ($cid, $rest) = split(/\0/, $key);
 5229:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 5230:     }
 5231: 
 5232:     foreach my $key (keys(%timerinterval)) {
 5233:         my ($cid,$rest) = split(/\0/,$key);
 5234:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 5235:     }
 5236: 
 5237:     my %allroles=();
 5238:     my %allgroups=();
 5239: 
 5240:     for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
 5241:         my $role = $rolesdump{$area};
 5242:         $area =~ s/\_\w\w$//;
 5243: 
 5244:         my ($trole, $tend, $tstart, $group_privs);
 5245: 
 5246:         if ($role =~ /^cr/) {
 5247:         # Custom role, defined by a user 
 5248:         # e.g., user.role.cr/msu/smith/mynewrole
 5249:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 5250:                 $trole = $1;
 5251:                 ($tend, $tstart) = split('_', $2);
 5252:             } else {
 5253:                 $trole = $role;
 5254:             }
 5255:         } elsif ($role =~ m|^gr/|) {
 5256:         # Role of member in a group, defined within a course/community
 5257:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 5258:             ($trole, $tend, $tstart) = split(/_/, $role);
 5259:             next if $tstart eq '-1';
 5260:             ($trole, $group_privs) = split(/\//, $trole);
 5261:             $group_privs = &unescape($group_privs);
 5262:         } else {
 5263:         # Just a normal role, defined in roles.tab
 5264:             ($trole, $tend, $tstart) = split(/_/,$role);
 5265:         }
 5266: 
 5267:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 5268:                  $username);
 5269:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 5270: 
 5271:         # role expired or not available yet?
 5272:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 5273:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 5274: 
 5275:         next if $area eq '' or $trole eq '';
 5276: 
 5277:         my $spec = "$trole.$area";
 5278:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 5279: 
 5280:         if ($trole =~ /^cr\//) {
 5281:         # Custom role, defined by a user
 5282:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 5283:         } elsif ($trole eq 'gr') {
 5284:         # Role of a member in a group, defined within a course/community
 5285:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 5286:             next;
 5287:         } else {
 5288:         # Normal role, defined in roles.tab
 5289:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 5290:         }
 5291: 
 5292:         my $cid = $tdomain.'_'.$trest;
 5293:         unless ($firstaccchk{$cid}) {
 5294:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 5295:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 5296:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 5297:                         $coursetimerstarts{$cid}{$item}; 
 5298:                 }
 5299:             }
 5300:             $firstaccchk{$cid} = 1;
 5301:         }
 5302:         unless ($timerintchk{$cid}) {
 5303:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 5304:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 5305:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 5306:                        $coursetimerintervals{$cid}{$item};
 5307:                 }
 5308:             }
 5309:             $timerintchk{$cid} = 1;
 5310:         }
 5311:     }
 5312: 
 5313:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
 5314:         \%allroles, \%allgroups);
 5315:     $env{'user.adv'} = $userroles{'user.adv'};
 5316: 
 5317:     return (\%userroles,\%firstaccenv,\%timerintenv);
 5318: }
 5319: 
 5320: sub set_arearole {
 5321:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
 5322:     unless ($nolog) {
 5323: # log the associated role with the area
 5324:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 5325:     }
 5326:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 5327: }
 5328: 
 5329: sub custom_roleprivs {
 5330:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 5331:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 5332:     my $homsvr = &homeserver($rauthor,$rdomain);
 5333:     if (&hostname($homsvr) ne '') {
 5334:         my ($rdummy,$roledef)=
 5335:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 5336:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 5337:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 5338:             if (defined($syspriv)) {
 5339:                 if ($trest =~ /^$match_community$/) {
 5340:                     $syspriv =~ s/bre\&S//; 
 5341:                 }
 5342:                 $$allroles{'cm./'}.=':'.$syspriv;
 5343:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 5344:             }
 5345:             if ($tdomain ne '') {
 5346:                 if (defined($dompriv)) {
 5347:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 5348:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 5349:                 }
 5350:                 if (($trest ne '') && (defined($coursepriv))) {
 5351:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 5352:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 5353:                 }
 5354:             }
 5355:         }
 5356:     }
 5357: }
 5358: 
 5359: sub group_roleprivs {
 5360:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 5361:     my $access = 1;
 5362:     my $now = time;
 5363:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 5364:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 5365:     if ($access) {
 5366:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 5367:         $$allgroups{$course}{$group} .=':'.$group_privs;
 5368:     }
 5369: }
 5370: 
 5371: sub standard_roleprivs {
 5372:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 5373:     if (defined($pr{$trole.':s'})) {
 5374:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 5375:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 5376:     }
 5377:     if ($tdomain ne '') {
 5378:         if (defined($pr{$trole.':d'})) {
 5379:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 5380:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 5381:         }
 5382:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 5383:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 5384:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 5385:         }
 5386:     }
 5387: }
 5388: 
 5389: sub set_userprivs {
 5390:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 5391:     my $author=0;
 5392:     my $adv=0;
 5393:     my %grouproles = ();
 5394:     if (keys(%{$allgroups}) > 0) {
 5395:         my @groupkeys; 
 5396:         foreach my $role (keys(%{$allroles})) {
 5397:             push(@groupkeys,$role);
 5398:         }
 5399:         if (ref($groups_roles) eq 'HASH') {
 5400:             foreach my $key (keys(%{$groups_roles})) {
 5401:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 5402:                     push(@groupkeys,$key);
 5403:                 }
 5404:             }
 5405:         }
 5406:         if (@groupkeys > 0) {
 5407:             foreach my $role (@groupkeys) {
 5408:                 my ($trole,$area,$sec,$extendedarea);
 5409:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 5410:                     $trole = $1;
 5411:                     $area = $2;
 5412:                     $sec = $3;
 5413:                     $extendedarea = $area.$sec;
 5414:                     if (exists($$allgroups{$area})) {
 5415:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 5416:                             my $spec = $trole.'.'.$extendedarea;
 5417:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 5418:                                                 $$allgroups{$area}{$group};
 5419:                         }
 5420:                     }
 5421:                 }
 5422:             }
 5423:         }
 5424:     }
 5425:     foreach my $group (keys(%grouproles)) {
 5426:         $$allroles{$group} = $grouproles{$group};
 5427:     }
 5428:     foreach my $role (keys(%{$allroles})) {
 5429:         my %thesepriv;
 5430:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 5431:         foreach my $item (split(/:/,$$allroles{$role})) {
 5432:             if ($item ne '') {
 5433:                 my ($privilege,$restrictions)=split(/&/,$item);
 5434:                 if ($restrictions eq '') {
 5435:                     $thesepriv{$privilege}='F';
 5436:                 } elsif ($thesepriv{$privilege} ne 'F') {
 5437:                     $thesepriv{$privilege}.=$restrictions;
 5438:                 }
 5439:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 5440:             }
 5441:         }
 5442:         my $thesestr='';
 5443:         foreach my $priv (sort(keys(%thesepriv))) {
 5444: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 5445: 	}
 5446:         $userroles->{'user.priv.'.$role} = $thesestr;
 5447:     }
 5448:     return ($author,$adv);
 5449: }
 5450: 
 5451: sub role_status {
 5452:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 5453:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 5454:         my ($one,$two) = split(m{\./},$rolekey,2);
 5455:         (undef,undef,$$role) = split(/\./,$one,3);
 5456:         unless (!defined($$role) || $$role eq '') {
 5457:             $$where = '/'.$two;
 5458:             $$trolecode=$$role.'.'.$$where;
 5459:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 5460:             $$tstatus='is';
 5461:             if ($$tstart && $$tstart>$update) {
 5462:                 $$tstatus='future';
 5463:                 if ($$tstart<$now) {
 5464:                     if ($$tstart && $$tstart>$refresh) {
 5465:                         if (($$where ne '') && ($$role ne '')) {
 5466:                             my (%allroles,%allgroups,$group_privs,
 5467:                                 %groups_roles,@rolecodes);
 5468:                             my %userroles = (
 5469:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 5470:                             );
 5471:                             @rolecodes = ('cm'); 
 5472:                             my $spec=$$role.'.'.$$where;
 5473:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 5474:                             if ($$role =~ /^cr\//) {
 5475:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 5476:                                 push(@rolecodes,'cr');
 5477:                             } elsif ($$role eq 'gr') {
 5478:                                 push(@rolecodes,$$role);
 5479:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 5480:                                                     $env{'user.name'});
 5481:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 5482:                                 (undef,my $group_privs) = split(/\//,$trole);
 5483:                                 $group_privs = &unescape($group_privs);
 5484:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 5485:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 5486:                                 &get_groups_roles($tdomain,$trest,
 5487:                                                   \%course_roles,\@rolecodes,
 5488:                                                   \%groups_roles);
 5489:                             } else {
 5490:                                 push(@rolecodes,$$role);
 5491:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 5492:                             }
 5493:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
 5494:                             &appenv(\%userroles,\@rolecodes);
 5495:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 5496:                         }
 5497:                     }
 5498:                     $$tstatus = 'is';
 5499:                 }
 5500:             }
 5501:             if ($$tend) {
 5502:                 if ($$tend<$update) {
 5503:                     $$tstatus='expired';
 5504:                 } elsif ($$tend<$now) {
 5505:                     $$tstatus='will_not';
 5506:                 }
 5507:             }
 5508:         }
 5509:     }
 5510: }
 5511: 
 5512: sub get_groups_roles {
 5513:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 5514:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 5515:                   (ref($rolecodes) eq 'ARRAY') && 
 5516:                   (ref($groups_roles) eq 'HASH')); 
 5517:     if (keys(%{$cdom_courseroles}) > 0) {
 5518:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 5519:         if ($cdom ne '' && $cnum ne '') {
 5520:             foreach my $key (keys(%{$cdom_courseroles})) {
 5521:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 5522:                     my $crsrole = $1;
 5523:                     my $crssec = $2;
 5524:                     if ($crsrole =~ /^cr/) {
 5525:                         unless (grep(/^cr$/,@{$rolecodes})) {
 5526:                             push(@{$rolecodes},'cr');
 5527:                         }
 5528:                     } else {
 5529:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 5530:                             push(@{$rolecodes},$crsrole);
 5531:                         }
 5532:                     }
 5533:                     my $rolekey = "$crsrole./$cdom/$cnum";
 5534:                     if ($crssec ne '') {
 5535:                         $rolekey .= "/$crssec";
 5536:                     }
 5537:                     $rolekey .= './';
 5538:                     $groups_roles->{$rolekey} = $rolecodes;
 5539:                 }
 5540:             }
 5541:         }
 5542:     }
 5543:     return;
 5544: }
 5545: 
 5546: sub delete_env_groupprivs {
 5547:     my ($where,$courseroles,$possroles) = @_;
 5548:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 5549:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 5550:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 5551:         %{$courseroles->{$udom}} =
 5552:             &get_my_roles('','','userroles',['active'],
 5553:                           $possroles,[$udom],1);
 5554:     }
 5555:     if (ref($courseroles->{$udom}) eq 'HASH') {
 5556:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 5557:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 5558:             my $area = '/'.$cdom.'/'.$cnum;
 5559:             my $privkey = "user.priv.$crsrole.$area";
 5560:             if ($crssec ne '') {
 5561:                 $privkey .= '/'.$crssec;
 5562:             }
 5563:             $privkey .= ".$area/$group";
 5564:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 5565:         }
 5566:     }
 5567:     return;
 5568: }
 5569: 
 5570: sub check_adhoc_privs {
 5571:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
 5572:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 5573:     my $setprivs;
 5574:     if ($env{$cckey}) {
 5575:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 5576:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 5577:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 5578:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 5579:             $setprivs = 1;
 5580:         }
 5581:     } else {
 5582:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 5583:         $setprivs = 1;
 5584:     }
 5585:     return $setprivs;
 5586: }
 5587: 
 5588: sub set_adhoc_privileges {
 5589: # role can be cc or ca
 5590:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
 5591:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 5592:     my $spec = $role.'.'.$area;
 5593:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 5594:                                   $env{'user.name'},1);
 5595:     my %ccrole = ();
 5596:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
 5597:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
 5598:     &appenv(\%userroles,[$role,'cm']);
 5599:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 5600:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
 5601:         &appenv( {'request.role'        => $spec,
 5602:                   'request.role.domain' => $dcdom,
 5603:                   'request.course.sec'  => ''
 5604:                  }
 5605:                );
 5606:         my $tadv=0;
 5607:         if (&allowed('adv') eq 'F') { $tadv=1; }
 5608:         &appenv({'request.role.adv'    => $tadv});
 5609:     }
 5610: }
 5611: 
 5612: # --------------------------------------------------------------- get interface
 5613: 
 5614: sub get {
 5615:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5616:    my $items='';
 5617:    foreach my $item (@$storearr) {
 5618:        $items.=&escape($item).'&';
 5619:    }
 5620:    $items=~s/\&$//;
 5621:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5622:    if (!$uname) { $uname=$env{'user.name'}; }
 5623:    my $uhome=&homeserver($uname,$udomain);
 5624: 
 5625:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 5626:    my @pairs=split(/\&/,$rep);
 5627:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 5628:      return @pairs;
 5629:    }
 5630:    my %returnhash=();
 5631:    my $i=0;
 5632:    foreach my $item (@$storearr) {
 5633:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 5634:       $i++;
 5635:    }
 5636:    return %returnhash;
 5637: }
 5638: 
 5639: # --------------------------------------------------------------- del interface
 5640: 
 5641: sub del {
 5642:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5643:    my $items='';
 5644:    foreach my $item (@$storearr) {
 5645:        $items.=&escape($item).'&';
 5646:    }
 5647: 
 5648:    $items=~s/\&$//;
 5649:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5650:    if (!$uname) { $uname=$env{'user.name'}; }
 5651:    my $uhome=&homeserver($uname,$udomain);
 5652:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 5653: }
 5654: 
 5655: # -------------------------------------------------------------- dump interface
 5656: 
 5657: sub unserialize {
 5658:     my ($rep, $escapedkeys) = @_;
 5659: 
 5660:     return {} if $rep =~ /^error/;
 5661: 
 5662:     my %returnhash=();
 5663:     foreach my $item (split(/\&/,$rep)) {
 5664:         my ($key, $value) = split(/=/, $item, 2);
 5665:         $key = unescape($key) unless $escapedkeys;
 5666:         next if $key =~ /^error: 2 /;
 5667:         $returnhash{$key} = &thaw_unescape($value);
 5668:     }
 5669:     return \%returnhash;
 5670: }
 5671: 
 5672: # see Lond::dump_with_regexp
 5673: # if $escapedkeys hash keys won't get unescaped.
 5674: sub dump {
 5675:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
 5676:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5677:     if (!$uname) { $uname=$env{'user.name'}; }
 5678:     my $uhome=&homeserver($uname,$udomain);
 5679: 
 5680:     my $reply;
 5681:     if (grep { $_ eq $uhome } &current_machine_ids()) {
 5682:         # user is hosted on this machine
 5683:         $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
 5684:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
 5685:         return %{&unserialize($reply, $escapedkeys)};
 5686:     }
 5687:     if ($regexp) {
 5688: 	$regexp=&escape($regexp);
 5689:     } else {
 5690: 	$regexp='.';
 5691:     }
 5692:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 5693:     my @pairs=split(/\&/,$rep);
 5694:     my %returnhash=();
 5695:     if (!($rep =~ /^error/ )) {
 5696: 	foreach my $item (@pairs) {
 5697: 	    my ($key,$value)=split(/=/,$item,2);
 5698:             $key = &unescape($key) unless ($escapedkeys);
 5699: 	    next if ($key =~ /^error: 2 /);
 5700: 	    $returnhash{$key}=&thaw_unescape($value);
 5701: 	}
 5702:     }
 5703:     return %returnhash;
 5704: }
 5705: 
 5706: 
 5707: # --------------------------------------------------------- dumpstore interface
 5708: 
 5709: sub dumpstore {
 5710:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 5711:    # same as dump but keys must be escaped. They may contain colon separated
 5712:    # lists of values that may themself contain colons (e.g. symbs).
 5713:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
 5714: }
 5715: 
 5716: # -------------------------------------------------------------- keys interface
 5717: 
 5718: sub getkeys {
 5719:    my ($namespace,$udomain,$uname)=@_;
 5720:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5721:    if (!$uname) { $uname=$env{'user.name'}; }
 5722:    my $uhome=&homeserver($uname,$udomain);
 5723:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 5724:    my @keyarray=();
 5725:    foreach my $key (split(/\&/,$rep)) {
 5726:       next if ($key =~ /^error: 2 /);
 5727:       push(@keyarray,&unescape($key));
 5728:    }
 5729:    return @keyarray;
 5730: }
 5731: 
 5732: # --------------------------------------------------------------- currentdump
 5733: sub currentdump {
 5734:    my ($courseid,$sdom,$sname)=@_;
 5735:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 5736:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 5737:    $sname    = $env{'user.name'}         if (! defined($sname));
 5738:    my $uhome = &homeserver($sname,$sdom);
 5739:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 5740:    return if ($rep =~ /^(error:|no_such_host)/);
 5741:    #
 5742:    my %returnhash=();
 5743:    #
 5744:    if ($rep eq "unknown_cmd") { 
 5745:        # an old lond will not know currentdump
 5746:        # Do a dump and make it look like a currentdump
 5747:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 5748:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 5749:        my %hash = @tmp;
 5750:        @tmp=();
 5751:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 5752:    } else {
 5753:        my @pairs=split(/\&/,$rep);
 5754:        foreach my $pair (@pairs) {
 5755:            my ($key,$value)=split(/=/,$pair,2);
 5756:            my ($symb,$param) = split(/:/,$key);
 5757:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 5758:                                                         &thaw_unescape($value);
 5759:        }
 5760:    }
 5761:    return %returnhash;
 5762: }
 5763: 
 5764: sub convert_dump_to_currentdump{
 5765:     my %hash = %{shift()};
 5766:     my %returnhash;
 5767:     # Code ripped from lond, essentially.  The only difference
 5768:     # here is the unescaping done by lonnet::dump().  Conceivably
 5769:     # we might run in to problems with parameter names =~ /^v\./
 5770:     while (my ($key,$value) = each(%hash)) {
 5771:         my ($v,$symb,$param) = split(/:/,$key);
 5772: 	$symb  = &unescape($symb);
 5773: 	$param = &unescape($param);
 5774:         next if ($v eq 'version' || $symb eq 'keys');
 5775:         next if (exists($returnhash{$symb}) &&
 5776:                  exists($returnhash{$symb}->{$param}) &&
 5777:                  $returnhash{$symb}->{'v.'.$param} > $v);
 5778:         $returnhash{$symb}->{$param}=$value;
 5779:         $returnhash{$symb}->{'v.'.$param}=$v;
 5780:     }
 5781:     #
 5782:     # Remove all of the keys in the hashes which keep track of
 5783:     # the version of the parameter.
 5784:     while (my ($symb,$param_hash) = each(%returnhash)) {
 5785:         # use a foreach because we are going to delete from the hash.
 5786:         foreach my $key (keys(%$param_hash)) {
 5787:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 5788:         }
 5789:     }
 5790:     return \%returnhash;
 5791: }
 5792: 
 5793: # ------------------------------------------------------ critical inc interface
 5794: 
 5795: sub cinc {
 5796:     return &inc(@_,'critical');
 5797: }
 5798: 
 5799: # --------------------------------------------------------------- inc interface
 5800: 
 5801: sub inc {
 5802:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 5803:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5804:     if (!$uname) { $uname=$env{'user.name'}; }
 5805:     my $uhome=&homeserver($uname,$udomain);
 5806:     my $items='';
 5807:     if (! ref($store)) {
 5808:         # got a single value, so use that instead
 5809:         $items = &escape($store).'=&';
 5810:     } elsif (ref($store) eq 'SCALAR') {
 5811:         $items = &escape($$store).'=&';        
 5812:     } elsif (ref($store) eq 'ARRAY') {
 5813:         $items = join('=&',map {&escape($_);} @{$store});
 5814:     } elsif (ref($store) eq 'HASH') {
 5815:         while (my($key,$value) = each(%{$store})) {
 5816:             $items.= &escape($key).'='.&escape($value).'&';
 5817:         }
 5818:     }
 5819:     $items=~s/\&$//;
 5820:     if ($critical) {
 5821: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 5822:     } else {
 5823: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 5824:     }
 5825: }
 5826: 
 5827: # --------------------------------------------------------------- put interface
 5828: 
 5829: sub put {
 5830:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5831:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5832:    if (!$uname) { $uname=$env{'user.name'}; }
 5833:    my $uhome=&homeserver($uname,$udomain);
 5834:    my $items='';
 5835:    foreach my $item (keys(%$storehash)) {
 5836:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5837:    }
 5838:    $items=~s/\&$//;
 5839:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5840: }
 5841: 
 5842: # ------------------------------------------------------------ newput interface
 5843: 
 5844: sub newput {
 5845:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5846:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5847:    if (!$uname) { $uname=$env{'user.name'}; }
 5848:    my $uhome=&homeserver($uname,$udomain);
 5849:    my $items='';
 5850:    foreach my $key (keys(%$storehash)) {
 5851:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 5852:    }
 5853:    $items=~s/\&$//;
 5854:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 5855: }
 5856: 
 5857: # ---------------------------------------------------------  putstore interface
 5858: 
 5859: sub putstore {
 5860:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 5861:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5862:    if (!$uname) { $uname=$env{'user.name'}; }
 5863:    my $uhome=&homeserver($uname,$udomain);
 5864:    my $items='';
 5865:    foreach my $key (keys(%$storehash)) {
 5866:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 5867:    }
 5868:    $items=~s/\&$//;
 5869:    my $esc_symb=&escape($symb);
 5870:    my $esc_v=&escape($version);
 5871:    my $reply =
 5872:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 5873: 	      $uhome);
 5874:    if ($reply eq 'unknown_cmd') {
 5875:        # gfall back to way things use to be done
 5876:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 5877: 			    $uname);
 5878:    }
 5879:    return $reply;
 5880: }
 5881: 
 5882: sub old_putstore {
 5883:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 5884:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5885:     if (!$uname) { $uname=$env{'user.name'}; }
 5886:     my $uhome=&homeserver($uname,$udomain);
 5887:     my %newstorehash;
 5888:     foreach my $item (keys(%$storehash)) {
 5889: 	my $key = $version.':'.&escape($symb).':'.$item;
 5890: 	$newstorehash{$key} = $storehash->{$item};
 5891:     }
 5892:     my $items='';
 5893:     my %allitems = ();
 5894:     foreach my $item (keys(%newstorehash)) {
 5895: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 5896: 	    my $key = $1.':keys:'.$2;
 5897: 	    $allitems{$key} .= $3.':';
 5898: 	}
 5899: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 5900:     }
 5901:     foreach my $item (keys(%allitems)) {
 5902: 	$allitems{$item} =~ s/\:$//;
 5903: 	$items.= $item.'='.$allitems{$item}.'&';
 5904:     }
 5905:     $items=~s/\&$//;
 5906:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5907: }
 5908: 
 5909: # ------------------------------------------------------ critical put interface
 5910: 
 5911: sub cput {
 5912:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5913:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5914:    if (!$uname) { $uname=$env{'user.name'}; }
 5915:    my $uhome=&homeserver($uname,$udomain);
 5916:    my $items='';
 5917:    foreach my $item (keys(%$storehash)) {
 5918:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5919:    }
 5920:    $items=~s/\&$//;
 5921:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 5922: }
 5923: 
 5924: # -------------------------------------------------------------- eget interface
 5925: 
 5926: sub eget {
 5927:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5928:    my $items='';
 5929:    foreach my $item (@$storearr) {
 5930:        $items.=&escape($item).'&';
 5931:    }
 5932:    $items=~s/\&$//;
 5933:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5934:    if (!$uname) { $uname=$env{'user.name'}; }
 5935:    my $uhome=&homeserver($uname,$udomain);
 5936:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 5937:    my @pairs=split(/\&/,$rep);
 5938:    my %returnhash=();
 5939:    my $i=0;
 5940:    foreach my $item (@$storearr) {
 5941:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 5942:       $i++;
 5943:    }
 5944:    return %returnhash;
 5945: }
 5946: 
 5947: # ------------------------------------------------------------ tmpput interface
 5948: sub tmpput {
 5949:     my ($storehash,$server,$context)=@_;
 5950:     my $items='';
 5951:     foreach my $item (keys(%$storehash)) {
 5952: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5953:     }
 5954:     $items=~s/\&$//;
 5955:     if (defined($context)) {
 5956:         $items .= ':'.&escape($context);
 5957:     }
 5958:     return &reply("tmpput:$items",$server);
 5959: }
 5960: 
 5961: # ------------------------------------------------------------ tmpget interface
 5962: sub tmpget {
 5963:     my ($token,$server)=@_;
 5964:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 5965:     my $rep=&reply("tmpget:$token",$server);
 5966:     my %returnhash;
 5967:     foreach my $item (split(/\&/,$rep)) {
 5968: 	my ($key,$value)=split(/=/,$item);
 5969:         next if ($key =~ /^error: 2 /);
 5970: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 5971:     }
 5972:     return %returnhash;
 5973: }
 5974: 
 5975: # ------------------------------------------------------------ tmpdel interface
 5976: sub tmpdel {
 5977:     my ($token,$server)=@_;
 5978:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 5979:     return &reply("tmpdel:$token",$server);
 5980: }
 5981: 
 5982: # ------------------------------------------------------------ get_timebased_id
 5983: 
 5984: sub get_timebased_id {
 5985:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
 5986:         $maxtries) = @_;
 5987:     my ($newid,$error,$dellock);
 5988:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
 5989:         return ('','ok','invalid call to get suffix');
 5990:     }
 5991: 
 5992: # set defaults for any optional args for which values were not supplied
 5993:     if ($who eq '') {
 5994:         $who = $env{'user.name'}.':'.$env{'user.domain'};
 5995:     }
 5996:     if (!$locktries) {
 5997:         $locktries = 3;
 5998:     }
 5999:     if (!$maxtries) {
 6000:         $maxtries = 10;
 6001:     }
 6002: 
 6003:     if (($cdom eq '') || ($cnum eq '')) {
 6004:         if ($env{'request.course.id'}) {
 6005:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6006:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6007:         }
 6008:         if (($cdom eq '') || ($cnum eq '')) {
 6009:             return ('','ok','call to get suffix not in course context');
 6010:         }
 6011:     }
 6012: 
 6013: # construct locking item
 6014:     my $lockhash = {
 6015:                       $prefix."\0".'locked_'.$keyid => $who,
 6016:                    };
 6017:     my $tries = 0;
 6018: 
 6019: # attempt to get lock on nohist_$namespace file
 6020:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 6021:     while (($gotlock ne 'ok') && $tries <$locktries) {
 6022:         $tries ++;
 6023:         sleep 1;
 6024:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 6025:     }
 6026: 
 6027: # attempt to get unique identifier, based on current timestamp
 6028:     if ($gotlock eq 'ok') {
 6029:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
 6030:         my $id = time;
 6031:         $newid = $id;
 6032:         my $idtries = 0;
 6033:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
 6034:             if ($idtype eq 'concat') {
 6035:                 $newid = $id.$idtries;
 6036:             } else {
 6037:                 $newid ++;
 6038:             }
 6039:             $idtries ++;
 6040:         }
 6041:         if (!exists($inuse{$prefix."\0".$newid})) {
 6042:             my %new_item =  (
 6043:                               $prefix."\0".$newid => $who,
 6044:                             );
 6045:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
 6046:                                                  $cdom,$cnum);
 6047:             if ($putresult ne 'ok') {
 6048:                 undef($newid);
 6049:                 $error = 'error saving new item: '.$putresult;
 6050:             }
 6051:         } else {
 6052:              $error = ('error: no unique suffix available for the new item ');
 6053:         }
 6054: #  remove lock
 6055:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
 6056:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
 6057:     } else {
 6058:         $error = "error: could not obtain lockfile\n";
 6059:         $dellock = 'ok';
 6060:     }
 6061:     return ($newid,$dellock,$error);
 6062: }
 6063: 
 6064: # -------------------------------------------------- portfolio access checking
 6065: 
 6066: sub portfolio_access {
 6067:     my ($requrl) = @_;
 6068:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 6069:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 6070:     if ($result) {
 6071:         my %setters;
 6072:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 6073:             my ($startblock,$endblock) =
 6074:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 6075:             if ($startblock && $endblock) {
 6076:                 return 'B';
 6077:             }
 6078:         } else {
 6079:             my ($startblock,$endblock) =
 6080:                 &Apache::loncommon::blockcheck(\%setters,'port');
 6081:             if ($startblock && $endblock) {
 6082:                 return 'B';
 6083:             }
 6084:         }
 6085:     }
 6086:     if ($result eq 'ok') {
 6087:        return 'F';
 6088:     } elsif ($result =~ /^[^:]+:guest_/) {
 6089:        return 'A';
 6090:     }
 6091:     return '';
 6092: }
 6093: 
 6094: sub get_portfolio_access {
 6095:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 6096: 
 6097:     if (!ref($access_hash)) {
 6098: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 6099: 	my %access_controls = &get_access_controls($current_perms,$group,
 6100: 						   $file_name);
 6101: 	$access_hash = $access_controls{$file_name};
 6102:     }
 6103: 
 6104:     my ($public,$guest,@domains,@users,@courses,@groups);
 6105:     my $now = time;
 6106:     if (ref($access_hash) eq 'HASH') {
 6107:         foreach my $key (keys(%{$access_hash})) {
 6108:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 6109:             if ($start > $now) {
 6110:                 next;
 6111:             }
 6112:             if ($end && $end<$now) {
 6113:                 next;
 6114:             }
 6115:             if ($scope eq 'public') {
 6116:                 $public = $key;
 6117:                 last;
 6118:             } elsif ($scope eq 'guest') {
 6119:                 $guest = $key;
 6120:             } elsif ($scope eq 'domains') {
 6121:                 push(@domains,$key);
 6122:             } elsif ($scope eq 'users') {
 6123:                 push(@users,$key);
 6124:             } elsif ($scope eq 'course') {
 6125:                 push(@courses,$key);
 6126:             } elsif ($scope eq 'group') {
 6127:                 push(@groups,$key);
 6128:             }
 6129:         }
 6130:         if ($public) {
 6131:             return 'ok';
 6132:         }
 6133:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 6134:             if ($guest) {
 6135:                 return $guest;
 6136:             }
 6137:         } else {
 6138:             if (@domains > 0) {
 6139:                 foreach my $domkey (@domains) {
 6140:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 6141:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 6142:                             return 'ok';
 6143:                         }
 6144:                     }
 6145:                 }
 6146:             }
 6147:             if (@users > 0) {
 6148:                 foreach my $userkey (@users) {
 6149:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 6150:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 6151:                             if (ref($item) eq 'HASH') {
 6152:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 6153:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 6154:                                     return 'ok';
 6155:                                 }
 6156:                             }
 6157:                         }
 6158:                     } 
 6159:                 }
 6160:             }
 6161:             my %roleshash;
 6162:             my @courses_and_groups = @courses;
 6163:             push(@courses_and_groups,@groups); 
 6164:             if (@courses_and_groups > 0) {
 6165:                 my (%allgroups,%allroles); 
 6166:                 my ($start,$end,$role,$sec,$group);
 6167:                 foreach my $envkey (%env) {
 6168:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 6169:                         my $cid = $2.'_'.$3; 
 6170:                         if ($1 eq 'gr') {
 6171:                             $group = $4;
 6172:                             $allgroups{$cid}{$group} = $env{$envkey};
 6173:                         } else {
 6174:                             if ($4 eq '') {
 6175:                                 $sec = 'none';
 6176:                             } else {
 6177:                                 $sec = $4;
 6178:                             }
 6179:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 6180:                         }
 6181:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 6182:                         my $cid = $2.'_'.$3;
 6183:                         if ($4 eq '') {
 6184:                             $sec = 'none';
 6185:                         } else {
 6186:                             $sec = $4;
 6187:                         }
 6188:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 6189:                     }
 6190:                 }
 6191:                 if (keys(%allroles) == 0) {
 6192:                     return;
 6193:                 }
 6194:                 foreach my $key (@courses_and_groups) {
 6195:                     my %content = %{$$access_hash{$key}};
 6196:                     my $cnum = $content{'number'};
 6197:                     my $cdom = $content{'domain'};
 6198:                     my $cid = $cdom.'_'.$cnum;
 6199:                     if (!exists($allroles{$cid})) {
 6200:                         next;
 6201:                     }    
 6202:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 6203:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 6204:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 6205:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 6206:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 6207:                         foreach my $role (keys(%{$allroles{$cid}})) {
 6208:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 6209:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 6210:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 6211:                                         if (grep/^all$/,@sections) {
 6212:                                             return 'ok';
 6213:                                         } else {
 6214:                                             if (grep/^$sec$/,@sections) {
 6215:                                                 return 'ok';
 6216:                                             }
 6217:                                         }
 6218:                                     }
 6219:                                 }
 6220:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 6221:                                     if (grep/^none$/,@groups) {
 6222:                                         return 'ok';
 6223:                                     }
 6224:                                 } else {
 6225:                                     if (grep/^all$/,@groups) {
 6226:                                         return 'ok';
 6227:                                     } 
 6228:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 6229:                                         if (grep/^$group$/,@groups) {
 6230:                                             return 'ok';
 6231:                                         }
 6232:                                     }
 6233:                                 } 
 6234:                             }
 6235:                         }
 6236:                     }
 6237:                 }
 6238:             }
 6239:             if ($guest) {
 6240:                 return $guest;
 6241:             }
 6242:         }
 6243:     }
 6244:     return;
 6245: }
 6246: 
 6247: sub course_group_datechecker {
 6248:     my ($dates,$now,$status) = @_;
 6249:     my ($start,$end) = split(/\./,$dates);
 6250:     if (!$start && !$end) {
 6251:         return 'ok';
 6252:     }
 6253:     if (grep/^active$/,@{$status}) {
 6254:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 6255:             return 'ok';
 6256:         }
 6257:     }
 6258:     if (grep/^previous$/,@{$status}) {
 6259:         if ($end > $now ) {
 6260:             return 'ok';
 6261:         }
 6262:     }
 6263:     if (grep/^future$/,@{$status}) {
 6264:         if ($start > $now) {
 6265:             return 'ok';
 6266:         }
 6267:     }
 6268:     return; 
 6269: }
 6270: 
 6271: sub parse_portfolio_url {
 6272:     my ($url) = @_;
 6273: 
 6274:     my ($type,$udom,$unum,$group,$file_name);
 6275:     
 6276:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 6277: 	$type = 1;
 6278:         $udom = $1;
 6279:         $unum = $2;
 6280:         $file_name = $3;
 6281:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 6282: 	$type = 2;
 6283:         $udom = $1;
 6284:         $unum = $2;
 6285:         $group = $3;
 6286:         $file_name = $3.'/'.$4;
 6287:     }
 6288:     if (wantarray) {
 6289: 	return ($type,$udom,$unum,$file_name,$group);
 6290:     }
 6291:     return $type;
 6292: }
 6293: 
 6294: sub is_portfolio_url {
 6295:     my ($url) = @_;
 6296:     return scalar(&parse_portfolio_url($url));
 6297: }
 6298: 
 6299: sub is_portfolio_file {
 6300:     my ($file) = @_;
 6301:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 6302:         return 1;
 6303:     }
 6304:     return;
 6305: }
 6306: 
 6307: sub usertools_access {
 6308:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 6309:     my ($access,%tools);
 6310:     if ($context eq '') {
 6311:         $context = 'tools';
 6312:     }
 6313:     if ($context eq 'requestcourses') {
 6314:         %tools = (
 6315:                       official   => 1,
 6316:                       unofficial => 1,
 6317:                       community  => 1,
 6318:                       textbook   => 1,
 6319:                  );
 6320:     } elsif ($context eq 'requestauthor') {
 6321:         %tools = (
 6322:                       requestauthor => 1,
 6323:                  );
 6324:     } else {
 6325:         %tools = (
 6326:                       aboutme   => 1,
 6327:                       blog      => 1,
 6328:                       webdav    => 1,
 6329:                       portfolio => 1,
 6330:                  );
 6331:     }
 6332:     return if (!defined($tools{$tool}));
 6333: 
 6334:     if (($udom eq '') || ($uname eq '')) {
 6335:         $udom = $env{'user.domain'};
 6336:         $uname = $env{'user.name'};
 6337:     }
 6338: 
 6339:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 6340:         if ($action ne 'reload') {
 6341:             if ($context eq 'requestcourses') {
 6342:                 return $env{'environment.canrequest.'.$tool};
 6343:             } elsif ($context eq 'requestauthor') {
 6344:                 return $env{'environment.canrequest.author'};
 6345:             } else {
 6346:                 return $env{'environment.availabletools.'.$tool};
 6347:             }
 6348:         }
 6349:     }
 6350: 
 6351:     my ($toolstatus,$inststatus,$envkey);
 6352:     if ($context eq 'requestauthor') {
 6353:         $envkey = $context;
 6354:     } else {
 6355:         $envkey = $context.'.'.$tool;
 6356:     }
 6357: 
 6358:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 6359:          ($action ne 'reload')) {
 6360:         $toolstatus = $env{'environment.'.$envkey};
 6361:         $inststatus = $env{'environment.inststatus'};
 6362:     } else {
 6363:         if (ref($userenvref) eq 'HASH') {
 6364:             $toolstatus = $userenvref->{$envkey};
 6365:             $inststatus = $userenvref->{'inststatus'};
 6366:         } else {
 6367:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 6368:             $toolstatus = $userenv{$envkey};
 6369:             $inststatus = $userenv{'inststatus'};
 6370:         }
 6371:     }
 6372: 
 6373:     if ($toolstatus ne '') {
 6374:         if ($toolstatus) {
 6375:             $access = 1;
 6376:         } else {
 6377:             $access = 0;
 6378:         }
 6379:         return $access;
 6380:     }
 6381: 
 6382:     my ($is_adv,%domdef);
 6383:     if (ref($is_advref) eq 'HASH') {
 6384:         $is_adv = $is_advref->{'is_adv'};
 6385:     } else {
 6386:         $is_adv = &is_advanced_user($udom,$uname);
 6387:     }
 6388:     if (ref($domdefref) eq 'HASH') {
 6389:         %domdef = %{$domdefref};
 6390:     } else {
 6391:         %domdef = &get_domain_defaults($udom);
 6392:     }
 6393:     if (ref($domdef{$tool}) eq 'HASH') {
 6394:         if ($is_adv) {
 6395:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 6396:                 if ($domdef{$tool}{'_LC_adv'}) { 
 6397:                     $access = 1;
 6398:                 } else {
 6399:                     $access = 0;
 6400:                 }
 6401:                 return $access;
 6402:             }
 6403:         }
 6404:         if ($inststatus ne '') {
 6405:             my ($hasaccess,$hasnoaccess);
 6406:             foreach my $affiliation (split(/:/,$inststatus)) {
 6407:                 if ($domdef{$tool}{$affiliation} ne '') { 
 6408:                     if ($domdef{$tool}{$affiliation}) {
 6409:                         $hasaccess = 1;
 6410:                     } else {
 6411:                         $hasnoaccess = 1;
 6412:                     }
 6413:                 }
 6414:             }
 6415:             if ($hasaccess || $hasnoaccess) {
 6416:                 if ($hasaccess) {
 6417:                     $access = 1;
 6418:                 } elsif ($hasnoaccess) {
 6419:                     $access = 0; 
 6420:                 }
 6421:                 return $access;
 6422:             }
 6423:         } else {
 6424:             if ($domdef{$tool}{'default'} ne '') {
 6425:                 if ($domdef{$tool}{'default'}) {
 6426:                     $access = 1;
 6427:                 } elsif ($domdef{$tool}{'default'} == 0) {
 6428:                     $access = 0;
 6429:                 }
 6430:                 return $access;
 6431:             }
 6432:         }
 6433:     } else {
 6434:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 6435:             $access = 1;
 6436:         } else {
 6437:             $access = 0;
 6438:         }
 6439:         return $access;
 6440:     }
 6441: }
 6442: 
 6443: sub is_course_owner {
 6444:     my ($cdom,$cnum,$udom,$uname) = @_;
 6445:     if (($udom eq '') || ($uname eq '')) {
 6446:         $udom = $env{'user.domain'};
 6447:         $uname = $env{'user.name'};
 6448:     }
 6449:     unless (($udom eq '') || ($uname eq '')) {
 6450:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 6451:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 6452:                 return 1;
 6453:             } else {
 6454:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 6455:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 6456:                     return 1;
 6457:                 }
 6458:             }
 6459:         }
 6460:     }
 6461:     return;
 6462: }
 6463: 
 6464: sub is_advanced_user {
 6465:     my ($udom,$uname) = @_;
 6466:     if ($udom ne '' && $uname ne '') {
 6467:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 6468:             if (wantarray) {
 6469:                 return ($env{'user.adv'},$env{'user.author'});
 6470:             } else {
 6471:                 return $env{'user.adv'};
 6472:             }
 6473:         }
 6474:     }
 6475:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 6476:     my %allroles;
 6477:     my ($is_adv,$is_author);
 6478:     foreach my $role (keys(%roleshash)) {
 6479:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 6480:         my $area = '/'.$tdomain.'/'.$trest;
 6481:         if ($sec ne '') {
 6482:             $area .= '/'.$sec;
 6483:         }
 6484:         if (($area ne '') && ($trole ne '')) {
 6485:             my $spec=$trole.'.'.$area;
 6486:             if ($trole =~ /^cr\//) {
 6487:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 6488:             } elsif ($trole ne 'gr') {
 6489:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 6490:             }
 6491:             if ($trole eq 'au') {
 6492:                 $is_author = 1;
 6493:             }
 6494:         }
 6495:     }
 6496:     foreach my $role (keys(%allroles)) {
 6497:         last if ($is_adv);
 6498:         foreach my $item (split(/:/,$allroles{$role})) {
 6499:             if ($item ne '') {
 6500:                 my ($privilege,$restrictions)=split(/&/,$item);
 6501:                 if ($privilege eq 'adv') {
 6502:                     $is_adv = 1;
 6503:                     last;
 6504:                 }
 6505:             }
 6506:         }
 6507:     }
 6508:     if (wantarray) {
 6509:         return ($is_adv,$is_author);
 6510:     }
 6511:     return $is_adv;
 6512: }
 6513: 
 6514: sub check_can_request {
 6515:     my ($dom,$can_request,$request_domains) = @_;
 6516:     my $canreq = 0;
 6517:     my ($types,$typename) = &Apache::loncommon::course_types();
 6518:     my @options = ('approval','validate','autolimit');
 6519:     my $optregex = join('|',@options);
 6520:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 6521:         foreach my $type (@{$types}) {
 6522:             if (&usertools_access($env{'user.name'},
 6523:                                   $env{'user.domain'},
 6524:                                   $type,undef,'requestcourses')) {
 6525:                 $canreq ++;
 6526:                 if (ref($request_domains) eq 'HASH') {
 6527:                     push(@{$request_domains->{$type}},$env{'user.domain'});
 6528:                 }
 6529:                 if ($dom eq $env{'user.domain'}) {
 6530:                     $can_request->{$type} = 1;
 6531:                 }
 6532:             }
 6533:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
 6534:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 6535:                 if (@curr > 0) {
 6536:                     foreach my $item (@curr) {
 6537:                         if (ref($request_domains) eq 'HASH') {
 6538:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 6539:                             if ($otherdom ne '') {
 6540:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 6541:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 6542:                                         push(@{$request_domains->{$type}},$otherdom);
 6543:                                     }
 6544:                                 } else {
 6545:                                     push(@{$request_domains->{$type}},$otherdom);
 6546:                                 }
 6547:                             }
 6548:                         }
 6549:                     }
 6550:                     unless($dom eq $env{'user.domain'}) {
 6551:                         $canreq ++;
 6552:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 6553:                             $can_request->{$type} = 1;
 6554:                         }
 6555:                     }
 6556:                 }
 6557:             }
 6558:         }
 6559:     }
 6560:     return $canreq;
 6561: }
 6562: 
 6563: # ---------------------------------------------- Custom access rule evaluation
 6564: 
 6565: sub customaccess {
 6566:     my ($priv,$uri)=@_;
 6567:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 6568:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 6569:     $udom = &LONCAPA::clean_domain($udom);
 6570:     $ucrs = &LONCAPA::clean_username($ucrs);
 6571:     my $access=0;
 6572:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 6573: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 6574: 	if ($type eq 'user') {
 6575: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 6576: 		my ($tdom,$tuname)=split(m{/},$scope);
 6577: 		if ($tdom) {
 6578: 		    if ($tdom ne $env{'user.domain'}) { next; }
 6579: 		}
 6580: 		if ($tuname) {
 6581: 		    if ($tuname ne $env{'user.name'}) { next; }
 6582: 		}
 6583: 		$access=($effect eq 'allow');
 6584: 		last;
 6585: 	    }
 6586: 	} else {
 6587: 	    if ($role) {
 6588: 		if ($role ne $urole) { next; }
 6589: 	    }
 6590: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 6591: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 6592: 		if ($tdom) {
 6593: 		    if ($tdom ne $udom) { next; }
 6594: 		}
 6595: 		if ($tcrs) {
 6596: 		    if ($tcrs ne $ucrs) { next; }
 6597: 		}
 6598: 		if ($tsec) {
 6599: 		    if ($tsec ne $usec) { next; }
 6600: 		}
 6601: 		$access=($effect eq 'allow');
 6602: 		last;
 6603: 	    }
 6604: 	    if ($realm eq '' && $role eq '') {
 6605: 		$access=($effect eq 'allow');
 6606: 	    }
 6607: 	}
 6608:     }
 6609:     return $access;
 6610: }
 6611: 
 6612: # ------------------------------------------------- Check for a user privilege
 6613: 
 6614: sub allowed {
 6615:     my ($priv,$uri,$symb,$role)=@_;
 6616:     my $ver_orguri=$uri;
 6617:     $uri=&deversion($uri);
 6618:     my $orguri=$uri;
 6619:     $uri=&declutter($uri);
 6620: 
 6621:     if ($priv eq 'evb') {
 6622: # Evade communication block restrictions for specified role in a course
 6623:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 6624:             return $1;
 6625:         } else {
 6626:             return;
 6627:         }
 6628:     }
 6629: 
 6630:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 6631: # Free bre access to adm and meta resources
 6632:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 6633: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 6634: 	&& ($priv eq 'bre')) {
 6635: 	return 'F';
 6636:     }
 6637: 
 6638: # Free bre access to user's own portfolio contents
 6639:     my ($space,$domain,$name,@dir)=split('/',$uri);
 6640:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 6641: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 6642:         my %setters;
 6643:         my ($startblock,$endblock) = 
 6644:             &Apache::loncommon::blockcheck(\%setters,'port');
 6645:         if ($startblock && $endblock) {
 6646:             return 'B';
 6647:         } else {
 6648:             return 'F';
 6649:         }
 6650:     }
 6651: 
 6652: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 6653:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 6654:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 6655:         if (exists($env{'request.course.id'})) {
 6656:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6657:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6658:             if (($domain eq $cdom) && ($name eq $cnum)) {
 6659:                 my $courseprivid=$env{'request.course.id'};
 6660:                 $courseprivid=~s/\_/\//;
 6661:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 6662:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 6663:                     return $1; 
 6664:                 } else {
 6665:                     if ($env{'request.course.sec'}) {
 6666:                         $courseprivid.='/'.$env{'request.course.sec'};
 6667:                     }
 6668:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 6669:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 6670:                         return $2;
 6671:                     }
 6672:                 }
 6673:             }
 6674:         }
 6675:     }
 6676: 
 6677: # Free bre to public access
 6678: 
 6679:     if ($priv eq 'bre') {
 6680:         my $copyright=&metadata($uri,'copyright');
 6681: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 6682:            return 'F'; 
 6683:         }
 6684:         if ($copyright eq 'priv') {
 6685:             $uri=~/([^\/]+)\/([^\/]+)\//;
 6686: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 6687: 		return '';
 6688:             }
 6689:         }
 6690:         if ($copyright eq 'domain') {
 6691:             $uri=~/([^\/]+)\/([^\/]+)\//;
 6692: 	    unless (($env{'user.domain'} eq $1) ||
 6693:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 6694: 		return '';
 6695:             }
 6696:         }
 6697:         if ($env{'request.role'}=~ /li\.\//) {
 6698:             # Library role, so allow browsing of resources in this domain.
 6699:             return 'F';
 6700:         }
 6701:         if ($copyright eq 'custom') {
 6702: 	    unless (&customaccess($priv,$uri)) { return ''; }
 6703:         }
 6704:     }
 6705:     # Domain coordinator is trying to create a course
 6706:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 6707:         # uri is the requested domain in this case.
 6708:         # comparison to 'request.role.domain' shows if the user has selected
 6709:         # a role of dc for the domain in question.
 6710:         return 'F' if ($uri eq $env{'request.role.domain'});
 6711:     }
 6712: 
 6713:     my $thisallowed='';
 6714:     my $statecond=0;
 6715:     my $courseprivid='';
 6716: 
 6717:     my $ownaccess;
 6718:     # Community Coordinator or Assistant Co-author browsing resource space.
 6719:     if (($priv eq 'bro') && ($env{'user.author'})) {
 6720:         if ($uri eq '') {
 6721:             $ownaccess = 1;
 6722:         } else {
 6723:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 6724:                 my $udom = $env{'user.domain'};
 6725:                 my $uname = $env{'user.name'};
 6726:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 6727:                     $ownaccess = 1;
 6728:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 6729:                     unless ($uri =~ m{\.\./}) {
 6730:                         $ownaccess = 1;
 6731:                     }
 6732:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 6733:                     my $now = time;
 6734:                     if ($uri =~ m{^([^/]+)/?$}) {
 6735:                         my $adom = $1;
 6736:                         foreach my $key (keys(%env)) {
 6737:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 6738:                                 my ($start,$end) = split('.',$env{$key});
 6739:                                 if (($now >= $start) && (!$end || $end < $now)) {
 6740:                                     $ownaccess = 1;
 6741:                                     last;
 6742:                                 }
 6743:                             }
 6744:                         }
 6745:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 6746:                         my $adom = $1;
 6747:                         my $aname = $2;
 6748:                         foreach my $role ('ca','aa') { 
 6749:                             if ($env{"user.role.$role./$adom/$aname"}) {
 6750:                                 my ($start,$end) =
 6751:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 6752:                                 if (($now >= $start) && (!$end || $end < $now)) {
 6753:                                     $ownaccess = 1;
 6754:                                     last;
 6755:                                 }
 6756:                             }
 6757:                         }
 6758:                     }
 6759:                 }
 6760:             }
 6761:         }
 6762:     }
 6763: 
 6764: # Course
 6765: 
 6766:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 6767:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6768:             $thisallowed.=$1;
 6769:         }
 6770:     }
 6771: 
 6772: # Domain
 6773: 
 6774:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 6775:        =~/\Q$priv\E\&([^\:]*)/) {
 6776:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6777:             $thisallowed.=$1;
 6778:         }
 6779:     }
 6780: 
 6781: # User who is not author or co-author might still be able to edit
 6782: # resource of an author in the domain (e.g., if Domain Coordinator).
 6783:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 6784:         (&allowed('mdc',$env{'request.course.id'}))) {
 6785:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 6786:             $thisallowed.=$1;
 6787:         }
 6788:     }
 6789: 
 6790: # Course: uri itself is a course
 6791:     my $courseuri=$uri;
 6792:     $courseuri=~s/\_(\d)/\/$1/;
 6793:     $courseuri=~s/^([^\/])/\/$1/;
 6794: 
 6795:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 6796:        =~/\Q$priv\E\&([^\:]*)/) {
 6797:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6798:             $thisallowed.=$1;
 6799:         }
 6800:     }
 6801: 
 6802: # URI is an uploaded document for this course, default permissions don't matter
 6803: # not allowing 'edit' access (editupload) to uploaded course docs
 6804:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 6805: 	$thisallowed='';
 6806:         my ($match)=&is_on_map($uri);
 6807:         if ($match) {
 6808:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 6809:                   =~/\Q$priv\E\&([^\:]*)/) {
 6810:                 my @blockers = &has_comm_blocking($priv,$symb,$uri);
 6811:                 if (@blockers > 0) {
 6812:                     $thisallowed = 'B';
 6813:                 } else {
 6814:                     $thisallowed.=$1;
 6815:                 }
 6816:             }
 6817:         } else {
 6818:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 6819:             if ($refuri) {
 6820:                 if ($refuri =~ m|^/adm/|) {
 6821:                     $thisallowed='F';
 6822:                 } else {
 6823:                     $refuri=&declutter($refuri);
 6824:                     my ($match) = &is_on_map($refuri);
 6825:                     if ($match) {
 6826:                         my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 6827:                         if (@blockers > 0) {
 6828:                             $thisallowed = 'B';
 6829:                         } else {
 6830:                             $thisallowed='F';
 6831:                         }
 6832:                     }
 6833:                 }
 6834:             }
 6835:         }
 6836:     }
 6837: 
 6838:     if ($priv eq 'bre'
 6839: 	&& $thisallowed ne 'F' 
 6840: 	&& $thisallowed ne '2'
 6841: 	&& &is_portfolio_url($uri)) {
 6842: 	$thisallowed = &portfolio_access($uri);
 6843:     }
 6844:     
 6845: # Full access at system, domain or course-wide level? Exit.
 6846:     if ($thisallowed=~/F/) {
 6847: 	return 'F';
 6848:     }
 6849: 
 6850: # If this is generating or modifying users, exit with special codes
 6851: 
 6852:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 6853: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 6854: 	    my ($audom,$auname)=split('/',$uri);
 6855: # no author name given, so this just checks on the general right to make a co-author in this domain
 6856: 	    unless ($auname) { return $thisallowed; }
 6857: # an author name is given, so we are about to actually make a co-author for a certain account
 6858: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 6859: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 6860: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 6861: 	}
 6862: 	return $thisallowed;
 6863:     }
 6864: #
 6865: # Gathered so far: system, domain and course wide privileges
 6866: #
 6867: # Course: See if uri or referer is an individual resource that is part of 
 6868: # the course
 6869: 
 6870:     if ($env{'request.course.id'}) {
 6871: 
 6872:        $courseprivid=$env{'request.course.id'};
 6873:        if ($env{'request.course.sec'}) {
 6874:           $courseprivid.='/'.$env{'request.course.sec'};
 6875:        }
 6876:        $courseprivid=~s/\_/\//;
 6877:        my $checkreferer=1;
 6878:        my ($match,$cond)=&is_on_map($uri);
 6879:        if ($match) {
 6880:            $statecond=$cond;
 6881:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 6882:                =~/\Q$priv\E\&([^\:]*)/) {
 6883:                my $value = $1;
 6884:                if ($priv eq 'bre') {
 6885:                    my @blockers = &has_comm_blocking($priv,$symb,$uri);
 6886:                    if (@blockers > 0) {
 6887:                        $thisallowed = 'B';
 6888:                    } else {
 6889:                        $thisallowed.=$value;
 6890:                    }
 6891:                } else {
 6892:                    $thisallowed.=$value;
 6893:                }
 6894:                $checkreferer=0;
 6895:            }
 6896:        }
 6897:        
 6898:        if ($checkreferer) {
 6899: 	  my $refuri=$env{'httpref.'.$orguri};
 6900:             unless ($refuri) {
 6901:                 foreach my $key (keys(%env)) {
 6902: 		    if ($key=~/^httpref\..*\*/) {
 6903: 			my $pattern=$key;
 6904:                         $pattern=~s/^httpref\.\/res\///;
 6905:                         $pattern=~s/\*/\[\^\/\]\+/g;
 6906:                         $pattern=~s/\//\\\//g;
 6907:                         if ($orguri=~/$pattern/) {
 6908: 			    $refuri=$env{$key};
 6909:                         }
 6910:                     }
 6911:                 }
 6912:             }
 6913: 
 6914:          if ($refuri) { 
 6915: 	  $refuri=&declutter($refuri);
 6916:           my ($match,$cond)=&is_on_map($refuri);
 6917:             if ($match) {
 6918:               my $refstatecond=$cond;
 6919:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 6920:                   =~/\Q$priv\E\&([^\:]*)/) {
 6921:                   my $value = $1;
 6922:                   if ($priv eq 'bre') {
 6923:                       my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 6924:                       if (@blockers > 0) {
 6925:                           $thisallowed = 'B';
 6926:                       } else {
 6927:                           $thisallowed.=$value;
 6928:                       }
 6929:                   } else {
 6930:                       $thisallowed.=$value;
 6931:                   }
 6932:                   $uri=$refuri;
 6933:                   $statecond=$refstatecond;
 6934:               }
 6935:           }
 6936:         }
 6937:        }
 6938:    }
 6939: 
 6940: #
 6941: # Gathered now: all privileges that could apply, and condition number
 6942: # 
 6943: #
 6944: # Full or no access?
 6945: #
 6946: 
 6947:     if ($thisallowed=~/F/) {
 6948: 	return 'F';
 6949:     }
 6950: 
 6951:     unless ($thisallowed) {
 6952:         return '';
 6953:     }
 6954: 
 6955: # Restrictions exist, deal with them
 6956: #
 6957: #   C:according to course preferences
 6958: #   R:according to resource settings
 6959: #   L:unless locked
 6960: #   X:according to user session state
 6961: #
 6962: 
 6963: # Possibly locked functionality, check all courses
 6964: # Locks might take effect only after 10 minutes cache expiration for other
 6965: # courses, and 2 minutes for current course
 6966: 
 6967:     my $envkey;
 6968:     if ($thisallowed=~/L/) {
 6969:         foreach $envkey (keys(%env)) {
 6970:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 6971:                my $courseid=$2;
 6972:                my $roleid=$1.'.'.$2;
 6973:                $courseid=~s/^\///;
 6974:                my $expiretime=600;
 6975:                if ($env{'request.role'} eq $roleid) {
 6976: 		  $expiretime=120;
 6977:                }
 6978: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 6979:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 6980:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 6981: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 6982:                }
 6983:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 6984:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 6985: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 6986:                        &log($env{'user.domain'},$env{'user.name'},
 6987:                             $env{'user.home'},
 6988:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 6989:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 6990:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 6991: 		       return '';
 6992:                    }
 6993:                }
 6994:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 6995:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 6996: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 6997:                        &log($env{'user.domain'},$env{'user.name'},
 6998:                             $env{'user.home'},
 6999:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 7000:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 7001:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 7002: 		       return '';
 7003:                    }
 7004:                }
 7005: 	   }
 7006:        }
 7007:     }
 7008:    
 7009: #
 7010: # Rest of the restrictions depend on selected course
 7011: #
 7012: 
 7013:     unless ($env{'request.course.id'}) {
 7014: 	if ($thisallowed eq 'A') {
 7015: 	    return 'A';
 7016:         } elsif ($thisallowed eq 'B') {
 7017:             return 'B';
 7018: 	} else {
 7019: 	    return '1';
 7020: 	}
 7021:     }
 7022: 
 7023: #
 7024: # Now user is definitely in a course
 7025: #
 7026: 
 7027: 
 7028: # Course preferences
 7029: 
 7030:    if ($thisallowed=~/C/) {
 7031:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 7032:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 7033:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 7034: 	   =~/\Q$rolecode\E/) {
 7035: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 7036: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 7037: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 7038: 			$env{'request.course.id'});
 7039: 	   }
 7040:            return '';
 7041:        }
 7042: 
 7043:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 7044: 	   =~/\Q$unamedom\E/) {
 7045: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 7046: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 7047: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 7048: 			$env{'request.course.id'});
 7049: 	   }
 7050:            return '';
 7051:        }
 7052:    }
 7053: 
 7054: # Resource preferences
 7055: 
 7056:    if ($thisallowed=~/R/) {
 7057:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 7058:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 7059: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 7060: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 7061: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 7062: 	   }
 7063: 	   return '';
 7064:        }
 7065:    }
 7066: 
 7067: # Restricted by state or randomout?
 7068: 
 7069:    if ($thisallowed=~/X/) {
 7070:       if ($env{'acc.randomout'}) {
 7071: 	 if (!$symb) { $symb=&symbread($uri,1); }
 7072:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 7073:             return ''; 
 7074:          }
 7075:       }
 7076:       if (&condval($statecond)) {
 7077: 	 return '2';
 7078:       } else {
 7079:          return '';
 7080:       }
 7081:    }
 7082: 
 7083:     if ($thisallowed eq 'A') {
 7084: 	return 'A';
 7085:     } elsif ($thisallowed eq 'B') {
 7086:         return 'B';
 7087:     }
 7088:    return 'F';
 7089: }
 7090: 
 7091: # ------------------------------------------- Check construction space access
 7092: 
 7093: sub constructaccess {
 7094:     my ($url,$setpriv)=@_;
 7095: 
 7096: # We do not allow editing of previous versions of files
 7097:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
 7098: 
 7099: # Get username and domain from URL
 7100:     my ($ownername,$ownerdomain,$ownerhome);
 7101: 
 7102:     ($ownerdomain,$ownername) =
 7103:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
 7104: 
 7105: # The URL does not really point to any authorspace, forget it
 7106:     unless (($ownername) && ($ownerdomain)) { return ''; }
 7107: 
 7108: # Now we need to see if the user has access to the authorspace of
 7109: # $ownername at $ownerdomain
 7110: 
 7111:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
 7112: # Real author for this?
 7113:        $ownerhome = $env{'user.home'};
 7114:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
 7115:           return ($ownername,$ownerdomain,$ownerhome);
 7116:        }
 7117:     } else {
 7118: # Co-author for this?
 7119:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
 7120:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
 7121:             $ownerhome = &homeserver($ownername,$ownerdomain);
 7122:             return ($ownername,$ownerdomain,$ownerhome);
 7123:         }
 7124:     }
 7125: 
 7126: # We don't have any access right now. If we are not possibly going to do anything about this,
 7127: # we might as well leave
 7128:    unless ($setpriv) { return ''; }
 7129: 
 7130: # Backdoor access?
 7131:     my $allowed=&allowed('eco',$ownerdomain);
 7132: # Nope
 7133:     unless ($allowed) { return ''; }
 7134: # Looks like we may have access, but could be locked by the owner of the construction space
 7135:     if ($allowed eq 'U') {
 7136:         my %blocked=&get('environment',['domcoord.author'],
 7137:                          $ownerdomain,$ownername);
 7138: # Is blocked by owner
 7139:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
 7140:     }
 7141:     if (($allowed eq 'F') || ($allowed eq 'U')) {
 7142: # Grant temporary access
 7143:         my $then=$env{'user.login.time'};
 7144:         my $update=$env{'user.update.time'};
 7145:         if (!$update) { $update = $then; }
 7146:         my $refresh=$env{'user.refresh.time'};
 7147:         if (!$refresh) { $refresh = $update; }
 7148:         my $now = time;
 7149:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
 7150:                            $now,'ca','constructaccess');
 7151:         $ownerhome = &homeserver($ownername,$ownerdomain);
 7152:         return($ownername,$ownerdomain,$ownerhome);
 7153:     }
 7154: # No business here
 7155:     return '';
 7156: }
 7157: 
 7158: sub get_comm_blocks {
 7159:     my ($cdom,$cnum) = @_;
 7160:     if ($cdom eq '' || $cnum eq '') {
 7161:         return unless ($env{'request.course.id'});
 7162:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7163:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7164:     }
 7165:     my %commblocks;
 7166:     my $hashid=$cdom.'_'.$cnum;
 7167:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 7168:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 7169:         %commblocks = %{$blocksref};
 7170:     } else {
 7171:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 7172:         my $cachetime = 600;
 7173:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 7174:     }
 7175:     return %commblocks;
 7176: }
 7177: 
 7178: sub has_comm_blocking {
 7179:     my ($priv,$symb,$uri,$blocks) = @_;
 7180:     return unless ($env{'request.course.id'});
 7181:     return unless ($priv eq 'bre');
 7182:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 7183:     my %commblocks;
 7184:     if (ref($blocks) eq 'HASH') {
 7185:         %commblocks = %{$blocks};
 7186:     } else {
 7187:         %commblocks = &get_comm_blocks();
 7188:     }
 7189:     return unless (keys(%commblocks) > 0);
 7190:     if (!$symb) { $symb=&symbread($uri,1); }
 7191:     my ($map,$resid,undef)=&decode_symb($symb);
 7192:     my %tocheck = (
 7193:                     maps      => $map,
 7194:                     resources => $symb,
 7195:                   );
 7196:     my @blockers;
 7197:     my $now = time;
 7198:     my $navmap = Apache::lonnavmaps::navmap->new();
 7199:     foreach my $block (keys(%commblocks)) {
 7200:         if ($block =~ /^(\d+)____(\d+)$/) {
 7201:             my ($start,$end) = ($1,$2);
 7202:             if ($start <= $now && $end >= $now) {
 7203:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 7204:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 7205:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 7206:                             if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
 7207:                                 unless (grep(/^\Q$block\E$/,@blockers)) {
 7208:                                     push(@blockers,$block);
 7209:                                 }
 7210:                             }
 7211:                         }
 7212:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 7213:                             if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
 7214:                                 unless (grep(/^\Q$block\E$/,@blockers)) {  
 7215:                                     push(@blockers,$block);
 7216:                                 }
 7217:                             }
 7218:                         }
 7219:                     }
 7220:                 }
 7221:             }
 7222:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 7223:             my $item = $1;
 7224:             my @to_test;
 7225:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 7226:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 7227:                     my $check_interval;
 7228:                     if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
 7229:                         my @interval;
 7230:                         my $type = 'map';
 7231:                         if ($item eq 'course') {
 7232:                             $type = 'course';
 7233:                             @interval=&EXT("resource.0.interval");
 7234:                         } else {
 7235:                             if ($item =~ /___\d+___/) {
 7236:                                 $type = 'resource';
 7237:                                 @interval=&EXT("resource.0.interval",$item);
 7238:                                 if (ref($navmap)) {                        
 7239:                                     my $res = $navmap->getBySymb($item); 
 7240:                                     push(@to_test,$res);
 7241:                                 }
 7242:                             } else {
 7243:                                 my $mapsymb = &symbread($item,1);
 7244:                                 if ($mapsymb) {
 7245:                                     if (ref($navmap)) {
 7246:                                         my $mapres = $navmap->getBySymb($mapsymb);
 7247:                                         @to_test = $mapres->retrieveResources($mapres,undef,0,1);
 7248:                                         foreach my $res (@to_test) {
 7249:                                             my $symb = $res->symb();
 7250:                                             next if ($symb eq $mapsymb);
 7251:                                             if ($symb ne '') {
 7252:                                                 @interval=&EXT("resource.0.interval",$symb);
 7253:                                                 last;
 7254:                                             }
 7255:                                         }
 7256:                                     }
 7257:                                 }
 7258:                             }
 7259:                         }
 7260:                         if ($interval[0] =~ /\d+/) {
 7261:                             my $first_access;
 7262:                             if ($type eq 'resource') {
 7263:                                 $first_access=&get_first_access($interval[1],$item);
 7264:                             } elsif ($type eq 'map') {
 7265:                                 $first_access=&get_first_access($interval[1],undef,$item);
 7266:                             } else {
 7267:                                 $first_access=&get_first_access($interval[1]);
 7268:                             }
 7269:                             if ($first_access) {
 7270:                                 my $timesup = $first_access+$interval[0];
 7271:                                 if ($timesup > $now) {
 7272:                                     foreach my $res (@to_test) {
 7273:                                         if ($res->is_problem()) {
 7274:                                             if ($res->completable()) {
 7275:                                                 unless (grep(/^\Q$block\E$/,@blockers)) {
 7276:                                                     push(@blockers,$block);
 7277:                                                 }
 7278:                                                 last;
 7279:                                             }
 7280:                                         }
 7281:                                     }
 7282:                                 }
 7283:                             }
 7284:                         }
 7285:                     }
 7286:                 }
 7287:             }
 7288:         }
 7289:     }
 7290:     return @blockers;
 7291: }
 7292: 
 7293: sub check_docs_block {
 7294:     my ($docsblock,$tocheck) =@_;
 7295:     if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
 7296:         return;
 7297:     }
 7298:     if (ref($docsblock->{'maps'}) eq 'HASH') {
 7299:         if ($tocheck->{'maps'}) {
 7300:             if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
 7301:                 return 1;
 7302:             }
 7303:         }
 7304:     }
 7305:     if (ref($docsblock->{'resources'}) eq 'HASH') {
 7306:         if ($tocheck->{'resources'}) {
 7307:             if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
 7308:                 return 1;
 7309:             }
 7310:         }
 7311:     }
 7312:     return;
 7313: }
 7314: 
 7315: #
 7316: #   Removes the versino from a URI and
 7317: #   splits it in to its filename and path to the filename.
 7318: #   Seems like File::Basename could have done this more clearly.
 7319: #   Parameters:
 7320: #      $uri   - input URI
 7321: #   Returns:
 7322: #     Two element list consisting of 
 7323: #     $pathname  - the URI up to and excluding the trailing /
 7324: #     $filename  - The part of the URI following the last /
 7325: #  NOTE:
 7326: #    Another realization of this is simply:
 7327: #    use File::Basename;
 7328: #    ...
 7329: #    $uri = shift;
 7330: #    $filename = basename($uri);
 7331: #    $path     = dirname($uri);
 7332: #    return ($filename, $path);
 7333: #
 7334: #     The implementation below is probably faster however.
 7335: #
 7336: sub split_uri_for_cond {
 7337:     my $uri=&deversion(&declutter(shift));
 7338:     my @uriparts=split(/\//,$uri);
 7339:     my $filename=pop(@uriparts);
 7340:     my $pathname=join('/',@uriparts);
 7341:     return ($pathname,$filename);
 7342: }
 7343: # --------------------------------------------------- Is a resource on the map?
 7344: 
 7345: sub is_on_map {
 7346:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 7347:     #Trying to find the conditional for the file
 7348:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 7349: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 7350:     if ($match) {
 7351: 	return (1,$1);
 7352:     } else {
 7353: 	return (0,0);
 7354:     }
 7355: }
 7356: 
 7357: # --------------------------------------------------------- Get symb from alias
 7358: 
 7359: sub get_symb_from_alias {
 7360:     my $symb=shift;
 7361:     my ($map,$resid,$url)=&decode_symb($symb);
 7362: # Already is a symb
 7363:     if ($url) { return $symb; }
 7364: # Must be an alias
 7365:     my $aliassymb='';
 7366:     my %bighash;
 7367:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7368:                             &GDBM_READER(),0640)) {
 7369:         my $rid=$bighash{'mapalias_'.$symb};
 7370: 	if ($rid) {
 7371: 	    my ($mapid,$resid)=split(/\./,$rid);
 7372: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 7373: 				    $resid,$bighash{'src_'.$rid});
 7374: 	}
 7375:         untie %bighash;
 7376:     }
 7377:     return $aliassymb;
 7378: }
 7379: 
 7380: # ----------------------------------------------------------------- Define Role
 7381: 
 7382: sub definerole {
 7383:   if (allowed('mcr','/')) {
 7384:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 7385:     foreach my $role (split(':',$sysrole)) {
 7386: 	my ($crole,$cqual)=split(/\&/,$role);
 7387:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 7388:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 7389: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 7390:                return "refused:s:$crole&$cqual"; 
 7391:             }
 7392:         }
 7393:     }
 7394:     foreach my $role (split(':',$domrole)) {
 7395: 	my ($crole,$cqual)=split(/\&/,$role);
 7396:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 7397:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 7398: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 7399:                return "refused:d:$crole&$cqual"; 
 7400:             }
 7401:         }
 7402:     }
 7403:     foreach my $role (split(':',$courole)) {
 7404: 	my ($crole,$cqual)=split(/\&/,$role);
 7405:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 7406:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 7407: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 7408:                return "refused:c:$crole&$cqual"; 
 7409:             }
 7410:         }
 7411:     }
 7412:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 7413:                 "$env{'user.domain'}:$env{'user.name'}:".
 7414: 	        "rolesdef_$rolename=".
 7415:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 7416:     return reply($command,$env{'user.home'});
 7417:   } else {
 7418:     return 'refused';
 7419:   }
 7420: }
 7421: 
 7422: # ---------------- Make a metadata query against the network of library servers
 7423: 
 7424: sub metadata_query {
 7425:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
 7426:     my %rhash;
 7427:     my %libserv = &all_library();
 7428:     my @server_list = (defined($server_array) ? @$server_array
 7429:                                               : keys(%libserv) );
 7430:     for my $server (@server_list) {
 7431:         my $domains = '';
 7432:         if (ref($domains_hash) eq 'HASH') {
 7433:             $domains = $domains_hash->{$server};    
 7434:         }
 7435: 	unless ($custom or $customshow) {
 7436: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
 7437: 	    $rhash{$server}=$reply;
 7438: 	}
 7439: 	else {
 7440: 	    my $reply=&reply("querysend:".&escape($query).':'.
 7441: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
 7442: 			     $server);
 7443: 	    $rhash{$server}=$reply;
 7444: 	}
 7445:     }
 7446:     return \%rhash;
 7447: }
 7448: 
 7449: # ----------------------------------------- Send log queries and wait for reply
 7450: 
 7451: sub log_query {
 7452:     my ($uname,$udom,$query,%filters)=@_;
 7453:     my $uhome=&homeserver($uname,$udom);
 7454:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 7455:     my $uhost=&hostname($uhome);
 7456:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 7457:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 7458:                        $uhome);
 7459:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 7460:     return get_query_reply($queryid);
 7461: }
 7462: 
 7463: # -------------------------- Update MySQL table for portfolio file
 7464: 
 7465: sub update_portfolio_table {
 7466:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 7467:     if ($group ne '') {
 7468:         $file_name =~s /^\Q$group\E//;
 7469:     }
 7470:     my $homeserver = &homeserver($uname,$udom);
 7471:     my $queryid=
 7472:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 7473:                ':'.&escape($file_name).':'.$action,$homeserver);
 7474:     my $reply = &get_query_reply($queryid);
 7475:     return $reply;
 7476: }
 7477: 
 7478: # -------------------------- Update MySQL allusers table
 7479: 
 7480: sub update_allusers_table {
 7481:     my ($uname,$udom,$names) = @_;
 7482:     my $homeserver = &homeserver($uname,$udom);
 7483:     my $queryid=
 7484:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 7485:                'lastname='.&escape($names->{'lastname'}).'%%'.
 7486:                'firstname='.&escape($names->{'firstname'}).'%%'.
 7487:                'middlename='.&escape($names->{'middlename'}).'%%'.
 7488:                'generation='.&escape($names->{'generation'}).'%%'.
 7489:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 7490:                'id='.&escape($names->{'id'}),$homeserver);
 7491:     return;
 7492: }
 7493: 
 7494: # ------- Request retrieval of institutional classlists for course(s)
 7495: 
 7496: sub fetch_enrollment_query {
 7497:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 7498:     my $homeserver;
 7499:     my $maxtries = 1;
 7500:     if ($context eq 'automated') {
 7501:         $homeserver = $perlvar{'lonHostID'};
 7502:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 7503:     } else {
 7504:         $homeserver = &homeserver($cnum,$dom);
 7505:     }
 7506:     my $host=&hostname($homeserver);
 7507:     my $cmd = '';
 7508:     foreach my $affiliate (keys(%{$affiliatesref})) {
 7509:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 7510:     }
 7511:     $cmd =~ s/%%$//;
 7512:     $cmd = &escape($cmd);
 7513:     my $query = 'fetchenrollment';
 7514:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 7515:     unless ($queryid=~/^\Q$host\E\_/) { 
 7516:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 7517:         return 'error: '.$queryid;
 7518:     }
 7519:     my $reply = &get_query_reply($queryid);
 7520:     my $tries = 1;
 7521:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 7522:         $reply = &get_query_reply($queryid);
 7523:         $tries ++;
 7524:     }
 7525:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 7526:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 7527:     } else {
 7528:         my @responses = split(/:/,$reply);
 7529:         if ($homeserver eq $perlvar{'lonHostID'}) {
 7530:             foreach my $line (@responses) {
 7531:                 my ($key,$value) = split(/=/,$line,2);
 7532:                 $$replyref{$key} = $value;
 7533:             }
 7534:         } else {
 7535:             my $pathname = LONCAPA::tempdir();
 7536:             foreach my $line (@responses) {
 7537:                 my ($key,$value) = split(/=/,$line);
 7538:                 $$replyref{$key} = $value;
 7539:                 if ($value > 0) {
 7540:                     foreach my $item (@{$$affiliatesref{$key}}) {
 7541:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 7542:                         my $destname = $pathname.'/'.$filename;
 7543:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 7544:                         if ($xml_classlist =~ /^error/) {
 7545:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 7546:                         } else {
 7547:                             if ( open(FILE,">$destname") ) {
 7548:                                 print FILE &unescape($xml_classlist);
 7549:                                 close(FILE);
 7550:                             } else {
 7551:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 7552:                             }
 7553:                         }
 7554:                     }
 7555:                 }
 7556:             }
 7557:         }
 7558:         return 'ok';
 7559:     }
 7560:     return 'error';
 7561: }
 7562: 
 7563: sub get_query_reply {
 7564:     my $queryid=shift;
 7565:     my $replyfile=LONCAPA::tempdir().$queryid;
 7566:     my $reply='';
 7567:     for (1..100) {
 7568: 	sleep 2;
 7569:         if (-e $replyfile.'.end') {
 7570: 	    if (open(my $fh,$replyfile)) {
 7571: 		$reply = join('',<$fh>);
 7572: 		close($fh);
 7573: 	   } else { return 'error: reply_file_error'; }
 7574:            return &unescape($reply);
 7575: 	}
 7576:     }
 7577:     return 'timeout:'.$queryid;
 7578: }
 7579: 
 7580: sub courselog_query {
 7581: #
 7582: # possible filters:
 7583: # url: url or symb
 7584: # username
 7585: # domain
 7586: # action: view, submit, grade
 7587: # start: timestamp
 7588: # end: timestamp
 7589: #
 7590:     my (%filters)=@_;
 7591:     unless ($env{'request.course.id'}) { return 'no_course'; }
 7592:     if ($filters{'url'}) {
 7593: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 7594:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 7595:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 7596:     }
 7597:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7598:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7599:     return &log_query($cname,$cdom,'courselog',%filters);
 7600: }
 7601: 
 7602: sub userlog_query {
 7603: #
 7604: # possible filters:
 7605: # action: log check role
 7606: # start: timestamp
 7607: # end: timestamp
 7608: #
 7609:     my ($uname,$udom,%filters)=@_;
 7610:     return &log_query($uname,$udom,'userlog',%filters);
 7611: }
 7612: 
 7613: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 7614: 
 7615: sub auto_run {
 7616:     my ($cnum,$cdom) = @_;
 7617:     my $response = 0;
 7618:     my $settings;
 7619:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 7620:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 7621:         $settings = $domconfig{'autoenroll'};
 7622:         if ($settings->{'run'} eq '1') {
 7623:             $response = 1;
 7624:         }
 7625:     } else {
 7626:         my $homeserver;
 7627:         if (&is_course($cdom,$cnum)) {
 7628:             $homeserver = &homeserver($cnum,$cdom);
 7629:         } else {
 7630:             $homeserver = &domain($cdom,'primary');
 7631:         }
 7632:         if ($homeserver ne 'no_host') {
 7633:             $response = &reply('autorun:'.$cdom,$homeserver);
 7634:         }
 7635:     }
 7636:     return $response;
 7637: }
 7638: 
 7639: sub auto_get_sections {
 7640:     my ($cnum,$cdom,$inst_coursecode) = @_;
 7641:     my $homeserver;
 7642:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 7643:         $homeserver = &homeserver($cnum,$cdom);
 7644:     }
 7645:     if (!defined($homeserver)) { 
 7646:         if ($cdom =~ /^$match_domain$/) {
 7647:             $homeserver = &domain($cdom,'primary');
 7648:         }
 7649:     }
 7650:     my @secs;
 7651:     if (defined($homeserver)) {
 7652:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 7653:         unless ($response eq 'refused') {
 7654:             @secs = split(/:/,$response);
 7655:         }
 7656:     }
 7657:     return @secs;
 7658: }
 7659: 
 7660: sub auto_new_course {
 7661:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 7662:     my $homeserver = &homeserver($cnum,$cdom);
 7663:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 7664:     return $response;
 7665: }
 7666: 
 7667: sub auto_validate_courseID {
 7668:     my ($cnum,$cdom,$inst_course_id) = @_;
 7669:     my $homeserver = &homeserver($cnum,$cdom);
 7670:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 7671:     return $response;
 7672: }
 7673: 
 7674: sub auto_validate_instcode {
 7675:     my ($cnum,$cdom,$instcode,$owner) = @_;
 7676:     my ($homeserver,$response);
 7677:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 7678:         $homeserver = &homeserver($cnum,$cdom);
 7679:     }
 7680:     if (!defined($homeserver)) {
 7681:         if ($cdom =~ /^$match_domain$/) {
 7682:             $homeserver = &domain($cdom,'primary');
 7683:         }
 7684:     }
 7685:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 7686:                         &escape($instcode).':'.&escape($owner),$homeserver));
 7687:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
 7688:     return ($outcome,$description,$defaultcredits);
 7689: }
 7690: 
 7691: sub auto_create_password {
 7692:     my ($cnum,$cdom,$authparam,$udom) = @_;
 7693:     my ($homeserver,$response);
 7694:     my $create_passwd = 0;
 7695:     my $authchk = '';
 7696:     if ($udom =~ /^$match_domain$/) {
 7697:         $homeserver = &domain($udom,'primary');
 7698:     }
 7699:     if ($homeserver eq '') {
 7700:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 7701:             $homeserver = &homeserver($cnum,$cdom);
 7702:         }
 7703:     }
 7704:     if ($homeserver eq '') {
 7705:         $authchk = 'nodomain';
 7706:     } else {
 7707:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 7708:         if ($response eq 'refused') {
 7709:             $authchk = 'refused';
 7710:         } else {
 7711:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 7712:         }
 7713:     }
 7714:     return ($authparam,$create_passwd,$authchk);
 7715: }
 7716: 
 7717: sub auto_photo_permission {
 7718:     my ($cnum,$cdom,$students) = @_;
 7719:     my $homeserver = &homeserver($cnum,$cdom);
 7720:     my ($outcome,$perm_reqd,$conditions) = 
 7721: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 7722:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7723: 	return (undef,undef);
 7724:     }
 7725:     return ($outcome,$perm_reqd,$conditions);
 7726: }
 7727: 
 7728: sub auto_checkphotos {
 7729:     my ($uname,$udom,$pid) = @_;
 7730:     my $homeserver = &homeserver($uname,$udom);
 7731:     my ($result,$resulttype);
 7732:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 7733: 				   &escape($uname).':'.&escape($pid),
 7734: 				   $homeserver));
 7735:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7736: 	return (undef,undef);
 7737:     }
 7738:     if ($outcome) {
 7739:         ($result,$resulttype) = split(/:/,$outcome);
 7740:     } 
 7741:     return ($result,$resulttype);
 7742: }
 7743: 
 7744: sub auto_photochoice {
 7745:     my ($cnum,$cdom) = @_;
 7746:     my $homeserver = &homeserver($cnum,$cdom);
 7747:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 7748: 						       &escape($cdom),
 7749: 						       $homeserver)));
 7750:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7751: 	return (undef,undef);
 7752:     }
 7753:     return ($update,$comment);
 7754: }
 7755: 
 7756: sub auto_photoupdate {
 7757:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 7758:     my $homeserver = &homeserver($cnum,$dom);
 7759:     my $host=&hostname($homeserver);
 7760:     my $cmd = '';
 7761:     my $maxtries = 1;
 7762:     foreach my $affiliate (keys(%{$affiliatesref})) {
 7763:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 7764:     }
 7765:     $cmd =~ s/%%$//;
 7766:     $cmd = &escape($cmd);
 7767:     my $query = 'institutionalphotos';
 7768:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 7769:     unless ($queryid=~/^\Q$host\E\_/) {
 7770:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 7771:         return 'error: '.$queryid;
 7772:     }
 7773:     my $reply = &get_query_reply($queryid);
 7774:     my $tries = 1;
 7775:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 7776:         $reply = &get_query_reply($queryid);
 7777:         $tries ++;
 7778:     }
 7779:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 7780:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 7781:     } else {
 7782:         my @responses = split(/:/,$reply);
 7783:         my $outcome = shift(@responses); 
 7784:         foreach my $item (@responses) {
 7785:             my ($key,$value) = split(/=/,$item);
 7786:             $$photo{$key} = $value;
 7787:         }
 7788:         return $outcome;
 7789:     }
 7790:     return 'error';
 7791: }
 7792: 
 7793: sub auto_instcode_format {
 7794:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 7795: 	$cat_order) = @_;
 7796:     my $courses = '';
 7797:     my @homeservers;
 7798:     if ($caller eq 'global') {
 7799: 	my %servers = &get_servers($codedom,'library');
 7800: 	foreach my $tryserver (keys(%servers)) {
 7801: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7802: 		push(@homeservers,$tryserver);
 7803: 	    }
 7804:         }
 7805:     } elsif ($caller eq 'requests') {
 7806:         if ($codedom =~ /^$match_domain$/) {
 7807:             my $chome = &domain($codedom,'primary');
 7808:             unless ($chome eq 'no_host') {
 7809:                 push(@homeservers,$chome);
 7810:             }
 7811:         }
 7812:     } else {
 7813:         push(@homeservers,&homeserver($caller,$codedom));
 7814:     }
 7815:     foreach my $code (keys(%{$instcodes})) {
 7816:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 7817:     }
 7818:     chop($courses);
 7819:     my $ok_response = 0;
 7820:     my $response;
 7821:     while (@homeservers > 0 && $ok_response == 0) {
 7822:         my $server = shift(@homeservers); 
 7823:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 7824:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 7825:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 7826: 		split(/:/,$response);
 7827:             %{$codes} = (%{$codes},&str2hash($codes_str));
 7828:             push(@{$codetitles},&str2array($codetitles_str));
 7829:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 7830:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 7831:             $ok_response = 1;
 7832:         }
 7833:     }
 7834:     if ($ok_response) {
 7835:         return 'ok';
 7836:     } else {
 7837:         return $response;
 7838:     }
 7839: }
 7840: 
 7841: sub auto_instcode_defaults {
 7842:     my ($domain,$returnhash,$code_order) = @_;
 7843:     my @homeservers;
 7844: 
 7845:     my %servers = &get_servers($domain,'library');
 7846:     foreach my $tryserver (keys(%servers)) {
 7847: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7848: 	    push(@homeservers,$tryserver);
 7849: 	}
 7850:     }
 7851: 
 7852:     my $response;
 7853:     foreach my $server (@homeservers) {
 7854:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 7855:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 7856: 	
 7857: 	foreach my $pair (split(/\&/,$response)) {
 7858: 	    my ($name,$value)=split(/\=/,$pair);
 7859: 	    if ($name eq 'code_order') {
 7860: 		@{$code_order} = split(/\&/,&unescape($value));
 7861: 	    } else {
 7862: 		$returnhash->{&unescape($name)}=&unescape($value);
 7863: 	    }
 7864: 	}
 7865: 	return 'ok';
 7866:     }
 7867: 
 7868:     return $response;
 7869: }
 7870: 
 7871: sub auto_possible_instcodes {
 7872:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 7873:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 7874:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 7875:         return;
 7876:     }
 7877:     my (@homeservers,$uhome);
 7878:     if (defined(&domain($domain,'primary'))) {
 7879:         $uhome=&domain($domain,'primary');
 7880:         push(@homeservers,&domain($domain,'primary'));
 7881:     } else {
 7882:         my %servers = &get_servers($domain,'library');
 7883:         foreach my $tryserver (keys(%servers)) {
 7884:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7885:                 push(@homeservers,$tryserver);
 7886:             }
 7887:         }
 7888:     }
 7889:     my $response;
 7890:     foreach my $server (@homeservers) {
 7891:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 7892:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 7893:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 7894:             split(':',$response);
 7895:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 7896:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 7897:         foreach my $item (split('&',$cat_title)) {   
 7898:             my ($name,$value)=split('=',$item);
 7899:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 7900:         }
 7901:         foreach my $item (split('&',$cat_order)) {
 7902:             my ($name,$value)=split('=',$item);
 7903:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 7904:         }
 7905:         return 'ok';
 7906:     }
 7907:     return $response;
 7908: }
 7909: 
 7910: sub auto_courserequest_checks {
 7911:     my ($dom) = @_;
 7912:     my ($homeserver,%validations);
 7913:     if ($dom =~ /^$match_domain$/) {
 7914:         $homeserver = &domain($dom,'primary');
 7915:     }
 7916:     unless ($homeserver eq 'no_host') {
 7917:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 7918:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 7919:             my @items = split(/&/,$response);
 7920:             foreach my $item (@items) {
 7921:                 my ($key,$value) = split('=',$item);
 7922:                 $validations{&unescape($key)} = &thaw_unescape($value);
 7923:             }
 7924:         }
 7925:     }
 7926:     return %validations; 
 7927: }
 7928: 
 7929: sub auto_courserequest_validation {
 7930:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
 7931:     my ($homeserver,$response);
 7932:     if ($dom =~ /^$match_domain$/) {
 7933:         $homeserver = &domain($dom,'primary');
 7934:     }
 7935:     unless ($homeserver eq 'no_host') {
 7936:         my $customdata;
 7937:         if (ref($custominfo) eq 'HASH') {
 7938:             $customdata = &freeze_escape($custominfo);
 7939:         }
 7940:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 7941:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 7942:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
 7943:                                     $customdata,$homeserver));
 7944:     }
 7945:     return $response;
 7946: }
 7947: 
 7948: sub auto_validate_class_sec {
 7949:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 7950:     my $homeserver = &homeserver($cnum,$cdom);
 7951:     my $ownerlist;
 7952:     if (ref($owners) eq 'ARRAY') {
 7953:         $ownerlist = join(',',@{$owners});
 7954:     } else {
 7955:         $ownerlist = $owners;
 7956:     }
 7957:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 7958:                         &escape($ownerlist).':'.$cdom,$homeserver);
 7959:     return $response;
 7960: }
 7961: 
 7962: sub auto_crsreq_update {
 7963:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
 7964:         $code,$inbound) = @_;
 7965:     my ($homeserver,%crsreqresponse);
 7966:     if ($cdom =~ /^$match_domain$/) {
 7967:         $homeserver = &domain($cdom,'primary');
 7968:     }
 7969:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 7970:         my $info;
 7971:         if (ref($inbound) eq 'HASH') {
 7972:             $info = &freeze_escape($inbound);
 7973:         }
 7974:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
 7975:                             ':'.&escape($action).':'.&escape($ownername).':'.
 7976:                             &escape($ownerdomain).':'.&escape($fullname).':'.
 7977:                             &escape($title).':'.&escape($code).':'.$info,$homeserver);
 7978:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 7979:             my @items = split(/&/,$response);
 7980:             foreach my $item (@items) {
 7981:                 my ($key,$value) = split('=',$item);
 7982:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
 7983:             }
 7984:         }
 7985:     }
 7986:     return \%crsreqresponse;
 7987: }
 7988: 
 7989: # ------------------------------------------------------- Course Group routines
 7990: 
 7991: sub get_coursegroups {
 7992:     my ($cdom,$cnum,$group,$namespace) = @_;
 7993:     return(&dump($namespace,$cdom,$cnum,$group));
 7994: }
 7995: 
 7996: sub modify_coursegroup {
 7997:     my ($cdom,$cnum,$groupsettings) = @_;
 7998:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 7999: }
 8000: 
 8001: sub toggle_coursegroup_status {
 8002:     my ($cdom,$cnum,$group,$action) = @_;
 8003:     my ($from_namespace,$to_namespace);
 8004:     if ($action eq 'delete') {
 8005:         $from_namespace = 'coursegroups';
 8006:         $to_namespace = 'deleted_groups';
 8007:     } else {
 8008:         $from_namespace = 'deleted_groups';
 8009:         $to_namespace = 'coursegroups';
 8010:     }
 8011:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 8012:     if (my $tmp = &error(%curr_group)) {
 8013:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 8014:         return ('read error',$tmp);
 8015:     } else {
 8016:         my %savedsettings = %curr_group; 
 8017:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 8018:         my $deloutcome;
 8019:         if ($result eq 'ok') {
 8020:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 8021:         } else {
 8022:             return ('write error',$result);
 8023:         }
 8024:         if ($deloutcome eq 'ok') {
 8025:             return 'ok';
 8026:         } else {
 8027:             return ('delete error',$deloutcome);
 8028:         }
 8029:     }
 8030: }
 8031: 
 8032: sub modify_group_roles {
 8033:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 8034:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 8035:     my $role = 'gr/'.&escape($userprivs);
 8036:     my ($uname,$udom) = split(/:/,$user);
 8037:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 8038:     if ($result eq 'ok') {
 8039:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 8040:     }
 8041:     return $result;
 8042: }
 8043: 
 8044: sub modify_coursegroup_membership {
 8045:     my ($cdom,$cnum,$membership) = @_;
 8046:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 8047:     return $result;
 8048: }
 8049: 
 8050: sub get_active_groups {
 8051:     my ($udom,$uname,$cdom,$cnum) = @_;
 8052:     my $now = time;
 8053:     my %groups = ();
 8054:     foreach my $key (keys(%env)) {
 8055:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 8056:             my ($start,$end) = split(/\./,$env{$key});
 8057:             if (($end!=0) && ($end<$now)) { next; }
 8058:             if (($start!=0) && ($start>$now)) { next; }
 8059:             if ($1 eq $cdom && $2 eq $cnum) {
 8060:                 $groups{$3} = $env{$key} ;
 8061:             }
 8062:         }
 8063:     }
 8064:     return %groups;
 8065: }
 8066: 
 8067: sub get_group_membership {
 8068:     my ($cdom,$cnum,$group) = @_;
 8069:     return(&dump('groupmembership',$cdom,$cnum,$group));
 8070: }
 8071: 
 8072: sub get_users_groups {
 8073:     my ($udom,$uname,$courseid) = @_;
 8074:     my @usersgroups;
 8075:     my $cachetime=1800;
 8076: 
 8077:     my $hashid="$udom:$uname:$courseid";
 8078:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 8079:     if (defined($cached)) {
 8080:         @usersgroups = split(/:/,$grouplist);
 8081:     } else {  
 8082:         $grouplist = '';
 8083:         my $courseurl = &courseid_to_courseurl($courseid);
 8084:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 8085:         my $access_end = $env{'course.'.$courseid.
 8086:                               '.default_enrollment_end_date'};
 8087:         my $now = time;
 8088:         foreach my $key (keys(%roleshash)) {
 8089:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 8090:                 my $group = $1;
 8091:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 8092:                     my $start = $2;
 8093:                     my $end = $1;
 8094:                     if ($start == -1) { next; } # deleted from group
 8095:                     if (($start!=0) && ($start>$now)) { next; }
 8096:                     if (($end!=0) && ($end<$now)) {
 8097:                         if ($access_end && $access_end < $now) {
 8098:                             if ($access_end - $end < 86400) {
 8099:                                 push(@usersgroups,$group);
 8100:                             }
 8101:                         }
 8102:                         next;
 8103:                     }
 8104:                     push(@usersgroups,$group);
 8105:                 }
 8106:             }
 8107:         }
 8108:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 8109:         $grouplist = join(':',@usersgroups);
 8110:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 8111:     }
 8112:     return @usersgroups;
 8113: }
 8114: 
 8115: sub devalidate_getgroups_cache {
 8116:     my ($udom,$uname,$cdom,$cnum)=@_;
 8117:     my $courseid = $cdom.'_'.$cnum;
 8118: 
 8119:     my $hashid="$udom:$uname:$courseid";
 8120:     &devalidate_cache_new('getgroups',$hashid);
 8121: }
 8122: 
 8123: # ------------------------------------------------------------------ Plain Text
 8124: 
 8125: sub plaintext {
 8126:     my ($short,$type,$cid,$forcedefault) = @_;
 8127:     if ($short =~ m{^cr/}) {
 8128: 	return (split('/',$short))[-1];
 8129:     }
 8130:     if (!defined($cid)) {
 8131:         $cid = $env{'request.course.id'};
 8132:     }
 8133:     my %rolenames = (
 8134:                       Course    => 'std',
 8135:                       Community => 'alt1',
 8136:                     );
 8137:     if ($cid ne '') {
 8138:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 8139:             unless ($forcedefault) {
 8140:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 8141:                 &Apache::lonlocal::mt_escape(\$roletext);
 8142:                 return &Apache::lonlocal::mt($roletext);
 8143:             }
 8144:         }
 8145:     }
 8146:     if ((defined($type)) && (defined($rolenames{$type})) &&
 8147:         (defined($rolenames{$type})) && 
 8148:         (defined($prp{$short}{$rolenames{$type}}))) {
 8149:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 8150:     } elsif ($cid ne '') {
 8151:         my $crstype = $env{'course.'.$cid.'.type'};
 8152:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
 8153:             (defined($prp{$short}{$rolenames{$crstype}}))) {
 8154:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
 8155:         }
 8156:     }
 8157:     return &Apache::lonlocal::mt($prp{$short}{'std'});
 8158: }
 8159: 
 8160: # ----------------------------------------------------------------- Assign Role
 8161: 
 8162: sub assignrole {
 8163:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 8164:         $context)=@_;
 8165:     my $mrole;
 8166:     if ($role =~ /^cr\//) {
 8167:         my $cwosec=$url;
 8168:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 8169: 	unless (&allowed('ccr',$cwosec)) {
 8170:            my $refused = 1;
 8171:            if ($context eq 'requestcourses') {
 8172:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 8173:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
 8174:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
 8175:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 8176:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 8177:                            if ($crsenv{'internal.courseowner'} eq
 8178:                                $env{'user.name'}.':'.$env{'user.domain'}) {
 8179:                                $refused = '';
 8180:                            }
 8181:                        }
 8182:                    }
 8183:                }
 8184:            }
 8185:            if ($refused) {
 8186:                &logthis('Refused custom assignrole: '.
 8187:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
 8188:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
 8189:                return 'refused';
 8190:            }
 8191:         }
 8192:         $mrole='cr';
 8193:     } elsif ($role =~ /^gr\//) {
 8194:         my $cwogrp=$url;
 8195:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 8196:         unless (&allowed('mdg',$cwogrp)) {
 8197:             &logthis('Refused group assignrole: '.
 8198:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 8199:                     $env{'user.name'}.' at '.$env{'user.domain'});
 8200:             return 'refused';
 8201:         }
 8202:         $mrole='gr';
 8203:     } else {
 8204:         my $cwosec=$url;
 8205:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 8206:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 8207:             my $refused;
 8208:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 8209:                 if (!(&allowed('c'.$role,$url))) {
 8210:                     $refused = 1;
 8211:                 }
 8212:             } else {
 8213:                 $refused = 1;
 8214:             }
 8215:             if ($refused) {
 8216:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 8217:                 if (!$selfenroll && $context eq 'course') {
 8218:                     my %crsenv;
 8219:                     if ($role eq 'cc' || $role eq 'co') {
 8220:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 8221:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
 8222:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
 8223:                                 if ($crsenv{'internal.courseowner'} eq 
 8224:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 8225:                                     $refused = '';
 8226:                                 }
 8227:                             }
 8228:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
 8229:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
 8230:                                 if ($crsenv{'internal.courseowner'} eq 
 8231:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 8232:                                     $refused = '';
 8233:                                 }
 8234:                             }
 8235:                         }
 8236:                     }
 8237:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 8238:                     $refused = '';
 8239:                 } elsif ($context eq 'requestcourses') {
 8240:                     my @possroles = ('st','ta','ep','in','cc','co');
 8241:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
 8242:                         my $wrongcc;
 8243:                         if ($cnum =~ /^$match_community$/) {
 8244:                             $wrongcc = 1 if ($role eq 'cc');
 8245:                         } else {
 8246:                             $wrongcc = 1 if ($role eq 'co');
 8247:                         }
 8248:                         unless ($wrongcc) {
 8249:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 8250:                             if ($crsenv{'internal.courseowner'} eq 
 8251:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
 8252:                                 $refused = '';
 8253:                             }
 8254:                         }
 8255:                     }
 8256:                 } elsif ($context eq 'requestauthor') {
 8257:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 8258:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
 8259:                         if ($env{'environment.requestauthor'} eq 'automatic') {
 8260:                             $refused = '';
 8261:                         } else {
 8262:                             my %domdefaults = &get_domain_defaults($udom);
 8263:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
 8264:                                 my $checkbystatus;
 8265:                                 if ($env{'user.adv'}) {
 8266:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
 8267:                                     if ($disposition eq 'automatic') {
 8268:                                         $refused = '';
 8269:                                     } elsif ($disposition eq '') {
 8270:                                         $checkbystatus = 1;
 8271:                                     }
 8272:                                 } else {
 8273:                                     $checkbystatus = 1;
 8274:                                 }
 8275:                                 if ($checkbystatus) {
 8276:                                     if ($env{'environment.inststatus'}) {
 8277:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
 8278:                                         foreach my $type (@inststatuses) {
 8279:                                             if (($type ne '') &&
 8280:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
 8281:                                                 $refused = '';
 8282:                                             }
 8283:                                         }
 8284:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
 8285:                                         $refused = '';
 8286:                                     }
 8287:                                 }
 8288:                             }
 8289:                         }
 8290:                     }
 8291:                 }
 8292:                 if ($refused) {
 8293:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 8294:                              ' '.$role.' '.$end.' '.$start.' by '.
 8295: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 8296:                     return 'refused';
 8297:                 }
 8298:             }
 8299:         } elsif ($role eq 'au') {
 8300:             if ($url ne '/'.$udom.'/') {
 8301:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
 8302:                          ' to assign author role for '.$uname.':'.$udom.
 8303:                          ' in domain: '.$url.' refused (wrong domain).');
 8304:                 return 'refused';
 8305:             }
 8306:         }
 8307:         $mrole=$role;
 8308:     }
 8309:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 8310:                 "$udom:$uname:$url".'_'."$mrole=$role";
 8311:     if ($end) { $command.='_'.$end; }
 8312:     if ($start) {
 8313: 	if ($end) { 
 8314:            $command.='_'.$start; 
 8315:         } else {
 8316:            $command.='_0_'.$start;
 8317:         }
 8318:     }
 8319:     my $origstart = $start;
 8320:     my $origend = $end;
 8321:     my $delflag;
 8322: # actually delete
 8323:     if ($deleteflag) {
 8324: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 8325: # modify command to delete the role
 8326:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 8327:                 "$udom:$uname:$url".'_'."$mrole";
 8328: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 8329: # set start and finish to negative values for userrolelog
 8330:            $start=-1;
 8331:            $end=-1;
 8332:            $delflag = 1;
 8333:         }
 8334:     }
 8335: # send command
 8336:     my $answer=&reply($command,&homeserver($uname,$udom));
 8337: # log new user role if status is ok
 8338:     if ($answer eq 'ok') {
 8339: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 8340:         if (($role eq 'cc') || ($role eq 'in') ||
 8341:             ($role eq 'ep') || ($role eq 'ad') ||
 8342:             ($role eq 'ta') || ($role eq 'st') ||
 8343:             ($role=~/^cr/) || ($role eq 'gr') ||
 8344:             ($role eq 'co')) {
 8345: # for course roles, perform group memberships changes triggered by role change.
 8346:             unless ($role =~ /^gr/) {
 8347:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 8348:                                                  $origstart,$selfenroll,$context);
 8349:             }
 8350:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 8351:                            $selfenroll,$context);
 8352:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
 8353:                  ($role eq 'au') || ($role eq 'dc')) {
 8354:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 8355:                            $context);
 8356:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
 8357:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 8358:                              $context);
 8359:         }
 8360:         if ($role eq 'cc') {
 8361:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
 8362:         }
 8363:     }
 8364:     return $answer;
 8365: }
 8366: 
 8367: sub autoupdate_coowners {
 8368:     my ($url,$end,$start,$uname,$udom) = @_;
 8369:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
 8370:     if (($cdom ne '') && ($cnum ne '')) {
 8371:         my $now = time;
 8372:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
 8373:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
 8374:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
 8375:             my $instcode = $coursehash{'internal.coursecode'};
 8376:             if ($instcode ne '') {
 8377:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
 8378:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
 8379:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
 8380:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
 8381:                         if ($result eq 'valid') {
 8382:                             if ($coursehash{'internal.co-owners'}) {
 8383:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 8384:                                     push(@newcoowners,$coowner);
 8385:                                 }
 8386:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
 8387:                                     push(@newcoowners,$uname.':'.$udom);
 8388:                                 }
 8389:                                 @newcoowners = sort(@newcoowners);
 8390:                             } else {
 8391:                                 push(@newcoowners,$uname.':'.$udom);
 8392:                             }
 8393:                         } else {
 8394:                             if ($coursehash{'internal.co-owners'}) {
 8395:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 8396:                                     unless ($coowner eq $uname.':'.$udom) {
 8397:                                         push(@newcoowners,$coowner);
 8398:                                     }
 8399:                                 }
 8400:                                 unless (@newcoowners > 0) {
 8401:                                     $delcoowners = 1;
 8402:                                     $coowners = '';
 8403:                                 }
 8404:                             }
 8405:                         }
 8406:                         if (@newcoowners || $delcoowners) {
 8407:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
 8408:                                             $delcoowners,@newcoowners);
 8409:                         }
 8410:                     }
 8411:                 }
 8412:             }
 8413:         }
 8414:     }
 8415: }
 8416: 
 8417: sub store_coowners {
 8418:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
 8419:     my $cid = $cdom.'_'.$cnum;
 8420:     my ($coowners,$delresult,$putresult);
 8421:     if (@newcoowners) {
 8422:         $coowners = join(',',@newcoowners);
 8423:         my %coownershash = (
 8424:                             'internal.co-owners' => $coowners,
 8425:                            );
 8426:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
 8427:         if ($putresult eq 'ok') {
 8428:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
 8429:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
 8430:             }
 8431:         }
 8432:     }
 8433:     if ($delcoowners) {
 8434:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
 8435:         if ($delresult eq 'ok') {
 8436:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
 8437:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
 8438:             }
 8439:         }
 8440:     }
 8441:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
 8442:         my %crsinfo =
 8443:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 8444:         if (ref($crsinfo{$cid}) eq 'HASH') {
 8445:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
 8446:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
 8447:         }
 8448:     }
 8449: }
 8450: 
 8451: # -------------------------------------------------- Modify user authentication
 8452: # Overrides without validation
 8453: 
 8454: sub modifyuserauth {
 8455:     my ($udom,$uname,$umode,$upass)=@_;
 8456:     my $uhome=&homeserver($uname,$udom);
 8457:     unless (&allowed('mau',$udom)) { return 'refused'; }
 8458:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 8459:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 8460:              ' in domain '.$env{'request.role.domain'});  
 8461:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 8462: 		     &escape($upass),$uhome);
 8463:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 8464:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 8465:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 8466:     &log($udom,,$uname,$uhome,
 8467:         'Authentication changed by '.$env{'user.domain'}.', '.
 8468:                                      $env{'user.name'}.', '.$umode.
 8469:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 8470:     unless ($reply eq 'ok') {
 8471:         &logthis('Authentication mode error: '.$reply);
 8472: 	return 'error: '.$reply;
 8473:     }   
 8474:     return 'ok';
 8475: }
 8476: 
 8477: # --------------------------------------------------------------- Modify a user
 8478: 
 8479: sub modifyuser {
 8480:     my ($udom,    $uname, $uid,
 8481:         $umode,   $upass, $first,
 8482:         $middle,  $last,  $gene,
 8483:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
 8484:     $udom= &LONCAPA::clean_domain($udom);
 8485:     $uname=&LONCAPA::clean_username($uname);
 8486:     my $showcandelete = 'none';
 8487:     if (ref($candelete) eq 'ARRAY') {
 8488:         if (@{$candelete} > 0) {
 8489:             $showcandelete = join(', ',@{$candelete});
 8490:         }
 8491:     }
 8492:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 8493:              $umode.', '.$first.', '.$middle.', '.
 8494: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
 8495:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 8496:                                      ' desiredhome not specified'). 
 8497:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 8498:              ' in domain '.$env{'request.role.domain'});
 8499:     my $uhome=&homeserver($uname,$udom,'true');
 8500:     my $newuser;
 8501:     if ($uhome eq 'no_host') {
 8502:         $newuser = 1;
 8503:     }
 8504: # ----------------------------------------------------------------- Create User
 8505:     if (($uhome eq 'no_host') && 
 8506: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 8507:         my $unhome='';
 8508:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 8509:             $unhome = $desiredhome;
 8510: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 8511: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 8512:         } else { # load balancing routine for determining $unhome
 8513:             my $loadm=10000000;
 8514: 	    my %servers = &get_servers($udom,'library');
 8515: 	    foreach my $tryserver (keys(%servers)) {
 8516: 		my $answer=reply('load',$tryserver);
 8517: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 8518: 		    $loadm=$answer;
 8519: 		    $unhome=$tryserver;
 8520: 		}
 8521: 	    }
 8522:         }
 8523:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 8524: 	    return 'error: unable to find a home server for '.$uname.
 8525:                    ' in domain '.$udom;
 8526:         }
 8527:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 8528:                          &escape($upass),$unhome);
 8529: 	unless ($reply eq 'ok') {
 8530:             return 'error: '.$reply;
 8531:         }   
 8532:         $uhome=&homeserver($uname,$udom,'true');
 8533:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 8534: 	    return 'error: unable verify users home machine.';
 8535:         }
 8536:     }   # End of creation of new user
 8537: # ---------------------------------------------------------------------- Add ID
 8538:     if ($uid) {
 8539:        $uid=~tr/A-Z/a-z/;
 8540:        my %uidhash=&idrget($udom,$uname);
 8541:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 8542:          && (!$forceid)) {
 8543: 	  unless ($uid eq $uidhash{$uname}) {
 8544: 	      return 'error: user id "'.$uid.'" does not match '.
 8545:                   'current user id "'.$uidhash{$uname}.'".';
 8546:           }
 8547:        } else {
 8548: 	  &idput($udom,($uname => $uid));
 8549:        }
 8550:     }
 8551: # -------------------------------------------------------------- Add names, etc
 8552:     my @tmp=&get('environment',
 8553: 		   ['firstname','middlename','lastname','generation','id',
 8554:                     'permanentemail','inststatus'],
 8555: 		   $udom,$uname);
 8556:     my (%names,%oldnames);
 8557:     if ($tmp[0] =~ m/^error:.*/) { 
 8558:         %names=(); 
 8559:     } else {
 8560:         %names = @tmp;
 8561:         %oldnames = %names;
 8562:     }
 8563: #
 8564: # If name, email and/or uid are blank (e.g., because an uploaded file
 8565: # of users did not contain them), do not overwrite existing values
 8566: # unless field is in $candelete array ref.  
 8567: #
 8568: 
 8569:     my @fields = ('firstname','middlename','lastname','generation',
 8570:                   'permanentemail','id');
 8571:     my %newvalues;
 8572:     if (ref($candelete) eq 'ARRAY') {
 8573:         foreach my $field (@fields) {
 8574:             if (grep(/^\Q$field\E$/,@{$candelete})) {
 8575:                 if ($field eq 'firstname') {
 8576:                     $names{$field} = $first;
 8577:                 } elsif ($field eq 'middlename') {
 8578:                     $names{$field} = $middle;
 8579:                 } elsif ($field eq 'lastname') {
 8580:                     $names{$field} = $last;
 8581:                 } elsif ($field eq 'generation') { 
 8582:                     $names{$field} = $gene;
 8583:                 } elsif ($field eq 'permanentemail') {
 8584:                     $names{$field} = $email;
 8585:                 } elsif ($field eq 'id') {
 8586:                     $names{$field}  = $uid;
 8587:                 }
 8588:             }
 8589:         }
 8590:     }
 8591:     if ($first)  { $names{'firstname'}  = $first; }
 8592:     if (defined($middle)) { $names{'middlename'} = $middle; }
 8593:     if ($last)   { $names{'lastname'}   = $last; }
 8594:     if (defined($gene))   { $names{'generation'} = $gene; }
 8595:     if ($email) {
 8596:        $email=~s/[^\w\@\.\-\,]//gs;
 8597:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 8598:     }
 8599:     if ($uid) { $names{'id'}  = $uid; }
 8600:     if (defined($inststatus)) {
 8601:         $names{'inststatus'} = '';
 8602:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
 8603:         if (ref($usertypes) eq 'HASH') {
 8604:             my @okstatuses; 
 8605:             foreach my $item (split(/:/,$inststatus)) {
 8606:                 if (defined($usertypes->{$item})) {
 8607:                     push(@okstatuses,$item);  
 8608:                 }
 8609:             }
 8610:             if (@okstatuses) {
 8611:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
 8612:             }
 8613:         }
 8614:     }
 8615:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
 8616:                  $umode.', '.$first.', '.$middle.', '.
 8617:                  $last.', '.$gene.', '.$email.', '.$inststatus;
 8618:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 8619:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 8620:     } else {
 8621:         $logmsg .= ' during self creation';
 8622:     }
 8623:     my $changed;
 8624:     if ($newuser) {
 8625:         $changed = 1;
 8626:     } else {
 8627:         foreach my $field (@fields) {
 8628:             if ($names{$field} ne $oldnames{$field}) {
 8629:                 $changed = 1;
 8630:                 last;
 8631:             }
 8632:         }
 8633:     }
 8634:     unless ($changed) {
 8635:         $logmsg = 'No changes in user information needed for: '.$logmsg;
 8636:         &logthis($logmsg);
 8637:         return 'ok';
 8638:     }
 8639:     my $reply = &put('environment', \%names, $udom,$uname);
 8640:     if ($reply ne 'ok') { 
 8641:         return 'error: '.$reply;
 8642:     }
 8643:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
 8644:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
 8645:     }
 8646:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 8647:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 8648:     $logmsg = 'Success modifying user '.$logmsg;
 8649:     &logthis($logmsg);
 8650:     return 'ok';
 8651: }
 8652: 
 8653: # -------------------------------------------------------------- Modify student
 8654: 
 8655: sub modifystudent {
 8656:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 8657:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 8658:         $selfenroll,$context,$inststatus,$credits)=@_;
 8659:     if (!$cid) {
 8660: 	unless ($cid=$env{'request.course.id'}) {
 8661: 	    return 'not_in_class';
 8662: 	}
 8663:     }
 8664: # --------------------------------------------------------------- Make the user
 8665:     my $reply=&modifyuser
 8666: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 8667:          $desiredhome,$email,$inststatus);
 8668:     unless ($reply eq 'ok') { return $reply; }
 8669:     # This will cause &modify_student_enrollment to get the uid from the
 8670:     # student's environment
 8671:     $uid = undef if (!$forceid);
 8672:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 8673: 					$gene,$usec,$end,$start,$type,$locktype,
 8674:                                         $cid,$selfenroll,$context,$credits);
 8675:     return $reply;
 8676: }
 8677: 
 8678: sub modify_student_enrollment {
 8679:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
 8680:         $locktype,$cid,$selfenroll,$context,$credits) = @_;
 8681:     my ($cdom,$cnum,$chome);
 8682:     if (!$cid) {
 8683: 	unless ($cid=$env{'request.course.id'}) {
 8684: 	    return 'not_in_class';
 8685: 	}
 8686: 	$cdom=$env{'course.'.$cid.'.domain'};
 8687: 	$cnum=$env{'course.'.$cid.'.num'};
 8688:     } else {
 8689: 	($cdom,$cnum)=split(/_/,$cid);
 8690:     }
 8691:     $chome=$env{'course.'.$cid.'.home'};
 8692:     if (!$chome) {
 8693: 	$chome=&homeserver($cnum,$cdom);
 8694:     }
 8695:     if (!$chome) { return 'unknown_course'; }
 8696:     # Make sure the user exists
 8697:     my $uhome=&homeserver($uname,$udom);
 8698:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 8699: 	return 'error: no such user';
 8700:     }
 8701:     # Get student data if we were not given enough information
 8702:     if (!defined($first)  || $first  eq '' || 
 8703:         !defined($last)   || $last   eq '' || 
 8704:         !defined($uid)    || $uid    eq '' || 
 8705:         !defined($middle) || $middle eq '' || 
 8706:         !defined($gene)   || $gene   eq '') {
 8707:         # They did not supply us with enough data to enroll the student, so
 8708:         # we need to pick up more information.
 8709:         my %tmp = &get('environment',
 8710:                        ['firstname','middlename','lastname', 'generation','id']
 8711:                        ,$udom,$uname);
 8712: 
 8713:         #foreach my $key (keys(%tmp)) {
 8714:         #    &logthis("key $key = ".$tmp{$key});
 8715:         #}
 8716:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 8717:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 8718:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 8719:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 8720:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 8721:     }
 8722:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 8723:     my $user = "$uname:$udom";
 8724:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
 8725:     my $reply=cput('classlist',
 8726: 		   {$user => 
 8727: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
 8728: 		   $cdom,$cnum);
 8729:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
 8730:         &devalidate_getsection_cache($udom,$uname,$cid);
 8731:     } else { 
 8732: 	return 'error: '.$reply;
 8733:     }
 8734:     # Add student role to user
 8735:     my $uurl='/'.$cid;
 8736:     $uurl=~s/\_/\//g;
 8737:     if ($usec) {
 8738: 	$uurl.='/'.$usec;
 8739:     }
 8740:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
 8741:                              $selfenroll,$context);
 8742:     if ($result ne 'ok') {
 8743:         if ($old_entry{$user} ne '') {
 8744:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
 8745:         } else {
 8746:             $reply = &del('classlist',[$user],$cdom,$cnum);
 8747:         }
 8748:     }
 8749:     return $result; 
 8750: }
 8751: 
 8752: sub format_name {
 8753:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 8754:     my $name;
 8755:     if ($first ne 'lastname') {
 8756: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 8757:     } else {
 8758: 	if ($lastname=~/\S/) {
 8759: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 8760: 	    $name=~s/\s+,/,/;
 8761: 	} else {
 8762: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 8763: 	}
 8764:     }
 8765:     $name=~s/^\s+//;
 8766:     $name=~s/\s+$//;
 8767:     $name=~s/\s+/ /g;
 8768:     return $name;
 8769: }
 8770: 
 8771: # ------------------------------------------------- Write to course preferences
 8772: 
 8773: sub writecoursepref {
 8774:     my ($courseid,%prefs)=@_;
 8775:     $courseid=~s/^\///;
 8776:     $courseid=~s/\_/\//g;
 8777:     my ($cdomain,$cnum)=split(/\//,$courseid);
 8778:     my $chome=homeserver($cnum,$cdomain);
 8779:     if (($chome eq '') || ($chome eq 'no_host')) { 
 8780: 	return 'error: no such course';
 8781:     }
 8782:     my $cstring='';
 8783:     foreach my $pref (keys(%prefs)) {
 8784: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 8785:     }
 8786:     $cstring=~s/\&$//;
 8787:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 8788: }
 8789: 
 8790: # ---------------------------------------------------------- Make/modify course
 8791: 
 8792: sub createcourse {
 8793:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 8794:         $course_owner,$crstype,$cnum,$context,$category)=@_;
 8795:     $url=&declutter($url);
 8796:     my $cid='';
 8797:     if ($context eq 'requestcourses') {
 8798:         my $can_create = 0;
 8799:         my ($ownername,$ownerdom) = split(':',$course_owner);
 8800:         if ($udom eq $ownerdom) {
 8801:             if (&usertools_access($ownername,$ownerdom,$category,undef,
 8802:                                   $context)) {
 8803:                 $can_create = 1;
 8804:             }
 8805:         } else {
 8806:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
 8807:                                            $category);
 8808:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
 8809:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
 8810:                 if (@curr > 0) {
 8811:                     my @options = qw(approval validate autolimit);
 8812:                     my $optregex = join('|',@options);
 8813:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
 8814:                         $can_create = 1;
 8815:                     }
 8816:                 }
 8817:             }
 8818:         }
 8819:         if ($can_create) {
 8820:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
 8821:                 unless (&allowed('ccc',$udom)) {
 8822:                     return 'refused'; 
 8823:                 }
 8824:             }
 8825:         } else {
 8826:             return 'refused';
 8827:         }
 8828:     } elsif (!&allowed('ccc',$udom)) {
 8829:         return 'refused';
 8830:     }
 8831: # --------------------------------------------------------------- Get Unique ID
 8832:     my $uname;
 8833:     if ($cnum =~ /^$match_courseid$/) {
 8834:         my $chome=&homeserver($cnum,$udom,'true');
 8835:         if (($chome eq '') || ($chome eq 'no_host')) {
 8836:             $uname = $cnum;
 8837:         } else {
 8838:             $uname = &generate_coursenum($udom,$crstype);
 8839:         }
 8840:     } else {
 8841:         $uname = &generate_coursenum($udom,$crstype);
 8842:     }
 8843:     return $uname if ($uname =~ /^error/);
 8844: # -------------------------------------------------- Check supplied server name
 8845:     if (!defined($course_server)) {
 8846:         if (defined(&domain($udom,'primary'))) {
 8847:             $course_server = &domain($udom,'primary');
 8848:         } else {
 8849:             $course_server = $env{'user.home'}; 
 8850:         }
 8851:     }
 8852:     my %host_servers =
 8853:         &Apache::lonnet::get_servers($udom,'library');
 8854:     unless ($host_servers{$course_server}) {
 8855:         return 'error: invalid home server for course: '.$course_server;
 8856:     }
 8857: # ------------------------------------------------------------- Make the course
 8858:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 8859:                       $course_server);
 8860:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 8861:     my $uhome=&homeserver($uname,$udom,'true');
 8862:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 8863: 	return 'error: no such course';
 8864:     }
 8865: # ----------------------------------------------------------------- Course made
 8866: # log existence
 8867:     my $now = time;
 8868:     my $newcourse = {
 8869:                     $udom.'_'.$uname => {
 8870:                                      description => $description,
 8871:                                      inst_code   => $inst_code,
 8872:                                      owner       => $course_owner,
 8873:                                      type        => $crstype,
 8874:                                      creator     => $env{'user.name'}.':'.
 8875:                                                     $env{'user.domain'},
 8876:                                      created     => $now,
 8877:                                      context     => $context,
 8878:                                                 },
 8879:                     };
 8880:     &courseidput($udom,$newcourse,$uhome,'notime');
 8881: # set toplevel url
 8882:     my $topurl=$url;
 8883:     unless ($nonstandard) {
 8884: # ------------------------------------------ For standard courses, make top url
 8885:         my $mapurl=&clutter($url);
 8886:         if ($mapurl eq '/res/') { $mapurl=''; }
 8887:         $env{'form.initmap'}=(<<ENDINITMAP);
 8888: <map>
 8889: <resource id="1" type="start"></resource>
 8890: <resource id="2" src="$mapurl"></resource>
 8891: <resource id="3" type="finish"></resource>
 8892: <link index="1" from="1" to="2"></link>
 8893: <link index="2" from="2" to="3"></link>
 8894: </map>
 8895: ENDINITMAP
 8896:         $topurl=&declutter(
 8897:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 8898:                           );
 8899:     }
 8900: # ----------------------------------------------------------- Write preferences
 8901:     &writecoursepref($udom.'_'.$uname,
 8902:                      ('description'              => $description,
 8903:                       'url'                      => $topurl,
 8904:                       'internal.creator'         => $env{'user.name'}.':'.
 8905:                                                     $env{'user.domain'},
 8906:                       'internal.created'         => $now,
 8907:                       'internal.creationcontext' => $context)
 8908:                     );
 8909:     return '/'.$udom.'/'.$uname;
 8910: }
 8911: 
 8912: # ------------------------------------------------------------------- Create ID
 8913: sub generate_coursenum {
 8914:     my ($udom,$crstype) = @_;
 8915:     my $domdesc = &domain($udom);
 8916:     return 'error: invalid domain' if ($domdesc eq '');
 8917:     my $first;
 8918:     if ($crstype eq 'Community') {
 8919:         $first = '0';
 8920:     } else {
 8921:         $first = int(1+rand(9)); 
 8922:     } 
 8923:     my $uname=$first.
 8924:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 8925:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
 8926:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 8927: # ----------------------------------------------- Make sure that does not exist
 8928:     my $uhome=&homeserver($uname,$udom,'true');
 8929:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
 8930:         if ($crstype eq 'Community') {
 8931:             $first = '0';
 8932:         } else {
 8933:             $first = int(1+rand(9));
 8934:         }
 8935:         $uname=$first.
 8936:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 8937:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
 8938:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 8939:         $uhome=&homeserver($uname,$udom,'true');
 8940:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
 8941:             return 'error: unable to generate unique course-ID';
 8942:         }
 8943:     }
 8944:     return $uname;
 8945: }
 8946: 
 8947: sub is_course {
 8948:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
 8949:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
 8950: 
 8951:     return unless $cdom and $cnum;
 8952: 
 8953:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
 8954:         '.');
 8955: 
 8956:     return unless(exists($courses{$cdom.'_'.$cnum}));
 8957:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
 8958: }
 8959: 
 8960: sub store_userdata {
 8961:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
 8962:     my $result;
 8963:     if ($datakey ne '') {
 8964:         if (ref($storehash) eq 'HASH') {
 8965:             if ($udom eq '' || $uname eq '') {
 8966:                 $udom = $env{'user.domain'};
 8967:                 $uname = $env{'user.name'};
 8968:             }
 8969:             my $uhome=&homeserver($uname,$udom);
 8970:             if (($uhome eq '') || ($uhome eq 'no_host')) {
 8971:                 $result = 'error: no_host';
 8972:             } else {
 8973:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
 8974:                 $storehash->{'host'} = $perlvar{'lonHostID'};
 8975: 
 8976:                 my $namevalue='';
 8977:                 foreach my $key (keys(%{$storehash})) {
 8978:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 8979:                 }
 8980:                 $namevalue=~s/\&$//;
 8981:                 unless ($namespace eq 'courserequests') {
 8982:                     $datakey = &escape($datakey);
 8983:                 }
 8984:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
 8985:                                   $namevalue,$uhome);
 8986:             }
 8987:         } else {
 8988:             $result = 'error: data to store was not a hash reference'; 
 8989:         }
 8990:     } else {
 8991:         $result= 'error: invalid requestkey'; 
 8992:     }
 8993:     return $result;
 8994: }
 8995: 
 8996: # ---------------------------------------------------------- Assign Custom Role
 8997: 
 8998: sub assigncustomrole {
 8999:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
 9000:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 9001:                        $end,$start,$deleteflag,$selfenroll,$context);
 9002: }
 9003: 
 9004: # ----------------------------------------------------------------- Revoke Role
 9005: 
 9006: sub revokerole {
 9007:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
 9008:     my $now=time;
 9009:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
 9010: }
 9011: 
 9012: # ---------------------------------------------------------- Revoke Custom Role
 9013: 
 9014: sub revokecustomrole {
 9015:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
 9016:     my $now=time;
 9017:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 9018:            $deleteflag,$selfenroll,$context);
 9019: }
 9020: 
 9021: # ------------------------------------------------------------ Disk usage
 9022: sub diskusage {
 9023:     my ($udom,$uname,$directorypath,$getpropath)=@_;
 9024:     $directorypath =~ s/\/$//;
 9025:     my $listing=&reply('du2:'.&escape($directorypath).':'
 9026:                        .&escape($getpropath).':'.&escape($uname).':'
 9027:                        .&escape($udom),homeserver($uname,$udom));
 9028:     if ($listing eq 'unknown_cmd') {
 9029:         if ($getpropath) {
 9030:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
 9031:         }
 9032:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
 9033:     }
 9034:     return $listing;
 9035: }
 9036: 
 9037: sub is_locked {
 9038:     my ($file_name, $domain, $user, $which) = @_;
 9039:     my @check;
 9040:     my $is_locked;
 9041:     push (@check,$file_name);
 9042:     my %locked = &get('file_permissions',\@check,
 9043: 		      $env{'user.domain'},$env{'user.name'});
 9044:     my ($tmp)=keys(%locked);
 9045:     if ($tmp=~/^error:/) { undef(%locked); }
 9046:     
 9047:     if (ref($locked{$file_name}) eq 'ARRAY') {
 9048:         $is_locked = 'false';
 9049:         foreach my $entry (@{$locked{$file_name}}) {
 9050:            if (ref($entry) eq 'ARRAY') {
 9051:                $is_locked = 'true';
 9052:                if (ref($which) eq 'ARRAY') {
 9053:                    push(@{$which},$entry);
 9054:                } else {
 9055:                    last;
 9056:                }
 9057:            }
 9058:        }
 9059:     } else {
 9060:         $is_locked = 'false';
 9061:     }
 9062:     return $is_locked;
 9063: }
 9064: 
 9065: sub declutter_portfile {
 9066:     my ($file) = @_;
 9067:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 9068:     return $file;
 9069: }
 9070: 
 9071: # ------------------------------------------------------------- Mark as Read Only
 9072: 
 9073: sub mark_as_readonly {
 9074:     my ($domain,$user,$files,$what) = @_;
 9075:     my %current_permissions = &dump('file_permissions',$domain,$user);
 9076:     my ($tmp)=keys(%current_permissions);
 9077:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 9078:     foreach my $file (@{$files}) {
 9079: 	$file = &declutter_portfile($file);
 9080:         push(@{$current_permissions{$file}},$what);
 9081:     }
 9082:     &put('file_permissions',\%current_permissions,$domain,$user);
 9083:     return;
 9084: }
 9085: 
 9086: # ------------------------------------------------------------Save Selected Files
 9087: 
 9088: sub save_selected_files {
 9089:     my ($user, $path, @files) = @_;
 9090:     my $filename = $user."savedfiles";
 9091:     my @other_files = &files_not_in_path($user, $path);
 9092:     open (OUT, '>'.$tmpdir.$filename);
 9093:     foreach my $file (@files) {
 9094:         print (OUT $env{'form.currentpath'}.$file."\n");
 9095:     }
 9096:     foreach my $file (@other_files) {
 9097:         print (OUT $file."\n");
 9098:     }
 9099:     close (OUT);
 9100:     return 'ok';
 9101: }
 9102: 
 9103: sub clear_selected_files {
 9104:     my ($user) = @_;
 9105:     my $filename = $user."savedfiles";
 9106:     open (OUT, '>'.LONCAPA::tempdir().$filename);
 9107:     print (OUT undef);
 9108:     close (OUT);
 9109:     return ("ok");    
 9110: }
 9111: 
 9112: sub files_in_path {
 9113:     my ($user, $path) = @_;
 9114:     my $filename = $user."savedfiles";
 9115:     my %return_files;
 9116:     open (IN, '<'.LONCAPA::tempdir().$filename);
 9117:     while (my $line_in = <IN>) {
 9118:         chomp ($line_in);
 9119:         my @paths_and_file = split (m!/!, $line_in);
 9120:         my $file_part = pop (@paths_and_file);
 9121:         my $path_part = join ('/', @paths_and_file);
 9122:         $path_part.='/';
 9123:         my $path_and_file = $path_part.$file_part;
 9124:         if ($path_part eq $path) {
 9125:             $return_files{$file_part}= 'selected';
 9126:         }
 9127:     }
 9128:     close (IN);
 9129:     return (\%return_files);
 9130: }
 9131: 
 9132: # called in portfolio select mode, to show files selected NOT in current directory
 9133: sub files_not_in_path {
 9134:     my ($user, $path) = @_;
 9135:     my $filename = $user."savedfiles";
 9136:     my @return_files;
 9137:     my $path_part;
 9138:     open(IN, '<'.LONCAPA::.$filename);
 9139:     while (my $line = <IN>) {
 9140:         #ok, I know it's clunky, but I want it to work
 9141:         my @paths_and_file = split(m|/|, $line);
 9142:         my $file_part = pop(@paths_and_file);
 9143:         chomp($file_part);
 9144:         my $path_part = join('/', @paths_and_file);
 9145:         $path_part .= '/';
 9146:         my $path_and_file = $path_part.$file_part;
 9147:         if ($path_part ne $path) {
 9148:             push(@return_files, ($path_and_file));
 9149:         }
 9150:     }
 9151:     close(OUT);
 9152:     return (@return_files);
 9153: }
 9154: 
 9155: #----------------------------------------------Get portfolio file permissions
 9156: 
 9157: sub get_portfile_permissions {
 9158:     my ($domain,$user) = @_;
 9159:     my %current_permissions = &dump('file_permissions',$domain,$user);
 9160:     my ($tmp)=keys(%current_permissions);
 9161:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 9162:     return \%current_permissions;
 9163: }
 9164: 
 9165: #---------------------------------------------Get portfolio file access controls
 9166: 
 9167: sub get_access_controls {
 9168:     my ($current_permissions,$group,$file) = @_;
 9169:     my %access;
 9170:     my $real_file = $file;
 9171:     $file =~ s/\.meta$//;
 9172:     if (defined($file)) {
 9173:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 9174:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 9175:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 9176:             }
 9177:         }
 9178:     } else {
 9179:         foreach my $key (keys(%{$current_permissions})) {
 9180:             if ($key =~ /\0accesscontrol$/) {
 9181:                 if (defined($group)) {
 9182:                     if ($key !~ m-^\Q$group\E/-) {
 9183:                         next;
 9184:                     }
 9185:                 }
 9186:                 my ($fullpath) = split(/\0/,$key);
 9187:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 9188:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 9189:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 9190:                     }
 9191:                 }
 9192:             }
 9193:         }
 9194:     }
 9195:     return %access;
 9196: }
 9197: 
 9198: sub modify_access_controls {
 9199:     my ($file_name,$changes,$domain,$user)=@_;
 9200:     my ($outcome,$deloutcome);
 9201:     my %store_permissions;
 9202:     my %new_values;
 9203:     my %new_control;
 9204:     my %translation;
 9205:     my @deletions = ();
 9206:     my $now = time;
 9207:     if (exists($$changes{'activate'})) {
 9208:         if (ref($$changes{'activate'}) eq 'HASH') {
 9209:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 9210:             my $numnew = scalar(@newitems);
 9211:             for (my $i=0; $i<$numnew; $i++) {
 9212:                 my $newkey = $newitems[$i];
 9213:                 my $newid = &Apache::loncommon::get_cgi_id();
 9214:                 if ($newkey =~ /^\d+:/) { 
 9215:                     $newkey =~ s/^(\d+)/$newid/;
 9216:                     $translation{$1} = $newid;
 9217:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 9218:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 9219:                     $translation{$1} = $newid;
 9220:                 }
 9221:                 $new_values{$file_name."\0".$newkey} = 
 9222:                                           $$changes{'activate'}{$newitems[$i]};
 9223:                 $new_control{$newkey} = $now;
 9224:             }
 9225:         }
 9226:     }
 9227:     my %todelete;
 9228:     my %changed_items;
 9229:     foreach my $action ('delete','update') {
 9230:         if (exists($$changes{$action})) {
 9231:             if (ref($$changes{$action}) eq 'HASH') {
 9232:                 foreach my $key (keys(%{$$changes{$action}})) {
 9233:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 9234:                     if ($action eq 'delete') { 
 9235:                         $todelete{$itemnum} = 1;
 9236:                     } else {
 9237:                         $changed_items{$itemnum} = $key;
 9238:                     }
 9239:                 }
 9240:             }
 9241:         }
 9242:     }
 9243:     # get lock on access controls for file.
 9244:     my $lockhash = {
 9245:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 9246:                                                        ':'.$env{'user.domain'},
 9247:                    }; 
 9248:     my $tries = 0;
 9249:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 9250:    
 9251:     while (($gotlock ne 'ok') && $tries <3) {
 9252:         $tries ++;
 9253:         sleep 1;
 9254:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 9255:     }
 9256:     if ($gotlock eq 'ok') {
 9257:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 9258:         my ($tmp)=keys(%curr_permissions);
 9259:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 9260:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 9261:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 9262:             if (ref($curr_controls) eq 'HASH') {
 9263:                 foreach my $control_item (keys(%{$curr_controls})) {
 9264:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 9265:                     if (defined($todelete{$itemnum})) {
 9266:                         push(@deletions,$file_name."\0".$control_item);
 9267:                     } else {
 9268:                         if (defined($changed_items{$itemnum})) {
 9269:                             $new_control{$changed_items{$itemnum}} = $now;
 9270:                             push(@deletions,$file_name."\0".$control_item);
 9271:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 9272:                         } else {
 9273:                             $new_control{$control_item} = $$curr_controls{$control_item};
 9274:                         }
 9275:                     }
 9276:                 }
 9277:             }
 9278:         }
 9279:         my ($group);
 9280:         if (&is_course($domain,$user)) {
 9281:             ($group,my $file) = split(/\//,$file_name,2);
 9282:         }
 9283:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 9284:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 9285:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 9286:         #  remove lock
 9287:         my @del_lock = ($file_name."\0".'locked_access_records');
 9288:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 9289:         my $sqlresult =
 9290:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
 9291:                                     $group);
 9292:     } else {
 9293:         $outcome = "error: could not obtain lockfile\n";  
 9294:     }
 9295:     return ($outcome,$deloutcome,\%new_values,\%translation);
 9296: }
 9297: 
 9298: sub make_public_indefinitely {
 9299:     my ($requrl) = @_;
 9300:     my $now = time;
 9301:     my $action = 'activate';
 9302:     my $aclnum = 0;
 9303:     if (&is_portfolio_url($requrl)) {
 9304:         my (undef,$udom,$unum,$file_name,$group) =
 9305:             &parse_portfolio_url($requrl);
 9306:         my $current_perms = &get_portfile_permissions($udom,$unum);
 9307:         my %access_controls = &get_access_controls($current_perms,
 9308:                                                    $group,$file_name);
 9309:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 9310:             my ($num,$scope,$end,$start) = 
 9311:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 9312:             if ($scope eq 'public') {
 9313:                 if ($start <= $now && $end == 0) {
 9314:                     $action = 'none';
 9315:                 } else {
 9316:                     $action = 'update';
 9317:                     $aclnum = $num;
 9318:                 }
 9319:                 last;
 9320:             }
 9321:         }
 9322:         if ($action eq 'none') {
 9323:              return 'ok';
 9324:         } else {
 9325:             my %changes;
 9326:             my $newend = 0;
 9327:             my $newstart = $now;
 9328:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 9329:             $changes{$action}{$newkey} = {
 9330:                 type => 'public',
 9331:                 time => {
 9332:                     start => $newstart,
 9333:                     end   => $newend,
 9334:                 },
 9335:             };
 9336:             my ($outcome,$deloutcome,$new_values,$translation) =
 9337:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 9338:             return $outcome;
 9339:         }
 9340:     } else {
 9341:         return 'invalid';
 9342:     }
 9343: }
 9344: 
 9345: #------------------------------------------------------Get Marked as Read Only
 9346: 
 9347: sub get_marked_as_readonly {
 9348:     my ($domain,$user,$what,$group) = @_;
 9349:     my $current_permissions = &get_portfile_permissions($domain,$user);
 9350:     my @readonly_files;
 9351:     my $cmp1=$what;
 9352:     if (ref($what)) { $cmp1=join('',@{$what}) };
 9353:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 9354:         if (defined($group)) {
 9355:             if ($file_name !~ m-^\Q$group\E/-) {
 9356:                 next;
 9357:             }
 9358:         }
 9359:         if (ref($value) eq "ARRAY"){
 9360:             foreach my $stored_what (@{$value}) {
 9361:                 my $cmp2=$stored_what;
 9362:                 if (ref($stored_what) eq 'ARRAY') {
 9363:                     $cmp2=join('',@{$stored_what});
 9364:                 }
 9365:                 if ($cmp1 eq $cmp2) {
 9366:                     push(@readonly_files, $file_name);
 9367:                     last;
 9368:                 } elsif (!defined($what)) {
 9369:                     push(@readonly_files, $file_name);
 9370:                     last;
 9371:                 }
 9372:             }
 9373:         }
 9374:     }
 9375:     return @readonly_files;
 9376: }
 9377: #-----------------------------------------------------------Get Marked as Read Only Hash
 9378: 
 9379: sub get_marked_as_readonly_hash {
 9380:     my ($current_permissions,$group,$what) = @_;
 9381:     my %readonly_files;
 9382:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 9383:         if (defined($group)) {
 9384:             if ($file_name !~ m-^\Q$group\E/-) {
 9385:                 next;
 9386:             }
 9387:         }
 9388:         if (ref($value) eq "ARRAY"){
 9389:             foreach my $stored_what (@{$value}) {
 9390:                 if (ref($stored_what) eq 'ARRAY') {
 9391:                     foreach my $lock_descriptor(@{$stored_what}) {
 9392:                         if ($lock_descriptor eq 'graded') {
 9393:                             $readonly_files{$file_name} = 'graded';
 9394:                         } elsif ($lock_descriptor eq 'handback') {
 9395:                             $readonly_files{$file_name} = 'handback';
 9396:                         } else {
 9397:                             if (!exists($readonly_files{$file_name})) {
 9398:                                 $readonly_files{$file_name} = 'locked';
 9399:                             }
 9400:                         }
 9401:                     }
 9402:                 } 
 9403:             }
 9404:         } 
 9405:     }
 9406:     return %readonly_files;
 9407: }
 9408: # ------------------------------------------------------------ Unmark as Read Only
 9409: 
 9410: sub unmark_as_readonly {
 9411:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 9412:     # for portfolio submissions, $what contains [$symb,$crsid] 
 9413:     my ($domain,$user,$what,$file_name,$group) = @_;
 9414:     $file_name = &declutter_portfile($file_name);
 9415:     my $symb_crs = $what;
 9416:     if (ref($what)) { $symb_crs=join('',@$what); }
 9417:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 9418:     my ($tmp)=keys(%current_permissions);
 9419:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 9420:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 9421:     foreach my $file (@readonly_files) {
 9422: 	my $clean_file = &declutter_portfile($file);
 9423: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 9424: 	my $current_locks = $current_permissions{$file};
 9425:         my @new_locks;
 9426:         my @del_keys;
 9427:         if (ref($current_locks) eq "ARRAY"){
 9428:             foreach my $locker (@{$current_locks}) {
 9429:                 my $compare=$locker;
 9430:                 if (ref($locker) eq 'ARRAY') {
 9431:                     $compare=join('',@{$locker});
 9432:                     if ($compare ne $symb_crs) {
 9433:                         push(@new_locks, $locker);
 9434:                     }
 9435:                 }
 9436:             }
 9437:             if (scalar(@new_locks) > 0) {
 9438:                 $current_permissions{$file} = \@new_locks;
 9439:             } else {
 9440:                 push(@del_keys, $file);
 9441:                 &del('file_permissions',\@del_keys, $domain, $user);
 9442:                 delete($current_permissions{$file});
 9443:             }
 9444:         }
 9445:     }
 9446:     &put('file_permissions',\%current_permissions,$domain,$user);
 9447:     return;
 9448: }
 9449: 
 9450: # ------------------------------------------------------------ Directory lister
 9451: 
 9452: sub dirlist {
 9453:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
 9454:     $uri=~s/^\///;
 9455:     $uri=~s/\/$//;
 9456:     my ($udom, $uname);
 9457:     if ($getuserdir) {
 9458:         $udom = $userdomain;
 9459:         $uname = $username;
 9460:     } else {
 9461:         (undef,$udom,$uname)=split(/\//,$uri);
 9462:         if(defined($userdomain)) {
 9463:             $udom = $userdomain;
 9464:         }
 9465:         if(defined($username)) {
 9466:             $uname = $username;
 9467:         }
 9468:     }
 9469:     my ($dirRoot,$listing,@listing_results);
 9470: 
 9471:     $dirRoot = $perlvar{'lonDocRoot'};
 9472:     if (defined($getpropath)) {
 9473:         $dirRoot = &propath($udom,$uname);
 9474:         $dirRoot =~ s/\/$//;
 9475:     } elsif (defined($getuserdir)) {
 9476:         my $subdir=$uname.'__';
 9477:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 9478:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
 9479:                    ."/$udom/$subdir/$uname";
 9480:     } elsif (defined($alternateRoot)) {
 9481:         $dirRoot = $alternateRoot;
 9482:     }
 9483: 
 9484:     if($udom) {
 9485:         if($uname) {
 9486:             my $uhome = &homeserver($uname,$udom);
 9487:             if ($uhome eq 'no_host') {
 9488:                 return ([],'no_host');
 9489:             }
 9490:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
 9491:                               .$getuserdir.':'.&escape($dirRoot)
 9492:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
 9493:             if ($listing eq 'unknown_cmd') {
 9494:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
 9495:             } else {
 9496:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 9497:             }
 9498:             if ($listing eq 'unknown_cmd') {
 9499:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
 9500:                 @listing_results = split(/:/,$listing);
 9501:             } else {
 9502:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 9503:             }
 9504:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
 9505:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
 9506:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 9507:                 return ([],$listing);
 9508:             } else {
 9509:                 return (\@listing_results);
 9510:             }
 9511:         } elsif(!$alternateRoot) {
 9512:             my (%allusers,%listerror);
 9513: 	    my %servers = &get_servers($udom,'library');
 9514:  	    foreach my $tryserver (keys(%servers)) {
 9515:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
 9516:                                   &escape($udom),$tryserver);
 9517:                 if ($listing eq 'unknown_cmd') {
 9518: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 9519: 				      $udom, $tryserver);
 9520:                 } else {
 9521:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
 9522:                 }
 9523: 		if ($listing eq 'unknown_cmd') {
 9524: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 9525: 				      $udom, $tryserver);
 9526: 		    @listing_results = split(/:/,$listing);
 9527: 		} else {
 9528: 		    @listing_results =
 9529: 			map { &unescape($_); } split(/:/,$listing);
 9530: 		}
 9531:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
 9532:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
 9533:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 9534:                     $listerror{$tryserver} = $listing;
 9535:                 } else {
 9536: 		    foreach my $line (@listing_results) {
 9537: 			my ($entry) = split(/&/,$line,2);
 9538: 			$allusers{$entry} = 1;
 9539: 		    }
 9540: 		}
 9541:             }
 9542:             my @alluserslist=();
 9543:             foreach my $user (sort(keys(%allusers))) {
 9544:                 push(@alluserslist,$user.'&user');
 9545:             }
 9546:             return (\@alluserslist);
 9547:         } else {
 9548:             return ([],'missing username');
 9549:         }
 9550:     } elsif(!defined($getpropath)) {
 9551:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
 9552:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
 9553:         return (\@all_domains);
 9554:     } else {
 9555:         return ([],'missing domain');
 9556:     }
 9557: }
 9558: 
 9559: # --------------------------------------------- GetFileTimestamp
 9560: # This function utilizes dirlist and returns the date stamp for
 9561: # when it was last modified.  It will also return an error of -1
 9562: # if an error occurs
 9563: 
 9564: sub GetFileTimestamp {
 9565:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
 9566:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 9567:     $studentName   = &LONCAPA::clean_username($studentName);
 9568:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
 9569:                                     undef,$getuserdir);
 9570:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 9571:         return -1;
 9572:     }
 9573:     if (ref($fileref) eq 'ARRAY') {
 9574:         my @stats = split('&',$fileref->[0]);
 9575:         # @stats contains first the filename, then the stat output
 9576:         return $stats[10]; # so this is 10 instead of 9.
 9577:     } else {
 9578:         return -1;
 9579:     }
 9580: }
 9581: 
 9582: sub stat_file {
 9583:     my ($uri) = @_;
 9584:     $uri = &clutter_with_no_wrapper($uri);
 9585: 
 9586:     my ($udom,$uname,$file);
 9587:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 9588: 	($udom,$uname,$file) =
 9589: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 9590: 	$file = 'userfiles/'.$file;
 9591:     }
 9592:     if ($uri =~ m-^/res/-) {
 9593: 	($udom,$uname) = 
 9594: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 9595: 	$file = $uri;
 9596:     }
 9597: 
 9598:     if (!$udom || !$uname || !$file) {
 9599: 	# unable to handle the uri
 9600: 	return ();
 9601:     }
 9602:     my $getpropath;
 9603:     if ($file =~ /^userfiles\//) {
 9604:         $getpropath = 1;
 9605:     }
 9606:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
 9607:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 9608:         return ();
 9609:     } else {
 9610:         if (ref($listref) eq 'ARRAY') {
 9611:             my @stats = split('&',$listref->[0]);
 9612: 	    shift(@stats); #filename is first
 9613: 	    return @stats;
 9614:         }
 9615:     }
 9616:     return ();
 9617: }
 9618: 
 9619: # -------------------------------------------------------- Value of a Condition
 9620: 
 9621: # gets the value of a specific preevaluated condition
 9622: #    stored in the string  $env{user.state.<cid>}
 9623: # or looks up a condition reference in the bighash and if if hasn't
 9624: # already been evaluated recurses into docondval to get the value of
 9625: # the condition, then memoizing it to 
 9626: #   $env{user.state.<cid>.<condition>}
 9627: sub directcondval {
 9628:     my $number=shift;
 9629:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 9630: 	&Apache::lonuserstate::evalstate();
 9631:     }
 9632:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 9633: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 9634:     } elsif ($number =~ /^_/) {
 9635: 	my $sub_condition;
 9636: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9637: 		&GDBM_READER(),0640)) {
 9638: 	    $sub_condition=$bighash{'conditions'.$number};
 9639: 	    untie(%bighash);
 9640: 	}
 9641: 	my $value = &docondval($sub_condition);
 9642: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
 9643: 	return $value;
 9644:     }
 9645:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 9646:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 9647:     } else {
 9648:        return 2;
 9649:     }
 9650: }
 9651: 
 9652: # get the collection of conditions for this resource
 9653: sub condval {
 9654:     my $condidx=shift;
 9655:     my $allpathcond='';
 9656:     foreach my $cond (split(/\|/,$condidx)) {
 9657: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 9658: 	    $allpathcond.=
 9659: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 9660: 	}
 9661:     }
 9662:     $allpathcond=~s/\|$//;
 9663:     return &docondval($allpathcond);
 9664: }
 9665: 
 9666: #evaluates an expression of conditions
 9667: sub docondval {
 9668:     my ($allpathcond) = @_;
 9669:     my $result=0;
 9670:     if ($env{'request.course.id'}
 9671: 	&& defined($allpathcond)) {
 9672: 	my $operand='|';
 9673: 	my @stack;
 9674: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 9675: 	    if ($chunk eq '(') {
 9676: 		push @stack,($operand,$result);
 9677: 	    } elsif ($chunk eq ')') {
 9678: 		my $before=pop @stack;
 9679: 		if (pop @stack eq '&') {
 9680: 		    $result=$result>$before?$before:$result;
 9681: 		} else {
 9682: 		    $result=$result>$before?$result:$before;
 9683: 		}
 9684: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 9685: 		$operand=$chunk;
 9686: 	    } else {
 9687: 		my $new=directcondval($chunk);
 9688: 		if ($operand eq '&') {
 9689: 		    $result=$result>$new?$new:$result;
 9690: 		} else {
 9691: 		    $result=$result>$new?$result:$new;
 9692: 		}
 9693: 	    }
 9694: 	}
 9695:     }
 9696:     return $result;
 9697: }
 9698: 
 9699: # ---------------------------------------------------- Devalidate courseresdata
 9700: 
 9701: sub devalidatecourseresdata {
 9702:     my ($coursenum,$coursedomain)=@_;
 9703:     my $hashid=$coursenum.':'.$coursedomain;
 9704:     &devalidate_cache_new('courseres',$hashid);
 9705: }
 9706: 
 9707: 
 9708: # --------------------------------------------------- Course Resourcedata Query
 9709: #
 9710: #  Parameters:
 9711: #      $coursenum    - Number of the course.
 9712: #      $coursedomain - Domain at which the course was created.
 9713: #  Returns:
 9714: #     A hash of the course parameters along (I think) with timestamps
 9715: #     and version info.
 9716: 
 9717: sub get_courseresdata {
 9718:     my ($coursenum,$coursedomain)=@_;
 9719:     my $coursehom=&homeserver($coursenum,$coursedomain);
 9720:     my $hashid=$coursenum.':'.$coursedomain;
 9721:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 9722:     my %dumpreply;
 9723:     unless (defined($cached)) {
 9724: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 9725: 	$result=\%dumpreply;
 9726: 	my ($tmp) = keys(%dumpreply);
 9727: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 9728: 	    &do_cache_new('courseres',$hashid,$result,600);
 9729: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 9730: 	    return $tmp;
 9731: 	} elsif ($tmp =~ /^(error)/) {
 9732: 	    $result=undef;
 9733: 	    &do_cache_new('courseres',$hashid,$result,600);
 9734: 	}
 9735:     }
 9736:     return $result;
 9737: }
 9738: 
 9739: sub devalidateuserresdata {
 9740:     my ($uname,$udom)=@_;
 9741:     my $hashid="$udom:$uname";
 9742:     &devalidate_cache_new('userres',$hashid);
 9743: }
 9744: 
 9745: sub get_userresdata {
 9746:     my ($uname,$udom)=@_;
 9747:     #most student don\'t have any data set, check if there is some data
 9748:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 9749: 
 9750:     my $hashid="$udom:$uname";
 9751:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 9752:     if (!defined($cached)) {
 9753: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 9754: 	$result=\%resourcedata;
 9755: 	&do_cache_new('userres',$hashid,$result,600);
 9756:     }
 9757:     my ($tmp)=keys(%$result);
 9758:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 9759: 	return $result;
 9760:     }
 9761:     #error 2 occurs when the .db doesn't exist
 9762:     if ($tmp!~/error: 2 /) {
 9763: 	&logthis("<font color=\"blue\">WARNING:".
 9764: 		 " Trying to get resource data for ".
 9765: 		 $uname." at ".$udom.": ".
 9766: 		 $tmp."</font>");
 9767:     } elsif ($tmp=~/error: 2 /) {
 9768: 	#&EXT_cache_set($udom,$uname);
 9769: 	&do_cache_new('userres',$hashid,undef,600);
 9770: 	undef($tmp); # not really an error so don't send it back
 9771:     }
 9772:     return $tmp;
 9773: }
 9774: #----------------------------------------------- resdata - return resource data
 9775: #  Purpose:
 9776: #    Return resource data for either users or for a course.
 9777: #  Parameters:
 9778: #     $name      - Course/user name.
 9779: #     $domain    - Name of the domain the user/course is registered on.
 9780: #     $type      - Type of thing $name is (must be 'course' or 'user'
 9781: #     @which     - Array of names of resources desired.
 9782: #  Returns:
 9783: #     The value of the first reasource in @which that is found in the
 9784: #     resource hash.
 9785: #  Exceptional Conditions:
 9786: #     If the $type passed in is not valid (not the string 'course' or 
 9787: #     'user', an undefined  reference is returned.
 9788: #     If none of the resources are found, an undef is returned
 9789: sub resdata {
 9790:     my ($name,$domain,$type,@which)=@_;
 9791:     my $result;
 9792:     if ($type eq 'course') {
 9793: 	$result=&get_courseresdata($name,$domain);
 9794:     } elsif ($type eq 'user') {
 9795: 	$result=&get_userresdata($name,$domain);
 9796:     }
 9797:     if (!ref($result)) { return $result; }    
 9798:     foreach my $item (@which) {
 9799: 	if (defined($result->{$item->[0]})) {
 9800: 	    return [$result->{$item->[0]},$item->[1]];
 9801: 	}
 9802:     }
 9803:     return undef;
 9804: }
 9805: 
 9806: sub get_numsuppfiles {
 9807:     my ($cnum,$cdom,$ignorecache)=@_;
 9808:     my $hashid=$cnum.':'.$cdom;
 9809:     my ($suppcount,$cached);
 9810:     unless ($ignorecache) {
 9811:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
 9812:     }
 9813:     unless (defined($cached)) {
 9814:         my $chome=&homeserver($cnum,$cdom);
 9815:         unless ($chome eq 'no_host') {
 9816:             ($suppcount,my $errors) = (0,0);
 9817:             my $suppmap = 'supplemental.sequence';
 9818:             ($suppcount,$errors) =
 9819:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
 9820:         }
 9821:         &do_cache_new('suppcount',$hashid,$suppcount,600);
 9822:     }
 9823:     return $suppcount;
 9824: }
 9825: 
 9826: #
 9827: # EXT resource caching routines
 9828: #
 9829: 
 9830: sub clear_EXT_cache_status {
 9831:     &delenv('cache.EXT.');
 9832: }
 9833: 
 9834: sub EXT_cache_status {
 9835:     my ($target_domain,$target_user) = @_;
 9836:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 9837:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 9838:         # We know already the user has no data
 9839:         return 1;
 9840:     } else {
 9841:         return 0;
 9842:     }
 9843: }
 9844: 
 9845: sub EXT_cache_set {
 9846:     my ($target_domain,$target_user) = @_;
 9847:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 9848:     #&appenv({$cachename => time});
 9849: }
 9850: 
 9851: # --------------------------------------------------------- Value of a Variable
 9852: sub EXT {
 9853: 
 9854:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
 9855:     unless ($varname) { return ''; }
 9856:     #get real user name/domain, courseid and symb
 9857:     my $courseid;
 9858:     my $publicuser;
 9859:     if ($symbparm) {
 9860: 	$symbparm=&get_symb_from_alias($symbparm);
 9861:     }
 9862:     if (!($uname && $udom)) {
 9863:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 9864:       if (!$symbparm) {	$symbparm=$cursymb; }
 9865:     } else {
 9866: 	$courseid=$env{'request.course.id'};
 9867:     }
 9868:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 9869:     my $rest;
 9870:     if (defined($therest[0])) {
 9871:        $rest=join('.',@therest);
 9872:     } else {
 9873:        $rest='';
 9874:     }
 9875: 
 9876:     my $qualifierrest=$qualifier;
 9877:     if ($rest) { $qualifierrest.='.'.$rest; }
 9878:     my $spacequalifierrest=$space;
 9879:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 9880:     if ($realm eq 'user') {
 9881: # --------------------------------------------------------------- user.resource
 9882: 	if ($space eq 'resource') {
 9883: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 9884: 		  || defined($Apache::lonhomework::parsing_a_task))
 9885: 		 &&
 9886: 		 ($symbparm eq &symbread()) ) {	
 9887: 		# if we are in the middle of processing the resource the
 9888: 		# get the value we are planning on committing
 9889:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 9890:                     return $Apache::lonhomework::results{$qualifierrest};
 9891:                 } else {
 9892:                     return $Apache::lonhomework::history{$qualifierrest};
 9893:                 }
 9894: 	    } else {
 9895: 		my %restored;
 9896: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 9897: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 9898: 		} else {
 9899: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 9900: 		}
 9901: 		return $restored{$qualifierrest};
 9902: 	    }
 9903: # ----------------------------------------------------------------- user.access
 9904:         } elsif ($space eq 'access') {
 9905: 	    # FIXME - not supporting calls for a specific user
 9906:             return &allowed($qualifier,$rest);
 9907: # ------------------------------------------ user.preferences, user.environment
 9908:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 9909: 	    if (($uname eq $env{'user.name'}) &&
 9910: 		($udom eq $env{'user.domain'})) {
 9911: 		return $env{join('.',('environment',$qualifierrest))};
 9912: 	    } else {
 9913: 		my %returnhash;
 9914: 		if (!$publicuser) {
 9915: 		    %returnhash=&userenvironment($udom,$uname,
 9916: 						 $qualifierrest);
 9917: 		}
 9918: 		return $returnhash{$qualifierrest};
 9919: 	    }
 9920: # ----------------------------------------------------------------- user.course
 9921:         } elsif ($space eq 'course') {
 9922: 	    # FIXME - not supporting calls for a specific user
 9923:             return $env{join('.',('request.course',$qualifier))};
 9924: # ------------------------------------------------------------------- user.role
 9925:         } elsif ($space eq 'role') {
 9926: 	    # FIXME - not supporting calls for a specific user
 9927:             my ($role,$where)=split(/\./,$env{'request.role'});
 9928:             if ($qualifier eq 'value') {
 9929: 		return $role;
 9930:             } elsif ($qualifier eq 'extent') {
 9931:                 return $where;
 9932:             }
 9933: # ----------------------------------------------------------------- user.domain
 9934:         } elsif ($space eq 'domain') {
 9935:             return $udom;
 9936: # ------------------------------------------------------------------- user.name
 9937:         } elsif ($space eq 'name') {
 9938:             return $uname;
 9939: # ---------------------------------------------------- Any other user namespace
 9940:         } else {
 9941: 	    my %reply;
 9942: 	    if (!$publicuser) {
 9943: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 9944: 	    }
 9945: 	    return $reply{$qualifierrest};
 9946:         }
 9947:     } elsif ($realm eq 'query') {
 9948: # ---------------------------------------------- pull stuff out of query string
 9949:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 9950: 						[$spacequalifierrest]);
 9951: 	return $env{'form.'.$spacequalifierrest}; 
 9952:    } elsif ($realm eq 'request') {
 9953: # ------------------------------------------------------------- request.browser
 9954:         if ($space eq 'browser') {
 9955:             return $env{'browser.'.$qualifier};
 9956: # ------------------------------------------------------------ request.filename
 9957:         } else {
 9958:             return $env{'request.'.$spacequalifierrest};
 9959:         }
 9960:     } elsif ($realm eq 'course') {
 9961: # ---------------------------------------------------------- course.description
 9962:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 9963:     } elsif ($realm eq 'resource') {
 9964: 
 9965: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 9966: 	    if (!$symbparm) { $symbparm=&symbread(); }
 9967: 	}
 9968: 
 9969:         if ($qualifier eq '') {
 9970: 	    if ($space eq 'title') {
 9971: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 9972: 	        return &gettitle($symbparm);
 9973: 	    }
 9974: 	
 9975: 	    if ($space eq 'map') {
 9976: 	        my ($map) = &decode_symb($symbparm);
 9977: 	        return &symbread($map);
 9978: 	    }
 9979:             if ($space eq 'maptitle') {
 9980:                 my ($map) = &decode_symb($symbparm);
 9981:                 return &gettitle($map);
 9982:             }
 9983: 	    if ($space eq 'filename') {
 9984: 	        if ($symbparm) {
 9985: 		    return &clutter((&decode_symb($symbparm))[2]);
 9986: 	        }
 9987: 	        return &hreflocation('',$env{'request.filename'});
 9988: 	    }
 9989: 
 9990:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
 9991:                 if ($space eq 'visibleparts') {
 9992:                     my $navmap = Apache::lonnavmaps::navmap->new();
 9993:                     my $item;
 9994:                     if (ref($navmap)) {
 9995:                         my $res = $navmap->getBySymb($symbparm);
 9996:                         my $parts = $res->parts();
 9997:                         if (ref($parts) eq 'ARRAY') {
 9998:                             $item = join(',',@{$parts});
 9999:                         }
10000:                         undef($navmap);
10001:                     }
10002:                     return $item;
10003:                 }
10004:             }
10005:         }
10006: 
10007: 	my ($section, $group, @groups);
10008: 	my ($courselevelm,$courselevel);
10009:         if (($courseid eq '') && ($cid)) {
10010:             $courseid = $cid;
10011:         }
10012: 	if (($symbparm && $courseid) && 
10013: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
10014: 
10015: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
10016: 
10017: # ----------------------------------------------------- Cascading lookup scheme
10018: 	    my $symbp=$symbparm;
10019: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
10020: 
10021: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
10022: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
10023: 
10024: 	    if (($env{'user.name'} eq $uname) &&
10025: 		($env{'user.domain'} eq $udom)) {
10026: 		$section=$env{'request.course.sec'};
10027:                 @groups = split(/:/,$env{'request.course.groups'});  
10028:                 @groups=&sort_course_groups($courseid,@groups); 
10029: 	    } else {
10030: 		if (! defined($usection)) {
10031: 		    $section=&getsection($udom,$uname,$courseid);
10032: 		} else {
10033: 		    $section = $usection;
10034: 		}
10035:                 @groups = &get_users_groups($udom,$uname,$courseid);
10036: 	    }
10037: 
10038: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
10039: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
10040: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
10041: 
10042: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
10043: 	    my $courselevelr=$courseid.'.'.$symbparm;
10044: 	    $courselevelm=$courseid.'.'.$mapparm;
10045: 
10046: # ----------------------------------------------------------- first, check user
10047: 
10048: 	    my $userreply=&resdata($uname,$udom,'user',
10049: 				       ([$courselevelr,'resource'],
10050: 					[$courselevelm,'map'     ],
10051: 					[$courselevel, 'course'  ]));
10052: 	    if (defined($userreply)) { return &get_reply($userreply); }
10053: 
10054: # ------------------------------------------------ second, check some of course
10055:             my $coursereply;
10056:             if (@groups > 0) {
10057:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
10058:                                        $mapparm,$spacequalifierrest);
10059:                 if (defined($coursereply)) { return &get_reply($coursereply); }
10060:             }
10061: 
10062: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
10063: 				  $env{'course.'.$courseid.'.domain'},
10064: 				  'course',
10065: 				  ([$seclevelr,   'resource'],
10066: 				   [$seclevelm,   'map'     ],
10067: 				   [$seclevel,    'course'  ],
10068: 				   [$courselevelr,'resource']));
10069: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
10070: 
10071: # ------------------------------------------------------ third, check map parms
10072: 	    my %parmhash=();
10073: 	    my $thisparm='';
10074: 	    if (tie(%parmhash,'GDBM_File',
10075: 		    $env{'request.course.fn'}.'_parms.db',
10076: 		    &GDBM_READER(),0640)) {
10077: 		$thisparm=$parmhash{$symbparm};
10078: 		untie(%parmhash);
10079: 	    }
10080: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
10081: 	}
10082: # ------------------------------------------ fourth, look in resource metadata
10083: 
10084: 	$spacequalifierrest=~s/\./\_/;
10085: 	my $filename;
10086: 	if (!$symbparm) { $symbparm=&symbread(); }
10087: 	if ($symbparm) {
10088: 	    $filename=(&decode_symb($symbparm))[2];
10089: 	} else {
10090: 	    $filename=$env{'request.filename'};
10091: 	}
10092: 	my $metadata=&metadata($filename,$spacequalifierrest);
10093: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
10094: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
10095: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
10096: 
10097: # ---------------------------------------------- fourth, look in rest of course
10098: 	if ($symbparm && defined($courseid) && 
10099: 	    $courseid eq $env{'request.course.id'}) {
10100: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
10101: 				     $env{'course.'.$courseid.'.domain'},
10102: 				     'course',
10103: 				     ([$courselevelm,'map'   ],
10104: 				      [$courselevel, 'course']));
10105: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
10106: 	}
10107: # ------------------------------------------------------------------ Cascade up
10108: 	unless ($space eq '0') {
10109: 	    my @parts=split(/_/,$space);
10110: 	    my $id=pop(@parts);
10111: 	    my $part=join('_',@parts);
10112: 	    if ($part eq '') { $part='0'; }
10113: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
10114: 				 $symbparm,$udom,$uname,$section,1);
10115: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
10116: 	}
10117: 	if ($recurse) { return undef; }
10118: 	my $pack_def=&packages_tab_default($filename,$varname);
10119: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
10120: # ---------------------------------------------------- Any other user namespace
10121:     } elsif ($realm eq 'environment') {
10122: # ----------------------------------------------------------------- environment
10123: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
10124: 	    return $env{'environment.'.$spacequalifierrest};
10125: 	} else {
10126: 	    if ($uname eq 'anonymous' && $udom eq '') {
10127: 		return '';
10128: 	    }
10129: 	    my %returnhash=&userenvironment($udom,$uname,
10130: 					    $spacequalifierrest);
10131: 	    return $returnhash{$spacequalifierrest};
10132: 	}
10133:     } elsif ($realm eq 'system') {
10134: # ----------------------------------------------------------------- system.time
10135: 	if ($space eq 'time') {
10136: 	    return time;
10137:         }
10138:     } elsif ($realm eq 'server') {
10139: # ----------------------------------------------------------------- system.time
10140: 	if ($space eq 'name') {
10141: 	    return $ENV{'SERVER_NAME'};
10142:         }
10143:     }
10144:     return '';
10145: }
10146: 
10147: sub get_reply {
10148:     my ($reply_value) = @_;
10149:     if (ref($reply_value) eq 'ARRAY') {
10150:         if (wantarray) {
10151: 	    return @$reply_value;
10152:         }
10153:         return $reply_value->[0];
10154:     } else {
10155:         return $reply_value;
10156:     }
10157: }
10158: 
10159: sub check_group_parms {
10160:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
10161:     my @groupitems = ();
10162:     my $resultitem;
10163:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
10164:     foreach my $group (@{$groups}) {
10165:         foreach my $level (@levels) {
10166:              my $item = $courseid.'.['.$group.'].'.$level->[0];
10167:              push(@groupitems,[$item,$level->[1]]);
10168:         }
10169:     }
10170:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
10171:                             $env{'course.'.$courseid.'.domain'},
10172:                                      'course',@groupitems);
10173:     return $coursereply;
10174: }
10175: 
10176: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
10177:     my ($courseid,@groups) = @_;
10178:     @groups = sort(@groups);
10179:     return @groups;
10180: }
10181: 
10182: sub packages_tab_default {
10183:     my ($uri,$varname)=@_;
10184:     my (undef,$part,$name)=split(/\./,$varname);
10185: 
10186:     my (@extension,@specifics,$do_default);
10187:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
10188: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
10189: 	if ($pack_type eq 'default') {
10190: 	    $do_default=1;
10191: 	} elsif ($pack_type eq 'extension') {
10192: 	    push(@extension,[$package,$pack_type,$pack_part]);
10193: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
10194: 	    # only look at packages defaults for packages that this id is
10195: 	    push(@specifics,[$package,$pack_type,$pack_part]);
10196: 	}
10197:     }
10198:     # first look for a package that matches the requested part id
10199:     foreach my $package (@specifics) {
10200: 	my (undef,$pack_type,$pack_part)=@{$package};
10201: 	next if ($pack_part ne $part);
10202: 	if (defined($packagetab{"$pack_type&$name&default"})) {
10203: 	    return $packagetab{"$pack_type&$name&default"};
10204: 	}
10205:     }
10206:     # look for any possible matching non extension_ package
10207:     foreach my $package (@specifics) {
10208: 	my (undef,$pack_type,$pack_part)=@{$package};
10209: 	if (defined($packagetab{"$pack_type&$name&default"})) {
10210: 	    return $packagetab{"$pack_type&$name&default"};
10211: 	}
10212: 	if ($pack_type eq 'part') { $pack_part='0'; }
10213: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
10214: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
10215: 	}
10216:     }
10217:     # look for any posible extension_ match
10218:     foreach my $package (@extension) {
10219: 	my ($package,$pack_type)=@{$package};
10220: 	if (defined($packagetab{"$pack_type&$name&default"})) {
10221: 	    return $packagetab{"$pack_type&$name&default"};
10222: 	}
10223: 	if (defined($packagetab{$package."&$name&default"})) {
10224: 	    return $packagetab{$package."&$name&default"};
10225: 	}
10226:     }
10227:     # look for a global default setting
10228:     if ($do_default && defined($packagetab{"default&$name&default"})) {
10229: 	return $packagetab{"default&$name&default"};
10230:     }
10231:     return undef;
10232: }
10233: 
10234: sub add_prefix_and_part {
10235:     my ($prefix,$part)=@_;
10236:     my $keyroot;
10237:     if (defined($prefix) && $prefix !~ /^__/) {
10238: 	# prefix that has a part already
10239: 	$keyroot=$prefix;
10240:     } elsif (defined($prefix)) {
10241: 	# prefix that is missing a part
10242: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
10243:     } else {
10244: 	# no prefix at all
10245: 	if (defined($part)) { $keyroot='_'.$part; }
10246:     }
10247:     return $keyroot;
10248: }
10249: 
10250: # ---------------------------------------------------------------- Get metadata
10251: 
10252: my %metaentry;
10253: my %importedpartids;
10254: sub metadata {
10255:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
10256:     $uri=&declutter($uri);
10257:     # if it is a non metadata possible uri return quickly
10258:     if (($uri eq '') || 
10259: 	(($uri =~ m|^/*adm/|) && 
10260: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
10261:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
10262: 	return undef;
10263:     }
10264:     if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) 
10265: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
10266: 	return undef;
10267:     }
10268:     my $filename=$uri;
10269:     $uri=~s/\.meta$//;
10270: #
10271: # Is the metadata already cached?
10272: # Look at timestamp of caching
10273: # Everything is cached by the main uri, libraries are never directly cached
10274: #
10275:     if (!defined($liburi)) {
10276: 	my ($result,$cached)=&is_cached_new('meta',$uri);
10277: 	if (defined($cached)) { return $result->{':'.$what}; }
10278:     }
10279:     {
10280: # Imported parts would go here
10281:         my %importedids=();
10282:         my @origfileimportpartids=();
10283:         my $importedparts=0;
10284: #
10285: # Is this a recursive call for a library?
10286: #
10287: #	if (! exists($metacache{$uri})) {
10288: #	    $metacache{$uri}={};
10289: #	}
10290: 	my $cachetime = 60*60;
10291:         if ($liburi) {
10292: 	    $liburi=&declutter($liburi);
10293:             $filename=$liburi;
10294:         } else {
10295: 	    &devalidate_cache_new('meta',$uri);
10296: 	    undef(%metaentry);
10297: 	}
10298:         my %metathesekeys=();
10299:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
10300: 	my $metastring;
10301: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
10302: 	    my $which = &hreflocation('','/'.($liburi || $uri));
10303: 	    $metastring = 
10304: 		&Apache::lonnet::ssi_body($which,
10305: 					  ('grade_target' => 'meta'));
10306: 	    $cachetime = 1; # only want this cached in the child not long term
10307: 	} elsif (($uri !~ m -^(editupload)/-) && 
10308:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
10309: 	    my $file=&filelocation('',&clutter($filename));
10310: 	    #push(@{$metaentry{$uri.'.file'}},$file);
10311: 	    $metastring=&getfile($file);
10312: 	}
10313:         my $parser=HTML::LCParser->new(\$metastring);
10314:         my $token;
10315:         undef %metathesekeys;
10316:         while ($token=$parser->get_token) {
10317: 	    if ($token->[0] eq 'S') {
10318: 		if (defined($token->[2]->{'package'})) {
10319: #
10320: # This is a package - get package info
10321: #
10322: 		    my $package=$token->[2]->{'package'};
10323: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10324: 		    if (defined($token->[2]->{'id'})) { 
10325: 			$keyroot.='_'.$token->[2]->{'id'}; 
10326: 		    }
10327: 		    if ($metaentry{':packages'}) {
10328: 			$metaentry{':packages'}.=','.$package.$keyroot;
10329: 		    } else {
10330: 			$metaentry{':packages'}=$package.$keyroot;
10331: 		    }
10332: 		    foreach my $pack_entry (keys(%packagetab)) {
10333: 			my $part=$keyroot;
10334: 			$part=~s/^\_//;
10335: 			if ($pack_entry=~/^\Q$package\E\&/ || 
10336: 			    $pack_entry=~/^\Q$package\E_0\&/) {
10337: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
10338: 			    # ignore package.tab specified default values
10339:                             # here &package_tab_default() will fetch those
10340: 			    if ($subp eq 'default') { next; }
10341: 			    my $value=$packagetab{$pack_entry};
10342: 			    my $unikey;
10343: 			    if ($pack =~ /_0$/) {
10344: 				$unikey='parameter_0_'.$name;
10345: 				$part=0;
10346: 			    } else {
10347: 				$unikey='parameter'.$keyroot.'_'.$name;
10348: 			    }
10349: 			    if ($subp eq 'display') {
10350: 				$value.=' [Part: '.$part.']';
10351: 			    }
10352: 			    $metaentry{':'.$unikey.'.part'}=$part;
10353: 			    $metathesekeys{$unikey}=1;
10354: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10355: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
10356: 			    }
10357: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
10358: 				$metaentry{':'.$unikey}=
10359: 				    $metaentry{':'.$unikey.'.default'};
10360: 			    }
10361: 			}
10362: 		    }
10363: 		} else {
10364: #
10365: # This is not a package - some other kind of start tag
10366: #
10367: 		    my $entry=$token->[1];
10368: 		    my $unikey='';
10369: 
10370: 		    if ($entry eq 'import') {
10371: #
10372: # Importing a library here
10373: #
10374:                         my $location=$parser->get_text('/import');
10375:                         my $dir=$filename;
10376:                         $dir=~s|[^/]*$||;
10377:                         $location=&filelocation($dir,$location);
10378:                        
10379:                         my $importmode=$token->[2]->{'importmode'};
10380:                         if ($importmode eq 'problem') {
10381: # Import as problem/response
10382:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10383:                         } elsif ($importmode eq 'part') {
10384: # Import as part(s)
10385:                            $importedparts=1;
10386: # We need to get the original file and the imported file to get the part order correct
10387: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
10388: # Load and inspect original file
10389:                            if ($#origfileimportpartids<0) {
10390:                               undef(%importedpartids);
10391:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
10392:                               my $origfile=&getfile($origfilelocation);
10393:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10394:                            }
10395: 
10396: # Load and inspect imported file
10397:                            my $impfile=&getfile($location);
10398:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10399:                            if ($#impfilepartids>=0) {
10400: # This problem had parts
10401:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
10402:                            } else {
10403: # Importing by turning a single problem into a problem part
10404: # It gets the import-tags ID as part-ID
10405:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
10406:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
10407:                            }
10408:                         } else {
10409: # Normal import
10410:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10411:                            if (defined($token->[2]->{'id'})) {
10412:                               $unikey.='_'.$token->[2]->{'id'};
10413:                            }
10414:                         }
10415: 
10416: 			if ($depthcount<20) {
10417: 			    my $metadata = 
10418: 				&metadata($uri,'keys', $location,$unikey,
10419: 					  $depthcount+1);
10420: 			    foreach my $meta (split(',',$metadata)) {
10421: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
10422: 				$metathesekeys{$meta}=1;
10423: 			    }
10424: 			
10425:                         }
10426: 		    } else {
10427: #
10428: # Not importing, some other kind of non-package, non-library start tag
10429: # 
10430:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
10431:                         if (defined($token->[2]->{'id'})) {
10432:                             $unikey.='_'.$token->[2]->{'id'};
10433:                         }
10434: 			if (defined($token->[2]->{'name'})) { 
10435: 			    $unikey.='_'.$token->[2]->{'name'}; 
10436: 			}
10437: 			$metathesekeys{$unikey}=1;
10438: 			foreach my $param (@{$token->[3]}) {
10439: 			    $metaentry{':'.$unikey.'.'.$param} =
10440: 				$token->[2]->{$param};
10441: 			}
10442: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
10443: 			my $default=$metaentry{':'.$unikey.'.default'};
10444: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
10445: 		 # only ws inside the tag, and not in default, so use default
10446: 		 # as value
10447: 			    $metaentry{':'.$unikey}=$default;
10448: 			} elsif ( $internaltext =~ /\S/ ) {
10449: 		  # something interesting inside the tag
10450: 			    $metaentry{':'.$unikey}=$internaltext;
10451: 			} else {
10452: 		  # no interesting values, don't set a default
10453: 			}
10454: # end of not-a-package not-a-library import
10455: 		    }
10456: # end of not-a-package start tag
10457: 		}
10458: # the next is the end of "start tag"
10459: 	    }
10460: 	}
10461: 	my ($extension) = ($uri =~ /\.(\w+)$/);
10462: 	$extension = lc($extension);
10463: 	if ($extension eq 'htm') { $extension='html'; }
10464: 
10465: 	foreach my $key (keys(%packagetab)) {
10466: 	    #no specific packages #how's our extension
10467: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
10468: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
10469: 					 \%metathesekeys);
10470: 	}
10471: 
10472: 	if (!exists($metaentry{':packages'})
10473: 	    || $packagetab{"import_defaults&extension_$extension"}) {
10474: 	    foreach my $key (keys(%packagetab)) {
10475: 		#no specific packages well let's get default then
10476: 		if ($key!~/^default&/) { next; }
10477: 		&metadata_create_package_def($uri,$key,'default',
10478: 					     \%metathesekeys);
10479: 	    }
10480: 	}
10481: # are there custom rights to evaluate
10482: 	if ($metaentry{':copyright'} eq 'custom') {
10483: 
10484:     #
10485:     # Importing a rights file here
10486:     #
10487: 	    unless ($depthcount) {
10488: 		my $location=$metaentry{':customdistributionfile'};
10489: 		my $dir=$filename;
10490: 		$dir=~s|[^/]*$||;
10491: 		$location=&filelocation($dir,$location);
10492: 		my $rights_metadata =
10493: 		    &metadata($uri,'keys',$location,'_rights',
10494: 			      $depthcount+1);
10495: 		foreach my $rights (split(',',$rights_metadata)) {
10496: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
10497: 		    $metathesekeys{$rights}=1;
10498: 		}
10499: 	    }
10500: 	}
10501: 	# uniqifiy package listing
10502: 	my %seen;
10503: 	my @uniq_packages =
10504: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
10505: 	$metaentry{':packages'} = join(',',@uniq_packages);
10506: 
10507:         if ($importedparts) {
10508: # We had imported parts and need to rebuild partorder
10509:            $metaentry{':partorder'}='';
10510:            $metathesekeys{'partorder'}=1;
10511:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
10512:                if ($origfileimportpartids[$index] eq 'part') {
10513: # original part, part of the problem
10514:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
10515:                } else {
10516: # we have imported parts at this position
10517:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
10518:                }
10519:            }
10520:            $metaentry{':partorder'}=~s/^\,//;
10521:         }
10522: 
10523: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
10524: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
10525: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
10526: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
10527: # this is the end of "was not already recently cached
10528:     }
10529:     return $metaentry{':'.$what};
10530: }
10531: 
10532: sub metadata_create_package_def {
10533:     my ($uri,$key,$package,$metathesekeys)=@_;
10534:     my ($pack,$name,$subp)=split(/\&/,$key);
10535:     if ($subp eq 'default') { next; }
10536:     
10537:     if (defined($metaentry{':packages'})) {
10538: 	$metaentry{':packages'}.=','.$package;
10539:     } else {
10540: 	$metaentry{':packages'}=$package;
10541:     }
10542:     my $value=$packagetab{$key};
10543:     my $unikey;
10544:     $unikey='parameter_0_'.$name;
10545:     $metaentry{':'.$unikey.'.part'}=0;
10546:     $$metathesekeys{$unikey}=1;
10547:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10548: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
10549:     }
10550:     if (defined($metaentry{':'.$unikey.'.default'})) {
10551: 	$metaentry{':'.$unikey}=
10552: 	    $metaentry{':'.$unikey.'.default'};
10553:     }
10554: }
10555: 
10556: sub metadata_generate_part0 {
10557:     my ($metadata,$metacache,$uri) = @_;
10558:     my %allnames;
10559:     foreach my $metakey (keys(%$metadata)) {
10560: 	if ($metakey=~/^parameter\_(.*)/) {
10561: 	  my $part=$$metacache{':'.$metakey.'.part'};
10562: 	  my $name=$$metacache{':'.$metakey.'.name'};
10563: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
10564: 	    $allnames{$name}=$part;
10565: 	  }
10566: 	}
10567:     }
10568:     foreach my $name (keys(%allnames)) {
10569:       $$metadata{"parameter_0_$name"}=1;
10570:       my $key=":parameter_0_$name";
10571:       $$metacache{"$key.part"}='0';
10572:       $$metacache{"$key.name"}=$name;
10573:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
10574: 					   $allnames{$name}.'_'.$name.
10575: 					   '.type'};
10576:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
10577: 			     '.display'};
10578:       my $expr='[Part: '.$allnames{$name}.']';
10579:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
10580:       $$metacache{"$key.display"}=$olddis;
10581:     }
10582: }
10583: 
10584: # ------------------------------------------------------ Devalidate title cache
10585: 
10586: sub devalidate_title_cache {
10587:     my ($url)=@_;
10588:     if (!$env{'request.course.id'}) { return; }
10589:     my $symb=&symbread($url);
10590:     if (!$symb) { return; }
10591:     my $key=$env{'request.course.id'}."\0".$symb;
10592:     &devalidate_cache_new('title',$key);
10593: }
10594: 
10595: # ------------------------------------------------- Get the title of a course
10596: 
10597: sub current_course_title {
10598:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
10599: }
10600: # ------------------------------------------------- Get the title of a resource
10601: 
10602: sub gettitle {
10603:     my $urlsymb=shift;
10604:     my $symb=&symbread($urlsymb);
10605:     if ($symb) {
10606: 	my $key=$env{'request.course.id'}."\0".$symb;
10607: 	my ($result,$cached)=&is_cached_new('title',$key);
10608: 	if (defined($cached)) { 
10609: 	    return $result;
10610: 	}
10611: 	my ($map,$resid,$url)=&decode_symb($symb);
10612: 	my $title='';
10613: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
10614: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
10615: 	} else {
10616: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10617: 		    &GDBM_READER(),0640)) {
10618: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
10619: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
10620: 		untie(%bighash);
10621: 	    }
10622: 	}
10623: 	$title=~s/\&colon\;/\:/gs;
10624: 	if ($title) {
10625: # Remember both $symb and $title for dynamic metadata
10626:             $accesshash{$symb.'___crstitle'}=$title;
10627:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
10628: # Cache this title and then return it
10629: 	    return &do_cache_new('title',$key,$title,600);
10630: 	}
10631: 	$urlsymb=$url;
10632:     }
10633:     my $title=&metadata($urlsymb,'title');
10634:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
10635:     return $title;
10636: }
10637: 
10638: sub get_slot {
10639:     my ($which,$cnum,$cdom)=@_;
10640:     if (!$cnum || !$cdom) {
10641: 	(undef,my $courseid)=&whichuser();
10642: 	$cdom=$env{'course.'.$courseid.'.domain'};
10643: 	$cnum=$env{'course.'.$courseid.'.num'};
10644:     }
10645:     my $key=join("\0",'slots',$cdom,$cnum,$which);
10646:     my %slotinfo;
10647:     if (exists($remembered{$key})) {
10648: 	$slotinfo{$which} = $remembered{$key};
10649:     } else {
10650: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
10651: 	&Apache::lonhomework::showhash(%slotinfo);
10652: 	my ($tmp)=keys(%slotinfo);
10653: 	if ($tmp=~/^error:/) { return (); }
10654: 	$remembered{$key} = $slotinfo{$which};
10655:     }
10656:     if (ref($slotinfo{$which}) eq 'HASH') {
10657: 	return %{$slotinfo{$which}};
10658:     }
10659:     return $slotinfo{$which};
10660: }
10661: 
10662: sub get_reservable_slots {
10663:     my ($cnum,$cdom,$uname,$udom) = @_;
10664:     my $now = time;
10665:     my $reservable_info;
10666:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
10667:     if (exists($remembered{$key})) {
10668:         $reservable_info = $remembered{$key};
10669:     } else {
10670:         my %resv;
10671:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
10672:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
10673:         $reservable_info = \%resv;
10674:         $remembered{$key} = $reservable_info;
10675:     }
10676:     return $reservable_info;
10677: }
10678: 
10679: sub get_course_slots {
10680:     my ($cnum,$cdom) = @_;
10681:     my $hashid=$cnum.':'.$cdom;
10682:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
10683:     if (defined($cached)) {
10684:         if (ref($result) eq 'HASH') {
10685:             return %{$result};
10686:         }
10687:     } else {
10688:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
10689:         my ($tmp) = keys(%slots);
10690:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
10691:             &do_cache_new('allslots',$hashid,\%slots,600);
10692:             return %slots;
10693:         }
10694:     }
10695:     return;
10696: }
10697: 
10698: sub devalidate_slots_cache {
10699:     my ($cnum,$cdom)=@_;
10700:     my $hashid=$cnum.':'.$cdom;
10701:     &devalidate_cache_new('allslots',$hashid);
10702: }
10703: 
10704: sub get_coursechange {
10705:     my ($cdom,$cnum) = @_;
10706:     if ($cdom eq '' || $cnum eq '') {
10707:         return unless ($env{'request.course.id'});
10708:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10709:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10710:     }
10711:     my $hashid=$cdom.'_'.$cnum;
10712:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
10713:     if ((defined($cached)) && ($change ne '')) {
10714:         return $change;
10715:     } else {
10716:         my %crshash;
10717:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
10718:         if ($crshash{'internal.contentchange'} eq '') {
10719:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
10720:             if ($change eq '') {
10721:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
10722:                 $change = $crshash{'internal.created'};
10723:             }
10724:         } else {
10725:             $change = $crshash{'internal.contentchange'};
10726:         }
10727:         my $cachetime = 600;
10728:         &do_cache_new('crschange',$hashid,$change,$cachetime);
10729:     }
10730:     return $change;
10731: }
10732: 
10733: sub devalidate_coursechange_cache {
10734:     my ($cnum,$cdom)=@_;
10735:     my $hashid=$cnum.':'.$cdom;
10736:     &devalidate_cache_new('crschange',$hashid);
10737: }
10738: 
10739: # ------------------------------------------------- Update symbolic store links
10740: 
10741: sub symblist {
10742:     my ($mapname,%newhash)=@_;
10743:     $mapname=&deversion(&declutter($mapname));
10744:     my %hash;
10745:     if (($env{'request.course.fn'}) && (%newhash)) {
10746:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
10747:                       &GDBM_WRCREAT(),0640)) {
10748: 	    foreach my $url (keys(%newhash)) {
10749: 		next if ($url eq 'last_known'
10750: 			 && $env{'form.no_update_last_known'});
10751: 		$hash{declutter($url)}=&encode_symb($mapname,
10752: 						    $newhash{$url}->[1],
10753: 						    $newhash{$url}->[0]);
10754:             }
10755:             if (untie(%hash)) {
10756: 		return 'ok';
10757:             }
10758:         }
10759:     }
10760:     return 'error';
10761: }
10762: 
10763: # --------------------------------------------------------------- Verify a symb
10764: 
10765: sub symbverify {
10766:     my ($symb,$thisurl,$encstate)=@_;
10767:     my $thisfn=$thisurl;
10768:     $thisfn=&declutter($thisfn);
10769: # direct jump to resource in page or to a sequence - will construct own symbs
10770:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
10771: # check URL part
10772:     my ($map,$resid,$url)=&decode_symb($symb);
10773: 
10774:     unless ($url eq $thisfn) { return 0; }
10775: 
10776:     $symb=&symbclean($symb);
10777:     $thisurl=&deversion($thisurl);
10778:     $thisfn=&deversion($thisfn);
10779: 
10780:     my %bighash;
10781:     my $okay=0;
10782: 
10783:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10784:                             &GDBM_READER(),0640)) {
10785:         my $noclutter;
10786:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
10787:             $thisurl =~ s/\?.+$//;
10788:             if ($map =~ m{^uploaded/.+\.page$}) {
10789:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
10790:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
10791:                 $noclutter = 1;
10792:             }
10793:         }
10794:         my $ids;
10795:         if ($noclutter) {
10796:             $ids=$bighash{'ids_'.$thisurl};
10797:         } else {
10798:             $ids=$bighash{'ids_'.&clutter($thisurl)};
10799:         }
10800:         unless ($ids) {
10801:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
10802:             $ids=$bighash{$idkey};
10803:         }
10804:         if ($ids) {
10805: # ------------------------------------------------------------------- Has ID(s)
10806:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
10807:                 $symb =~ s/\?.+$//;
10808:             }
10809: 	    foreach my $id (split(/\,/,$ids)) {
10810: 	       my ($mapid,$resid)=split(/\./,$id);
10811:                if (
10812:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
10813:    eq $symb) {
10814:                    if (ref($encstate)) {
10815:                        $$encstate = $bighash{'encrypted_'.$id};
10816:                    }
10817:                    if (($env{'request.role.adv'}) ||
10818:                        ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
10819:                        ($thisurl eq '/adm/navmaps')) {
10820:                        $okay=1;
10821:                        last;
10822:                    }
10823:                }
10824:            }
10825:         }
10826: 	untie(%bighash);
10827:     }
10828:     return $okay;
10829: }
10830: 
10831: # --------------------------------------------------------------- Clean-up symb
10832: 
10833: sub symbclean {
10834:     my $symb=shift;
10835:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10836: # remove version from map
10837:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
10838: 
10839: # remove version from URL
10840:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
10841: 
10842: # remove wrapper
10843: 
10844:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
10845:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
10846:     return $symb;
10847: }
10848: 
10849: # ---------------------------------------------- Split symb to find map and url
10850: 
10851: sub encode_symb {
10852:     my ($map,$resid,$url)=@_;
10853:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
10854: }
10855: 
10856: sub decode_symb {
10857:     my $symb=shift;
10858:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10859:     my ($map,$resid,$url)=split(/___/,$symb);
10860:     return (&fixversion($map),$resid,&fixversion($url));
10861: }
10862: 
10863: sub fixversion {
10864:     my $fn=shift;
10865:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
10866:     my %bighash;
10867:     my $uri=&clutter($fn);
10868:     my $key=$env{'request.course.id'}.'_'.$uri;
10869: # is this cached?
10870:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
10871:     if (defined($cached)) { return $result; }
10872: # unfortunately not cached, or expired
10873:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10874: 	    &GDBM_READER(),0640)) {
10875:  	if ($bighash{'version_'.$uri}) {
10876:  	    my $version=$bighash{'version_'.$uri};
10877:  	    unless (($version eq 'mostrecent') || 
10878: 		    ($version==&getversion($uri))) {
10879:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
10880:  	    }
10881:  	}
10882:  	untie %bighash;
10883:     }
10884:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
10885: }
10886: 
10887: sub deversion {
10888:     my $url=shift;
10889:     $url=~s/\.\d+\.(\w+)$/\.$1/;
10890:     return $url;
10891: }
10892: 
10893: # ------------------------------------------------------ Return symb list entry
10894: 
10895: sub symbread {
10896:     my ($thisfn,$donotrecurse)=@_;
10897:     my $cache_str;
10898:     if ($thisfn ne '') {
10899:         $cache_str='request.symbread.cached.'.$thisfn;
10900:         if ($env{$cache_str} ne '') {
10901:             return $env{$cache_str};
10902:         }
10903:    } else {
10904: # no filename provided? try from environment
10905:         if ($env{'request.symb'}) {
10906:             return $env{$cache_str}=&symbclean($env{'request.symb'});
10907:         }
10908:         $thisfn=$env{'request.filename'};
10909:     }
10910:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
10911: # is that filename actually a symb? Verify, clean, and return
10912:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
10913: 	if (&symbverify($thisfn,$1)) {
10914: 	    return $env{$cache_str}=&symbclean($thisfn);
10915: 	}
10916:     }
10917:     $thisfn=declutter($thisfn);
10918:     my %hash;
10919:     my %bighash;
10920:     my $syval='';
10921:     if (($env{'request.course.fn'}) && ($thisfn)) {
10922:         my $targetfn = $thisfn;
10923:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
10924:             $targetfn = 'adm/wrapper/'.$thisfn;
10925:         }
10926: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
10927: 	    $targetfn=$1;
10928: 	}
10929:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
10930:                       &GDBM_READER(),0640)) {
10931: 	    $syval=$hash{$targetfn};
10932:             untie(%hash);
10933:         }
10934: # ---------------------------------------------------------- There was an entry
10935:         if ($syval) {
10936: 	    #unless ($syval=~/\_\d+$/) {
10937: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
10938: 		    #&appenv({'request.ambiguous' => $thisfn});
10939: 		    #return $env{$cache_str}='';
10940: 		#}    
10941: 		#$syval.=$1;
10942: 	    #}
10943:         } else {
10944: # ------------------------------------------------------- Was not in symb table
10945:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10946:                             &GDBM_READER(),0640)) {
10947: # ---------------------------------------------- Get ID(s) for current resource
10948:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
10949:               unless ($ids) { 
10950:                  $ids=$bighash{'ids_/'.$thisfn};
10951:               }
10952:               unless ($ids) {
10953: # alias?
10954: 		  $ids=$bighash{'mapalias_'.$thisfn};
10955:               }
10956:               if ($ids) {
10957: # ------------------------------------------------------------------- Has ID(s)
10958:                  my @possibilities=split(/\,/,$ids);
10959:                  if ($#possibilities==0) {
10960: # ----------------------------------------------- There is only one possibility
10961: 		     my ($mapid,$resid)=split(/\./,$ids);
10962: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
10963: 						    $resid,$thisfn);
10964:                  } elsif (!$donotrecurse) {
10965: # ------------------------------------------ There is more than one possibility
10966:                      my $realpossible=0;
10967:                      foreach my $id (@possibilities) {
10968: 			 my $file=$bighash{'src_'.$id};
10969:                          if (&allowed('bre',$file)) {
10970:          		    my ($mapid,$resid)=split(/\./,$id);
10971:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
10972: 				$realpossible++;
10973:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
10974: 						    $resid,$thisfn);
10975:                             }
10976: 			 }
10977:                      }
10978: 		     if ($realpossible!=1) { $syval=''; }
10979:                  } else {
10980:                      $syval='';
10981:                  }
10982: 	      }
10983:               untie(%bighash)
10984:            }
10985:         }
10986:         if ($syval) {
10987: 	    return $env{$cache_str}=$syval;
10988:         }
10989:     }
10990:     &appenv({'request.ambiguous' => $thisfn});
10991:     return $env{$cache_str}='';
10992: }
10993: 
10994: # ---------------------------------------------------------- Return random seed
10995: 
10996: sub numval {
10997:     my $txt=shift;
10998:     $txt=~tr/A-J/0-9/;
10999:     $txt=~tr/a-j/0-9/;
11000:     $txt=~tr/K-T/0-9/;
11001:     $txt=~tr/k-t/0-9/;
11002:     $txt=~tr/U-Z/0-5/;
11003:     $txt=~tr/u-z/0-5/;
11004:     $txt=~s/\D//g;
11005:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
11006:     return int($txt);
11007: }
11008: 
11009: sub numval2 {
11010:     my $txt=shift;
11011:     $txt=~tr/A-J/0-9/;
11012:     $txt=~tr/a-j/0-9/;
11013:     $txt=~tr/K-T/0-9/;
11014:     $txt=~tr/k-t/0-9/;
11015:     $txt=~tr/U-Z/0-5/;
11016:     $txt=~tr/u-z/0-5/;
11017:     $txt=~s/\D//g;
11018:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11019:     my $total;
11020:     foreach my $val (@txts) { $total+=$val; }
11021:     if ($_64bit) { if ($total > 2**32) { return -1; } }
11022:     return int($total);
11023: }
11024: 
11025: sub numval3 {
11026:     use integer;
11027:     my $txt=shift;
11028:     $txt=~tr/A-J/0-9/;
11029:     $txt=~tr/a-j/0-9/;
11030:     $txt=~tr/K-T/0-9/;
11031:     $txt=~tr/k-t/0-9/;
11032:     $txt=~tr/U-Z/0-5/;
11033:     $txt=~tr/u-z/0-5/;
11034:     $txt=~s/\D//g;
11035:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11036:     my $total;
11037:     foreach my $val (@txts) { $total+=$val; }
11038:     if ($_64bit) { $total=(($total<<32)>>32); }
11039:     return $total;
11040: }
11041: 
11042: sub digest {
11043:     my ($data)=@_;
11044:     my $digest=&Digest::MD5::md5($data);
11045:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
11046:     my ($e,$f);
11047:     {
11048:         use integer;
11049:         $e=($a+$b);
11050:         $f=($c+$d);
11051:         if ($_64bit) {
11052:             $e=(($e<<32)>>32);
11053:             $f=(($f<<32)>>32);
11054:         }
11055:     }
11056:     if (wantarray) {
11057: 	return ($e,$f);
11058:     } else {
11059: 	my $g;
11060: 	{
11061: 	    use integer;
11062: 	    $g=($e+$f);
11063: 	    if ($_64bit) {
11064: 		$g=(($g<<32)>>32);
11065: 	    }
11066: 	}
11067: 	return $g;
11068:     }
11069: }
11070: 
11071: sub latest_rnd_algorithm_id {
11072:     return '64bit5';
11073: }
11074: 
11075: sub get_rand_alg {
11076:     my ($courseid)=@_;
11077:     if (!$courseid) { $courseid=(&whichuser())[1]; }
11078:     if ($courseid) {
11079: 	return $env{"course.$courseid.rndseed"};
11080:     }
11081:     return &latest_rnd_algorithm_id();
11082: }
11083: 
11084: sub validCODE {
11085:     my ($CODE)=@_;
11086:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
11087:     return 0;
11088: }
11089: 
11090: sub getCODE {
11091:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
11092:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
11093: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
11094: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
11095: 	return $Apache::lonhomework::history{'resource.CODE'};
11096:     }
11097:     return undef;
11098: }
11099: #
11100: #  Determines the random seed for a specific context:
11101: #
11102: # parameters:
11103: #   symb      - in course context the symb for the seed.
11104: #   course_id - The course id of the form domain_coursenum.
11105: #   domain    - Domain for the user.
11106: #   course    - Course for the user.
11107: #   cenv      - environment of the course.
11108: #
11109: # NOTE:
11110: #   All parameters are picked out of the environment if missing
11111: #   or not defined.
11112: #   If a symb cannot be determined the current time is used instead.
11113: #
11114: #  For a given well defined symb, courside, domain, username,
11115: #  and course environment, the seed is reproducible.
11116: #
11117: sub rndseed {
11118:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
11119:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
11120:     if (!defined($symb)) {
11121: 	unless ($symb=$wsymb) { return time; }
11122:     }
11123:     if (!defined $courseid) { 
11124: 	$courseid=$wcourseid; 
11125:     }
11126:     if (!defined $domain) { $domain=$wdomain; }
11127:     if (!defined $username) { $username=$wusername }
11128: 
11129:     my $which;
11130:     if (defined($cenv->{'rndseed'})) {
11131: 	$which = $cenv->{'rndseed'};
11132:     } else {
11133: 	$which =&get_rand_alg($courseid);
11134:     }
11135:     if (defined(&getCODE())) {
11136: 	if ($which eq '64bit5') {
11137: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
11138: 	} elsif ($which eq '64bit4') {
11139: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
11140: 	} else {
11141: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
11142: 	}
11143:     } elsif ($which eq '64bit5') {
11144: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
11145:     } elsif ($which eq '64bit4') {
11146: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
11147:     } elsif ($which eq '64bit3') {
11148: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
11149:     } elsif ($which eq '64bit2') {
11150: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
11151:     } elsif ($which eq '64bit') {
11152: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
11153:     }
11154:     return &rndseed_32bit($symb,$courseid,$domain,$username);
11155: }
11156: 
11157: sub rndseed_32bit {
11158:     my ($symb,$courseid,$domain,$username)=@_;
11159:     {
11160: 	use integer;
11161: 	my $symbchck=unpack("%32C*",$symb) << 27;
11162: 	my $symbseed=numval($symb) << 22;
11163: 	my $namechck=unpack("%32C*",$username) << 17;
11164: 	my $nameseed=numval($username) << 12;
11165: 	my $domainseed=unpack("%32C*",$domain) << 7;
11166: 	my $courseseed=unpack("%32C*",$courseid);
11167: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
11168: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11169: 	#&logthis("rndseed :$num:$symb");
11170: 	if ($_64bit) { $num=(($num<<32)>>32); }
11171: 	return $num;
11172:     }
11173: }
11174: 
11175: sub rndseed_64bit {
11176:     my ($symb,$courseid,$domain,$username)=@_;
11177:     {
11178: 	use integer;
11179: 	my $symbchck=unpack("%32S*",$symb) << 21;
11180: 	my $symbseed=numval($symb) << 10;
11181: 	my $namechck=unpack("%32S*",$username);
11182: 	
11183: 	my $nameseed=numval($username) << 21;
11184: 	my $domainseed=unpack("%32S*",$domain) << 10;
11185: 	my $courseseed=unpack("%32S*",$courseid);
11186: 	
11187: 	my $num1=$symbchck+$symbseed+$namechck;
11188: 	my $num2=$nameseed+$domainseed+$courseseed;
11189: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11190: 	#&logthis("rndseed :$num:$symb");
11191: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11192: 	return "$num1,$num2";
11193:     }
11194: }
11195: 
11196: sub rndseed_64bit2 {
11197:     my ($symb,$courseid,$domain,$username)=@_;
11198:     {
11199: 	use integer;
11200: 	# strings need to be an even # of cahracters long, it it is odd the
11201:         # last characters gets thrown away
11202: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
11203: 	my $symbseed=numval($symb) << 10;
11204: 	my $namechck=unpack("%32S*",$username.' ');
11205: 	
11206: 	my $nameseed=numval($username) << 21;
11207: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
11208: 	my $courseseed=unpack("%32S*",$courseid.' ');
11209: 	
11210: 	my $num1=$symbchck+$symbseed+$namechck;
11211: 	my $num2=$nameseed+$domainseed+$courseseed;
11212: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11213: 	#&logthis("rndseed :$num:$symb");
11214: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11215: 	return "$num1,$num2";
11216:     }
11217: }
11218: 
11219: sub rndseed_64bit3 {
11220:     my ($symb,$courseid,$domain,$username)=@_;
11221:     {
11222: 	use integer;
11223: 	# strings need to be an even # of cahracters long, it it is odd the
11224:         # last characters gets thrown away
11225: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
11226: 	my $symbseed=numval2($symb) << 10;
11227: 	my $namechck=unpack("%32S*",$username.' ');
11228: 	
11229: 	my $nameseed=numval2($username) << 21;
11230: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
11231: 	my $courseseed=unpack("%32S*",$courseid.' ');
11232: 	
11233: 	my $num1=$symbchck+$symbseed+$namechck;
11234: 	my $num2=$nameseed+$domainseed+$courseseed;
11235: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11236: 	#&logthis("rndseed :$num1:$num2:$_64bit");
11237: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11238: 	
11239: 	return "$num1:$num2";
11240:     }
11241: }
11242: 
11243: sub rndseed_64bit4 {
11244:     my ($symb,$courseid,$domain,$username)=@_;
11245:     {
11246: 	use integer;
11247: 	# strings need to be an even # of cahracters long, it it is odd the
11248:         # last characters gets thrown away
11249: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
11250: 	my $symbseed=numval3($symb) << 10;
11251: 	my $namechck=unpack("%32S*",$username.' ');
11252: 	
11253: 	my $nameseed=numval3($username) << 21;
11254: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
11255: 	my $courseseed=unpack("%32S*",$courseid.' ');
11256: 	
11257: 	my $num1=$symbchck+$symbseed+$namechck;
11258: 	my $num2=$nameseed+$domainseed+$courseseed;
11259: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11260: 	#&logthis("rndseed :$num1:$num2:$_64bit");
11261: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11262: 	
11263: 	return "$num1:$num2";
11264:     }
11265: }
11266: 
11267: sub rndseed_64bit5 {
11268:     my ($symb,$courseid,$domain,$username)=@_;
11269:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
11270:     return "$num1:$num2";
11271: }
11272: 
11273: sub rndseed_CODE_64bit {
11274:     my ($symb,$courseid,$domain,$username)=@_;
11275:     {
11276: 	use integer;
11277: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
11278: 	my $symbseed=numval2($symb);
11279: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11280: 	my $CODEseed=numval(&getCODE());
11281: 	my $courseseed=unpack("%32S*",$courseid.' ');
11282: 	my $num1=$symbseed+$CODEchck;
11283: 	my $num2=$CODEseed+$courseseed+$symbchck;
11284: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11285: 	#&logthis("rndseed :$num1:$num2:$symb");
11286: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
11287: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
11288: 	return "$num1:$num2";
11289:     }
11290: }
11291: 
11292: sub rndseed_CODE_64bit4 {
11293:     my ($symb,$courseid,$domain,$username)=@_;
11294:     {
11295: 	use integer;
11296: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
11297: 	my $symbseed=numval3($symb);
11298: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11299: 	my $CODEseed=numval3(&getCODE());
11300: 	my $courseseed=unpack("%32S*",$courseid.' ');
11301: 	my $num1=$symbseed+$CODEchck;
11302: 	my $num2=$CODEseed+$courseseed+$symbchck;
11303: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11304: 	#&logthis("rndseed :$num1:$num2:$symb");
11305: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
11306: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
11307: 	return "$num1:$num2";
11308:     }
11309: }
11310: 
11311: sub rndseed_CODE_64bit5 {
11312:     my ($symb,$courseid,$domain,$username)=@_;
11313:     my $code = &getCODE();
11314:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
11315:     return "$num1:$num2";
11316: }
11317: 
11318: sub setup_random_from_rndseed {
11319:     my ($rndseed)=@_;
11320:     if ($rndseed =~/([,:])/) {
11321: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
11322: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
11323:     } else {
11324: 	&Math::Random::random_set_seed_from_phrase($rndseed);
11325:     }
11326: }
11327: 
11328: sub latest_receipt_algorithm_id {
11329:     return 'receipt3';
11330: }
11331: 
11332: sub recunique {
11333:     my $fucourseid=shift;
11334:     my $unique;
11335:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
11336: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
11337: 	$unique=$env{"course.$fucourseid.internal.encseed"};
11338:     } else {
11339: 	$unique=$perlvar{'lonReceipt'};
11340:     }
11341:     return unpack("%32C*",$unique);
11342: }
11343: 
11344: sub recprefix {
11345:     my $fucourseid=shift;
11346:     my $prefix;
11347:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
11348: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
11349: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
11350:     } else {
11351: 	$prefix=$perlvar{'lonHostID'};
11352:     }
11353:     return unpack("%32C*",$prefix);
11354: }
11355: 
11356: sub ireceipt {
11357:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
11358: 
11359:     my $return =&recprefix($fucourseid).'-';
11360: 
11361:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
11362: 	$env{'request.state'} eq 'construct') {
11363: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
11364: 	return $return;
11365:     }
11366: 
11367:     my $cuname=unpack("%32C*",$funame);
11368:     my $cudom=unpack("%32C*",$fudom);
11369:     my $cucourseid=unpack("%32C*",$fucourseid);
11370:     my $cusymb=unpack("%32C*",$fusymb);
11371:     my $cunique=&recunique($fucourseid);
11372:     my $cpart=unpack("%32S*",$part);
11373:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
11374: 
11375: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
11376: 			       
11377: 	$return.= ($cunique%$cuname+
11378: 		   $cunique%$cudom+
11379: 		   $cusymb%$cuname+
11380: 		   $cusymb%$cudom+
11381: 		   $cucourseid%$cuname+
11382: 		   $cucourseid%$cudom+
11383: 		   $cpart%$cuname+
11384: 		   $cpart%$cudom);
11385:     } else {
11386: 	$return.= ($cunique%$cuname+
11387: 		   $cunique%$cudom+
11388: 		   $cusymb%$cuname+
11389: 		   $cusymb%$cudom+
11390: 		   $cucourseid%$cuname+
11391: 		   $cucourseid%$cudom);
11392:     }
11393:     return $return;
11394: }
11395: 
11396: sub receipt {
11397:     my ($part)=@_;
11398:     my ($symb,$courseid,$domain,$name) = &whichuser();
11399:     return &ireceipt($name,$domain,$courseid,$symb,$part);
11400: }
11401: 
11402: sub whichuser {
11403:     my ($passedsymb)=@_;
11404:     my ($symb,$courseid,$domain,$name,$publicuser);
11405:     if (defined($env{'form.grade_symb'})) {
11406: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
11407: 	my $allowed=&allowed('vgr',$tmp_courseid);
11408: 	if (!$allowed &&
11409: 	    exists($env{'request.course.sec'}) &&
11410: 	    $env{'request.course.sec'} !~ /^\s*$/) {
11411: 	    $allowed=&allowed('vgr',$tmp_courseid.
11412: 			      '/'.$env{'request.course.sec'});
11413: 	}
11414: 	if ($allowed) {
11415: 	    ($symb)=&get_env_multiple('form.grade_symb');
11416: 	    $courseid=$tmp_courseid;
11417: 	    ($domain)=&get_env_multiple('form.grade_domain');
11418: 	    ($name)=&get_env_multiple('form.grade_username');
11419: 	    return ($symb,$courseid,$domain,$name,$publicuser);
11420: 	}
11421:     }
11422:     if (!$passedsymb) {
11423: 	$symb=&symbread();
11424:     } else {
11425: 	$symb=$passedsymb;
11426:     }
11427:     $courseid=$env{'request.course.id'};
11428:     $domain=$env{'user.domain'};
11429:     $name=$env{'user.name'};
11430:     if ($name eq 'public' && $domain eq 'public') {
11431: 	if (!defined($env{'form.username'})) {
11432: 	    $env{'form.username'}.=time.rand(10000000);
11433: 	}
11434: 	$name.=$env{'form.username'};
11435:     }
11436:     return ($symb,$courseid,$domain,$name,$publicuser);
11437: 
11438: }
11439: 
11440: # ------------------------------------------------------------ Serves up a file
11441: # returns either the contents of the file or 
11442: # -1 if the file doesn't exist
11443: #
11444: # if the target is a file that was uploaded via DOCS, 
11445: # a check will be made to see if a current copy exists on the local server,
11446: # if it does this will be served, otherwise a copy will be retrieved from
11447: # the home server for the course and stored in /home/httpd/html/userfiles on
11448: # the local server.   
11449: 
11450: sub getfile {
11451:     my ($file) = @_;
11452:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
11453:     &repcopy($file);
11454:     return &readfile($file);
11455: }
11456: 
11457: sub repcopy_userfile {
11458:     my ($file)=@_;
11459:     my $londocroot = $perlvar{'lonDocRoot'};
11460:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
11461:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
11462:     my ($cdom,$cnum,$filename) = 
11463: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
11464:     my $uri="/uploaded/$cdom/$cnum/$filename";
11465:     if (-e "$file") {
11466: # we already have a local copy, check it out
11467: 	my @fileinfo = stat($file);
11468: 	my $rtncode;
11469: 	my $info;
11470: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
11471: 	if ($lwpresp ne 'ok') {
11472: # there is no such file anymore, even though we had a local copy
11473: 	    if ($rtncode eq '404') {
11474: 		unlink($file);
11475: 	    }
11476: 	    return -1;
11477: 	}
11478: 	if ($info < $fileinfo[9]) {
11479: # nice, the file we have is up-to-date, just say okay
11480: 	    return 'ok';
11481: 	} else {
11482: # the file is outdated, get rid of it
11483: 	    unlink($file);
11484: 	}
11485:     }
11486: # one way or the other, at this point, we don't have the file
11487: # construct the correct path for the file
11488:     my @parts = ($cdom,$cnum); 
11489:     if ($filename =~ m|^(.+)/[^/]+$|) {
11490: 	push @parts, split(/\//,$1);
11491:     }
11492:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
11493:     foreach my $part (@parts) {
11494: 	$path .= '/'.$part;
11495: 	if (!-e $path) {
11496: 	    mkdir($path,0770);
11497: 	}
11498:     }
11499: # now the path exists for sure
11500: # get a user agent
11501:     my $ua=new LWP::UserAgent;
11502:     my $transferfile=$file.'.in.transfer';
11503: # FIXME: this should flock
11504:     if (-e $transferfile) { return 'ok'; }
11505:     my $request;
11506:     $uri=~s/^\///;
11507:     my $homeserver = &homeserver($cnum,$cdom);
11508:     my $protocol = $protocol{$homeserver};
11509:     $protocol = 'http' if ($protocol ne 'https');
11510:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
11511:     my $response=$ua->request($request,$transferfile);
11512: # did it work?
11513:     if ($response->is_error()) {
11514: 	unlink($transferfile);
11515: 	&logthis("Userfile repcopy failed for $uri");
11516: 	return -1;
11517:     }
11518: # worked, rename the transfer file
11519:     rename($transferfile,$file);
11520:     return 'ok';
11521: }
11522: 
11523: sub tokenwrapper {
11524:     my $uri=shift;
11525:     $uri=~s|^https?\://([^/]+)||;
11526:     $uri=~s|^/||;
11527:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
11528:     my $token=$1;
11529:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
11530:     if ($udom && $uname && $file) {
11531: 	$file=~s|(\?\.*)*$||;
11532:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
11533:         my $homeserver = &homeserver($uname,$udom);
11534:         my $protocol = $protocol{$homeserver};
11535:         $protocol = 'http' if ($protocol ne 'https');
11536:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
11537:                (($uri=~/\?/)?'&':'?').'token='.$token.
11538:                                '&tokenissued='.$perlvar{'lonHostID'};
11539:     } else {
11540:         return '/adm/notfound.html';
11541:     }
11542: }
11543: 
11544: # call with reqtype HEAD: get last modification time
11545: # call with reqtype GET: get the file contents
11546: # Do not call this with reqtype GET for large files! It loads everything into memory
11547: #
11548: sub getuploaded {
11549:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
11550:     $uri=~s/^\///;
11551:     my $homeserver = &homeserver($cnum,$cdom);
11552:     my $protocol = $protocol{$homeserver};
11553:     $protocol = 'http' if ($protocol ne 'https');
11554:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
11555:     my $ua=new LWP::UserAgent;
11556:     my $request=new HTTP::Request($reqtype,$uri);
11557:     my $response=$ua->request($request);
11558:     $$rtncode = $response->code;
11559:     if (! $response->is_success()) {
11560: 	return 'failed';
11561:     }      
11562:     if ($reqtype eq 'HEAD') {
11563: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
11564:     } elsif ($reqtype eq 'GET') {
11565: 	$$info = $response->content;
11566:     }
11567:     return 'ok';
11568: }
11569: 
11570: sub readfile {
11571:     my $file = shift;
11572:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
11573:     my $fh;
11574:     open($fh,"<$file");
11575:     my $a='';
11576:     while (my $line = <$fh>) { $a .= $line; }
11577:     return $a;
11578: }
11579: 
11580: sub filelocation {
11581:     my ($dir,$file) = @_;
11582:     my $location;
11583:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
11584: 
11585:     if ($file =~ m-^/adm/-) {
11586: 	$file=~s-^/adm/wrapper/-/-;
11587: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
11588:     }
11589: 
11590:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
11591:         $location = $file;
11592:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
11593:         my ($udom,$uname,$filename)=
11594:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
11595:         my $home=&homeserver($uname,$udom);
11596:         my $is_me=0;
11597:         my @ids=&current_machine_ids();
11598:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
11599:         if ($is_me) {
11600:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
11601:         } else {
11602:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
11603:   	      $udom.'/'.$uname.'/'.$filename;
11604:         }
11605:     } elsif ($file =~ m-^/adm/-) {
11606: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
11607:     } else {
11608:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
11609:         $file=~s:^/(res|priv)/:/:;
11610:         my $space=$1;
11611:         if ( !( $file =~ m:^/:) ) {
11612:             $location = $dir. '/'.$file;
11613:         } else {
11614:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
11615:         }
11616:     }
11617:     $location=~s://+:/:g; # remove duplicate /
11618:     while ($location=~m{/\.\./}) {
11619: 	if ($location =~ m{/[^/]+/\.\./}) {
11620: 	    $location=~ s{/[^/]+/\.\./}{/}g;
11621: 	} else {
11622: 	    $location=~ s{/\.\./}{/}g;
11623: 	}
11624:     } #remove dir/..
11625:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
11626:     return $location;
11627: }
11628: 
11629: sub hreflocation {
11630:     my ($dir,$file)=@_;
11631:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
11632: 	$file=filelocation($dir,$file);
11633:     } elsif ($file=~m-^/adm/-) {
11634: 	$file=~s-^/adm/wrapper/-/-;
11635: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
11636:     }
11637:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
11638: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
11639:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
11640: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
11641: 	        {/uploaded/$1/$2/}x;
11642:     }
11643:     if ($file=~ m{^/userfiles/}) {
11644: 	$file =~ s{^/userfiles/}{/uploaded/};
11645:     }
11646:     return $file;
11647: }
11648: 
11649: 
11650: 
11651: 
11652: 
11653: sub current_machine_domains {
11654:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
11655: }
11656: 
11657: sub machine_domains {
11658:     my ($hostname) = @_;
11659:     my @domains;
11660:     my %hostname = &all_hostnames();
11661:     while( my($id, $name) = each(%hostname)) {
11662: #	&logthis("-$id-$name-$hostname-");
11663: 	if ($hostname eq $name) {
11664: 	    push(@domains,&host_domain($id));
11665: 	}
11666:     }
11667:     return @domains;
11668: }
11669: 
11670: sub current_machine_ids {
11671:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
11672: }
11673: 
11674: sub machine_ids {
11675:     my ($hostname) = @_;
11676:     $hostname ||= &hostname($perlvar{'lonHostID'});
11677:     my @ids;
11678:     my %name_to_host = &all_names();
11679:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
11680: 	return @{ $name_to_host{$hostname} };
11681:     }
11682:     return;
11683: }
11684: 
11685: sub additional_machine_domains {
11686:     my @domains;
11687:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
11688:     while( my $line = <$fh>) {
11689:         $line =~ s/\s//g;
11690:         push(@domains,$line);
11691:     }
11692:     return @domains;
11693: }
11694: 
11695: sub default_login_domain {
11696:     my $domain = $perlvar{'lonDefDomain'};
11697:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
11698:     foreach my $posdom (&current_machine_domains(),
11699:                         &additional_machine_domains()) {
11700:         if (lc($posdom) eq lc($testdomain)) {
11701:             $domain=$posdom;
11702:             last;
11703:         }
11704:     }
11705:     return $domain;
11706: }
11707: 
11708: # ------------------------------------------------------------- Declutters URLs
11709: 
11710: sub declutter {
11711:     my $thisfn=shift;
11712:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
11713:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
11714:     $thisfn=~s/^\///;
11715:     $thisfn=~s|^adm/wrapper/||;
11716:     $thisfn=~s|^adm/coursedocs/showdoc/||;
11717:     $thisfn=~s/^res\///;
11718:     $thisfn=~s/^priv\///;
11719:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
11720:         $thisfn=~s/\?.+$//;
11721:     }
11722:     return $thisfn;
11723: }
11724: 
11725: # ------------------------------------------------------------- Clutter up URLs
11726: 
11727: sub clutter {
11728:     my $thisfn='/'.&declutter(shift);
11729:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
11730: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
11731:        $thisfn='/res'.$thisfn; 
11732:     }
11733:     if ($thisfn !~m|^/adm|) {
11734: 	if ($thisfn =~ m|^/ext/|) {
11735: 	    $thisfn='/adm/wrapper'.$thisfn;
11736: 	} else {
11737: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
11738: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
11739: 	    if ($embstyle eq 'ssi'
11740: 		|| ($embstyle eq 'hdn')
11741: 		|| ($embstyle eq 'rat')
11742: 		|| ($embstyle eq 'prv')
11743: 		|| ($embstyle eq 'ign')) {
11744: 		#do nothing with these
11745: 	    } elsif (($embstyle eq 'img') 
11746: 		|| ($embstyle eq 'emb')
11747: 		|| ($embstyle eq 'wrp')) {
11748: 		$thisfn='/adm/wrapper'.$thisfn;
11749: 	    } elsif ($embstyle eq 'unk'
11750: 		     && $thisfn!~/\.(sequence|page)$/) {
11751: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
11752: 	    } else {
11753: #		&logthis("Got a blank emb style");
11754: 	    }
11755: 	}
11756:     }
11757:     return $thisfn;
11758: }
11759: 
11760: sub clutter_with_no_wrapper {
11761:     my $uri = &clutter(shift);
11762:     if ($uri =~ m-^/adm/-) {
11763: 	$uri =~ s-^/adm/wrapper/-/-;
11764: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
11765:     }
11766:     return $uri;
11767: }
11768: 
11769: sub freeze_escape {
11770:     my ($value)=@_;
11771:     if (ref($value)) {
11772: 	$value=&nfreeze($value);
11773: 	return '__FROZEN__'.&escape($value);
11774:     }
11775:     return &escape($value);
11776: }
11777: 
11778: 
11779: sub thaw_unescape {
11780:     my ($value)=@_;
11781:     if ($value =~ /^__FROZEN__/) {
11782: 	substr($value,0,10,undef);
11783: 	$value=&unescape($value);
11784: 	return &thaw($value);
11785:     }
11786:     return &unescape($value);
11787: }
11788: 
11789: sub correct_line_ends {
11790:     my ($result)=@_;
11791:     $$result =~s/\r\n/\n/mg;
11792:     $$result =~s/\r/\n/mg;
11793: }
11794: # ================================================================ Main Program
11795: 
11796: sub goodbye {
11797:    &logthis("Starting Shut down");
11798: #not converted to using infrastruture and probably shouldn't be
11799:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
11800: #converted
11801: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
11802:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
11803: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
11804: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
11805: #1.1 only
11806: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
11807: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
11808: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
11809: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
11810:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
11811:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
11812:    &logthis(sprintf("%-20s is %s",'hits',$hits));
11813:    &flushcourselogs();
11814:    &logthis("Shutting down");
11815: }
11816: 
11817: sub get_dns {
11818:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
11819:     if (!$ignore_cache) {
11820: 	my ($content,$cached)=
11821: 	    &Apache::lonnet::is_cached_new('dns',$url);
11822: 	if ($cached) {
11823: 	    &$func($content,$hashref);
11824: 	    return;
11825: 	}
11826:     }
11827: 
11828:     my %alldns;
11829:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11830:     foreach my $dns (<$config>) {
11831: 	next if ($dns !~ /^\^(\S*)/x);
11832:         my $line = $1;
11833:         my ($host,$protocol) = split(/:/,$line);
11834:         if ($protocol ne 'https') {
11835:             $protocol = 'http';
11836:         }
11837: 	$alldns{$host} = $protocol;
11838:     }
11839:     while (%alldns) {
11840: 	my ($dns) = keys(%alldns);
11841: 	my $ua=new LWP::UserAgent;
11842:         $ua->timeout(30);
11843: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
11844: 	my $response=$ua->request($request);
11845:         delete($alldns{$dns});
11846: 	next if ($response->is_error());
11847: 	my @content = split("\n",$response->content);
11848:         unless ($nocache) {
11849: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
11850:         }
11851: 	&$func(\@content,$hashref);
11852: 	return;
11853:     }
11854:     close($config);
11855:     my $which = (split('/',$url))[3];
11856:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
11857:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
11858:     my @content = <$config>;
11859:     &$func(\@content,$hashref);
11860:     return;
11861: }
11862: 
11863: # ------------------------------------------------------Get DNS checksums file
11864: sub parse_dns_checksums_tab {
11865:     my ($lines,$hashref) = @_;
11866:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
11867:     my $loncaparev = &get_server_loncaparev($machine_dom);
11868:     my ($release,$timestamp) = split(/\-/,$loncaparev);
11869:     my (%chksum,%revnum);
11870:     if (ref($lines) eq 'ARRAY') {
11871:         chomp(@{$lines});
11872:         my $version = shift(@{$lines});
11873:         if ($version eq $release) {
11874:             foreach my $line (@{$lines}) {
11875:                 my ($file,$version,$shasum) = split(/,/,$line);
11876:                 $chksum{$file} = $shasum;
11877:                 $revnum{$file} = $version;
11878:             }
11879:             if (ref($hashref) eq 'HASH') {
11880:                 %{$hashref} = (
11881:                                 sums     => \%chksum,
11882:                                 versions => \%revnum,
11883:                               );
11884:             }
11885:         }
11886:     }
11887:     return;
11888: }
11889: 
11890: sub fetch_dns_checksums {
11891:     my %checksums;
11892:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
11893:     my $loncaparev = &get_server_loncaparev($machine_dom);
11894:     my ($release,$timestamp) = split(/\-/,$loncaparev);
11895:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
11896:              \%checksums);
11897:     return \%checksums;
11898: }
11899: 
11900: # ------------------------------------------------------------ Read domain file
11901: {
11902:     my $loaded;
11903:     my %domain;
11904: 
11905:     sub parse_domain_tab {
11906: 	my ($lines) = @_;
11907: 	foreach my $line (@$lines) {
11908: 	    next if ($line =~ /^(\#|\s*$ )/x);
11909: 
11910: 	    chomp($line);
11911: 	    my ($name,@elements) = split(/:/,$line,9);
11912: 	    my %this_domain;
11913: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
11914: 			       'lang_def', 'city', 'longi', 'lati',
11915: 			       'primary') {
11916: 		$this_domain{$field} = shift(@elements);
11917: 	    }
11918: 	    $domain{$name} = \%this_domain;
11919: 	}
11920:     }
11921: 
11922:     sub reset_domain_info {
11923: 	undef($loaded);
11924: 	undef(%domain);
11925:     }
11926: 
11927:     sub load_domain_tab {
11928: 	my ($ignore_cache) = @_;
11929: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
11930: 	my $fh;
11931: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
11932: 	    my @lines = <$fh>;
11933: 	    &parse_domain_tab(\@lines);
11934: 	}
11935: 	close($fh);
11936: 	$loaded = 1;
11937:     }
11938: 
11939:     sub domain {
11940: 	&load_domain_tab() if (!$loaded);
11941: 
11942: 	my ($name,$what) = @_;
11943: 	return if ( !exists($domain{$name}) );
11944: 
11945: 	if (!$what) {
11946: 	    return $domain{$name}{'description'};
11947: 	}
11948: 	return $domain{$name}{$what};
11949:     }
11950: 
11951:     sub domain_info {
11952:         &load_domain_tab() if (!$loaded);
11953:         return %domain;
11954:     }
11955: 
11956: }
11957: 
11958: 
11959: # ------------------------------------------------------------- Read hosts file
11960: {
11961:     my %hostname;
11962:     my %hostdom;
11963:     my %libserv;
11964:     my $loaded;
11965:     my %name_to_host;
11966:     my %internetdom;
11967:     my %LC_dns_serv;
11968: 
11969:     sub parse_hosts_tab {
11970: 	my ($file) = @_;
11971: 	foreach my $configline (@$file) {
11972: 	    next if ($configline =~ /^(\#|\s*$ )/x);
11973:             chomp($configline);
11974: 	    if ($configline =~ /^\^/) {
11975:                 if ($configline =~ /^\^([\w.\-]+)/) {
11976:                     $LC_dns_serv{$1} = 1;
11977:                 }
11978:                 next;
11979:             }
11980: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
11981: 	    $name=~s/\s//g;
11982: 	    if ($id && $domain && $role && $name) {
11983: 		$hostname{$id}=$name;
11984: 		push(@{$name_to_host{$name}}, $id);
11985: 		$hostdom{$id}=$domain;
11986: 		if ($role eq 'library') { $libserv{$id}=$name; }
11987:                 if (defined($protocol)) {
11988:                     if ($protocol eq 'https') {
11989:                         $protocol{$id} = $protocol;
11990:                     } else {
11991:                         $protocol{$id} = 'http'; 
11992:                     }
11993:                 } else {
11994:                     $protocol{$id} = 'http';
11995:                 }
11996:                 if (defined($intdom)) {
11997:                     $internetdom{$id} = $intdom;
11998:                 }
11999: 	    }
12000: 	}
12001:     }
12002:     
12003:     sub reset_hosts_info {
12004: 	&purge_remembered();
12005: 	&reset_domain_info();
12006: 	&reset_hosts_ip_info();
12007: 	undef(%name_to_host);
12008: 	undef(%hostname);
12009: 	undef(%hostdom);
12010: 	undef(%libserv);
12011: 	undef($loaded);
12012:     }
12013: 
12014:     sub load_hosts_tab {
12015: 	my ($ignore_cache) = @_;
12016: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
12017: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
12018: 	my @config = <$config>;
12019: 	&parse_hosts_tab(\@config);
12020: 	close($config);
12021: 	$loaded=1;
12022:     }
12023: 
12024:     sub hostname {
12025: 	&load_hosts_tab() if (!$loaded);
12026: 
12027: 	my ($lonid) = @_;
12028: 	return $hostname{$lonid};
12029:     }
12030: 
12031:     sub all_hostnames {
12032: 	&load_hosts_tab() if (!$loaded);
12033: 
12034: 	return %hostname;
12035:     }
12036: 
12037:     sub all_names {
12038: 	&load_hosts_tab() if (!$loaded);
12039: 
12040: 	return %name_to_host;
12041:     }
12042: 
12043:     sub all_host_domain {
12044:         &load_hosts_tab() if (!$loaded);
12045:         return %hostdom;
12046:     }
12047: 
12048:     sub is_library {
12049: 	&load_hosts_tab() if (!$loaded);
12050: 
12051: 	return exists($libserv{$_[0]});
12052:     }
12053: 
12054:     sub all_library {
12055: 	&load_hosts_tab() if (!$loaded);
12056: 
12057: 	return %libserv;
12058:     }
12059: 
12060:     sub unique_library {
12061: 	#2x reverse removes all hostnames that appear more than once
12062:         my %unique = reverse &all_library();
12063:         return reverse %unique;
12064:     }
12065: 
12066:     sub get_servers {
12067: 	&load_hosts_tab() if (!$loaded);
12068: 
12069: 	my ($domain,$type) = @_;
12070: 	my %possible_hosts = ($type eq 'library') ? %libserv
12071: 	                                          : %hostname;
12072: 	my %result;
12073: 	if (ref($domain) eq 'ARRAY') {
12074: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
12075: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
12076: 		    $result{$host} = $hostname;
12077: 		}
12078: 	    }
12079: 	} else {
12080: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
12081: 		if ($hostdom{$host} eq $domain) {
12082: 		    $result{$host} = $hostname;
12083: 		}
12084: 	    }
12085: 	}
12086: 	return %result;
12087:     }
12088: 
12089:     sub get_unique_servers {
12090:         my %unique = reverse &get_servers(@_);
12091: 	return reverse %unique;
12092:     }
12093: 
12094:     sub host_domain {
12095: 	&load_hosts_tab() if (!$loaded);
12096: 
12097: 	my ($lonid) = @_;
12098: 	return $hostdom{$lonid};
12099:     }
12100: 
12101:     sub all_domains {
12102: 	&load_hosts_tab() if (!$loaded);
12103: 
12104: 	my %seen;
12105: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
12106: 	return @uniq;
12107:     }
12108: 
12109:     sub internet_dom {
12110:         &load_hosts_tab() if (!$loaded);
12111: 
12112:         my ($lonid) = @_;
12113:         return $internetdom{$lonid};
12114:     }
12115: 
12116:     sub is_LC_dns {
12117:         &load_hosts_tab() if (!$loaded);
12118: 
12119:         my ($hostname) = @_;
12120:         return exists($LC_dns_serv{$hostname});
12121:     }
12122: 
12123: }
12124: 
12125: { 
12126:     my %iphost;
12127:     my %name_to_ip;
12128:     my %lonid_to_ip;
12129: 
12130:     sub get_hosts_from_ip {
12131: 	my ($ip) = @_;
12132: 	my %iphosts = &get_iphost();
12133: 	if (ref($iphosts{$ip})) {
12134: 	    return @{$iphosts{$ip}};
12135: 	}
12136: 	return;
12137:     }
12138:     
12139:     sub reset_hosts_ip_info {
12140: 	undef(%iphost);
12141: 	undef(%name_to_ip);
12142: 	undef(%lonid_to_ip);
12143:     }
12144: 
12145:     sub get_host_ip {
12146: 	my ($lonid) = @_;
12147: 	if (exists($lonid_to_ip{$lonid})) {
12148: 	    return $lonid_to_ip{$lonid};
12149: 	}
12150: 	my $name=&hostname($lonid);
12151:    	my $ip = gethostbyname($name);
12152: 	return if (!$ip || length($ip) ne 4);
12153: 	$ip=inet_ntoa($ip);
12154: 	$name_to_ip{$name}   = $ip;
12155: 	$lonid_to_ip{$lonid} = $ip;
12156: 	return $ip;
12157:     }
12158:     
12159:     sub get_iphost {
12160: 	my ($ignore_cache) = @_;
12161: 
12162: 	if (!$ignore_cache) {
12163: 	    if (%iphost) {
12164: 		return %iphost;
12165: 	    }
12166: 	    my ($ip_info,$cached)=
12167: 		&Apache::lonnet::is_cached_new('iphost','iphost');
12168: 	    if ($cached) {
12169: 		%iphost      = %{$ip_info->[0]};
12170: 		%name_to_ip  = %{$ip_info->[1]};
12171: 		%lonid_to_ip = %{$ip_info->[2]};
12172: 		return %iphost;
12173: 	    }
12174: 	}
12175: 
12176: 	# get yesterday's info for fallback
12177: 	my %old_name_to_ip;
12178: 	my ($ip_info,$cached)=
12179: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
12180: 	if ($cached) {
12181: 	    %old_name_to_ip = %{$ip_info->[1]};
12182: 	}
12183: 
12184: 	my %name_to_host = &all_names();
12185: 	foreach my $name (keys(%name_to_host)) {
12186: 	    my $ip;
12187: 	    if (!exists($name_to_ip{$name})) {
12188: 		$ip = gethostbyname($name);
12189: 		if (!$ip || length($ip) ne 4) {
12190: 		    if (defined($old_name_to_ip{$name})) {
12191: 			$ip = $old_name_to_ip{$name};
12192: 			&logthis("Can't find $name defaulting to old $ip");
12193: 		    } else {
12194: 			&logthis("Name $name no IP found");
12195: 			next;
12196: 		    }
12197: 		} else {
12198: 		    $ip=inet_ntoa($ip);
12199: 		}
12200: 		$name_to_ip{$name} = $ip;
12201: 	    } else {
12202: 		$ip = $name_to_ip{$name};
12203: 	    }
12204: 	    foreach my $id (@{ $name_to_host{$name} }) {
12205: 		$lonid_to_ip{$id} = $ip;
12206: 	    }
12207: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
12208: 	}
12209: 	&do_cache_new('iphost','iphost',
12210: 		      [\%iphost,\%name_to_ip,\%lonid_to_ip],
12211: 		      48*60*60);
12212: 
12213: 	return %iphost;
12214:     }
12215: 
12216:     #
12217:     #  Given a DNS returns the loncapa host name for that DNS 
12218:     # 
12219:     sub host_from_dns {
12220:         my ($dns) = @_;
12221:         my @hosts;
12222:         my $ip;
12223: 
12224:         if (exists($name_to_ip{$dns})) {
12225:             $ip = $name_to_ip{$dns};
12226:         }
12227:         if (!$ip) {
12228:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
12229:             if (length($ip) == 4) { 
12230: 	        $ip   = &IO::Socket::inet_ntoa($ip);
12231:             }
12232:         }
12233:         if ($ip) {
12234: 	    @hosts = get_hosts_from_ip($ip);
12235: 	    return $hosts[0];
12236:         }
12237:         return undef;
12238:     }
12239: 
12240:     sub get_internet_names {
12241:         my ($lonid) = @_;
12242:         return if ($lonid eq '');
12243:         my ($idnref,$cached)=
12244:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
12245:         if ($cached) {
12246:             return $idnref;
12247:         }
12248:         my $ip = &get_host_ip($lonid);
12249:         my @hosts = &get_hosts_from_ip($ip);
12250:         my %iphost = &get_iphost();
12251:         my (@idns,%seen);
12252:         foreach my $id (@hosts) {
12253:             my $dom = &host_domain($id);
12254:             my $prim_id = &domain($dom,'primary');
12255:             my $prim_ip = &get_host_ip($prim_id);
12256:             next if ($seen{$prim_ip});
12257:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
12258:                 foreach my $id (@{$iphost{$prim_ip}}) {
12259:                     my $intdom = &internet_dom($id);
12260:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
12261:                         push(@idns,$intdom);
12262:                     }
12263:                 }
12264:             }
12265:             $seen{$prim_ip} = 1;
12266:         }
12267:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
12268:     }
12269: 
12270: }
12271: 
12272: sub all_loncaparevs {
12273:     return qw(1.1 1.2 1.3 2.0 2.1 2.2 2.3 2.4 2.5 2.6 2.7 2.8 2.9 2.10 2.11);
12274: }
12275: 
12276: # ------------------------------------------------------- Read loncaparev table
12277: {
12278:     sub load_loncaparevs {
12279:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
12280:             if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
12281:                 while (my $configline=<$config>) {
12282:                     chomp($configline);
12283:                     my ($hostid,$loncaparev)=split(/:/,$configline);
12284:                     $loncaparevs{$hostid}=$loncaparev;
12285:                 }
12286:                 close($config);
12287:             }
12288:         }
12289:     }
12290: }
12291: 
12292: # ----------------------------------------------------- Read serverhostID table
12293: {
12294:     sub load_serverhomeIDs {
12295:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
12296:             if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
12297:                 while (my $configline=<$config>) {
12298:                     chomp($configline);
12299:                     my ($name,$id)=split(/:/,$configline);
12300:                     $serverhomeIDs{$name}=$id;
12301:                 }
12302:                 close($config);
12303:             }
12304:         }
12305:     }
12306: }
12307: 
12308: 
12309: BEGIN {
12310: 
12311: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
12312:     unless ($readit) {
12313: {
12314:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
12315:     %perlvar = (%perlvar,%{$configvars});
12316: }
12317: 
12318: 
12319: # ------------------------------------------------------ Read spare server file
12320: {
12321:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
12322: 
12323:     while (my $configline=<$config>) {
12324:        chomp($configline);
12325:        if ($configline) {
12326: 	   my ($host,$type) = split(':',$configline,2);
12327: 	   if (!defined($type) || $type eq '') { $type = 'default' };
12328: 	   push(@{ $spareid{$type} }, $host);
12329:        }
12330:     }
12331:     close($config);
12332: }
12333: # ------------------------------------------------------------ Read permissions
12334: {
12335:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
12336: 
12337:     while (my $configline=<$config>) {
12338: 	chomp($configline);
12339: 	if ($configline) {
12340: 	    my ($role,$perm)=split(/ /,$configline);
12341: 	    if ($perm ne '') { $pr{$role}=$perm; }
12342: 	}
12343:     }
12344:     close($config);
12345: }
12346: 
12347: # -------------------------------------------- Read plain texts for permissions
12348: {
12349:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
12350: 
12351:     while (my $configline=<$config>) {
12352: 	chomp($configline);
12353: 	if ($configline) {
12354: 	    my ($short,@plain)=split(/:/,$configline);
12355:             %{$prp{$short}} = ();
12356: 	    if (@plain > 0) {
12357:                 $prp{$short}{'std'} = $plain[0];
12358:                 for (my $i=1; $i<@plain; $i++) {
12359:                     $prp{$short}{'alt'.$i} = $plain[$i];  
12360:                 }
12361:             }
12362: 	}
12363:     }
12364:     close($config);
12365: }
12366: 
12367: # ---------------------------------------------------------- Read package table
12368: {
12369:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
12370: 
12371:     while (my $configline=<$config>) {
12372: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
12373: 	chomp($configline);
12374: 	my ($short,$plain)=split(/:/,$configline);
12375: 	my ($pack,$name)=split(/\&/,$short);
12376: 	if ($plain ne '') {
12377: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
12378: 	    $packagetab{$short}=$plain; 
12379: 	}
12380:     }
12381:     close($config);
12382: }
12383: 
12384: # --------------------------------------------------------- Read loncaparev table
12385: 
12386: &load_loncaparevs();
12387: 
12388: # ------------------------------------------------------- Read serverhostID table
12389: 
12390: &load_serverhomeIDs();
12391: 
12392: # ---------------------------------------------------------- Read releaseslist XML
12393: {
12394:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
12395:     if (-e $file) {
12396:         my $parser = HTML::LCParser->new($file);
12397:         while (my $token = $parser->get_token()) {
12398:             if ($token->[0] eq 'S') {
12399:                 my $item = $token->[1];
12400:                 my $name = $token->[2]{'name'};
12401:                 my $value = $token->[2]{'value'};
12402:                 if ($item ne '' && $name ne '' && $value ne '') {
12403:                     my $release = $parser->get_text();
12404:                     $release =~ s/(^\s*|\s*$ )//gx;
12405:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
12406:                 }
12407:             }
12408:         }
12409:     }
12410: }
12411: 
12412: # ---------------------------------------------------------- Read managers table
12413: {
12414:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
12415:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
12416:             while (my $configline=<$config>) {
12417:                 chomp($configline);
12418:                 next if ($configline =~ /^\#/);
12419:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
12420:                     $managerstab{$configline} = 1;
12421:                 }
12422:             }
12423:             close($config);
12424:         }
12425:     }
12426: }
12427: 
12428: # ------------- set up temporary directory
12429: {
12430:     $tmpdir = LONCAPA::tempdir();
12431: 
12432: }
12433: 
12434: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
12435: 				'compress_threshold'=> 20_000,
12436:  			        });
12437: 
12438: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
12439: $dumpcount=0;
12440: $locknum=0;
12441: 
12442: &logtouch();
12443: &logthis('<font color="yellow">INFO: Read configuration</font>');
12444: $readit=1;
12445:     {
12446: 	use integer;
12447: 	my $test=(2**32)+1;
12448: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
12449: 	&logthis(" Detected 64bit platform ($_64bit)");
12450:     }
12451: }
12452: }
12453: 
12454: 1;
12455: __END__
12456: 
12457: =pod
12458: 
12459: =head1 NAME
12460: 
12461: Apache::lonnet - Subroutines to ask questions about things in the network.
12462: 
12463: =head1 SYNOPSIS
12464: 
12465: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
12466: 
12467:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
12468: 
12469: Common parameters:
12470: 
12471: =over 4
12472: 
12473: =item *
12474: 
12475: $uname : an internal username (if $cname expecting a course Id specifically)
12476: 
12477: =item *
12478: 
12479: $udom : a domain (if $cdom expecting a course's domain specifically)
12480: 
12481: =item *
12482: 
12483: $symb : a resource instance identifier
12484: 
12485: =item *
12486: 
12487: $namespace : the name of a .db file that contains the data needed or
12488: being set.
12489: 
12490: =back
12491: 
12492: =head1 OVERVIEW
12493: 
12494: lonnet provides subroutines which interact with the
12495: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
12496: about classes, users, and resources.
12497: 
12498: For many of these objects you can also use this to store data about
12499: them or modify them in various ways.
12500: 
12501: =head2 Symbs
12502: 
12503: To identify a specific instance of a resource, LON-CAPA uses symbols
12504: or "symbs"X<symb>. These identifiers are built from the URL of the
12505: map, the resource number of the resource in the map, and the URL of
12506: the resource itself. The latter is somewhat redundant, but might help
12507: if maps change.
12508: 
12509: An example is
12510: 
12511:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
12512: 
12513: The respective map entry is
12514: 
12515:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
12516:   title="Problem 2">
12517:  </resource>
12518: 
12519: Symbs are used by the random number generator, as well as to store and
12520: restore data specific to a certain instance of for example a problem.
12521: 
12522: =head2 Storing And Retrieving Data
12523: 
12524: X<store()>X<cstore()>X<restore()>Three of the most important functions
12525: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
12526: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
12527: is is the non-critical message twin of cstore. These functions are for
12528: handlers to store a perl hash to a user's permanent data space in an
12529: easy manner, and to retrieve it again on another call. It is expected
12530: that a handler would use this once at the beginning to retrieve data,
12531: and then again once at the end to send only the new data back.
12532: 
12533: The data is stored in the user's data directory on the user's
12534: homeserver under the ID of the course.
12535: 
12536: The hash that is returned by restore will have all of the previous
12537: value for all of the elements of the hash.
12538: 
12539: Example:
12540: 
12541:  #creating a hash
12542:  my %hash;
12543:  $hash{'foo'}='bar';
12544: 
12545:  #storing it
12546:  &Apache::lonnet::cstore(\%hash);
12547: 
12548:  #changing a value
12549:  $hash{'foo'}='notbar';
12550: 
12551:  #adding a new value
12552:  $hash{'bar'}='foo';
12553:  &Apache::lonnet::cstore(\%hash);
12554: 
12555:  #retrieving the hash
12556:  my %history=&Apache::lonnet::restore();
12557: 
12558:  #print the hash
12559:  foreach my $key (sort(keys(%history))) {
12560:    print("\%history{$key} = $history{$key}");
12561:  }
12562: 
12563: Will print out:
12564: 
12565:  %history{1:foo} = bar
12566:  %history{1:keys} = foo:timestamp
12567:  %history{1:timestamp} = 990455579
12568:  %history{2:bar} = foo
12569:  %history{2:foo} = notbar
12570:  %history{2:keys} = foo:bar:timestamp
12571:  %history{2:timestamp} = 990455580
12572:  %history{bar} = foo
12573:  %history{foo} = notbar
12574:  %history{timestamp} = 990455580
12575:  %history{version} = 2
12576: 
12577: Note that the special hash entries C<keys>, C<version> and
12578: C<timestamp> were added to the hash. C<version> will be equal to the
12579: total number of versions of the data that have been stored. The
12580: C<timestamp> attribute will be the UNIX time the hash was
12581: stored. C<keys> is available in every historical section to list which
12582: keys were added or changed at a specific historical revision of a
12583: hash.
12584: 
12585: B<Warning>: do not store the hash that restore returns directly. This
12586: will cause a mess since it will restore the historical keys as if the
12587: were new keys. I.E. 1:foo will become 1:1:foo etc.
12588: 
12589: Calling convention:
12590: 
12591:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
12592:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname);
12593: 
12594: For more detailed information, see lonnet specific documentation.
12595: 
12596: =head1 RETURN MESSAGES
12597: 
12598: =over 4
12599: 
12600: =item * B<con_lost>: unable to contact remote host
12601: 
12602: =item * B<con_delayed>: unable to contact remote host, message will be delivered
12603: when the connection is brought back up
12604: 
12605: =item * B<con_failed>: unable to contact remote host and unable to save message
12606: for later delivery
12607: 
12608: =item * B<error:>: an error a occurred, a description of the error follows the :
12609: 
12610: =item * B<no_such_host>: unable to fund a host associated with the user/domain
12611: that was requested
12612: 
12613: =back
12614: 
12615: =head1 PUBLIC SUBROUTINES
12616: 
12617: =head2 Session Environment Functions
12618: 
12619: =over 4
12620: 
12621: =item * 
12622: X<appenv()>
12623: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
12624: the user envirnoment file, and will be restored for each access this
12625: user makes during this session, also modifies the %env for the current
12626: process. Optional rolesarrayref - if defined contains a reference to an array
12627: of roles which are exempt from the restriction on modifying user.role entries 
12628: in the user's environment.db and in %env.    
12629: 
12630: =item *
12631: X<delenv()>
12632: B<delenv($delthis,$regexp)>: removes all items from the session
12633: environment file that begin with $delthis. If the 
12634: optional second arg - $regexp - is true, $delthis is treated as a 
12635: regular expression, otherwise \Q$delthis\E is used. 
12636: The values are also deleted from the current processes %env.
12637: 
12638: =item * get_env_multiple($name) 
12639: 
12640: gets $name from the %env hash, it seemlessly handles the cases where multiple
12641: values may be defined and end up as an array ref.
12642: 
12643: returns an array of values
12644: 
12645: =back
12646: 
12647: =head2 User Information
12648: 
12649: =over 4
12650: 
12651: =item *
12652: X<queryauthenticate()>
12653: B<queryauthenticate($uname,$udom)>: try to determine user's current 
12654: authentication scheme
12655: 
12656: =item *
12657: X<authenticate()>
12658: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
12659: authenticate user from domain's lib servers (first use the current
12660: one). C<$upass> should be the users password.
12661: $checkdefauth is optional (value is 1 if a check should be made to
12662:    authenticate user using default authentication method, and allow
12663:    account creation if username does not have account in the domain).
12664: $clientcancheckhost is optional (value is 1 if checking whether the
12665:    server can host will occur on the client side in lonauth.pm).   
12666: 
12667: =item *
12668: X<homeserver()>
12669: B<homeserver($uname,$udom)>: find the server which has
12670: the user's directory and files (there must be only one), this caches
12671: the answer, and also caches if there is a borken connection.
12672: 
12673: =item *
12674: X<idget()>
12675: B<idget($udom,@ids)>: find the usernames behind a list of IDs
12676: (IDs are a unique resource in a domain, there must be only 1 ID per
12677: username, and only 1 username per ID in a specific domain) (returns
12678: hash: id=>name,id=>name)
12679: 
12680: =item *
12681: X<idrget()>
12682: B<idrget($udom,@unames)>: find the IDs behind a list of
12683: usernames (returns hash: name=>id,name=>id)
12684: 
12685: =item *
12686: X<idput()>
12687: B<idput($udom,%ids)>: store away a list of names and associated IDs
12688: 
12689: =item *
12690: X<rolesinit()>
12691: B<rolesinit($udom,$username)>: get user privileges.
12692: returns user role, first access and timer interval hashes
12693: 
12694: =item *
12695: X<privileged()>
12696: B<privileged($username,$domain)>: returns a true if user has a
12697: privileged and active role (i.e. su or dc), false otherwise.
12698: 
12699: =item *
12700: X<getsection()>
12701: B<getsection($udom,$uname,$cname)>: finds the section of student in the
12702: course $cname, return section name/number or '' for "not in course"
12703: and '-1' for "no section"
12704: 
12705: =item *
12706: X<userenvironment()>
12707: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
12708: passed in @what from the requested user's environment, returns a hash
12709: 
12710: =item * 
12711: X<userlog_query()>
12712: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
12713: activity.log file. %filters defines filters applied when parsing the
12714: log file. These can be start or end timestamps, or the type of action
12715: - log to look for Login or Logout events, check for Checkin or
12716: Checkout, role for role selection. The response is in the form
12717: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
12718: escaped strings of the action recorded in the activity.log file.
12719: 
12720: =back
12721: 
12722: =head2 User Roles
12723: 
12724: =over 4
12725: 
12726: =item *
12727: 
12728: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
12729:  F: full access
12730:  U,I,K: authentication modes (cxx only)
12731:  '': forbidden
12732:  1: user needs to choose course
12733:  2: browse allowed
12734:  A: passphrase authentication needed
12735: 
12736: =item *
12737: 
12738: constructaccess($url,$setpriv) : check for access to construction space URL
12739: 
12740: See if the owner domain and name in the URL match those in the
12741: expected environment.  If so, return three element list
12742: ($ownername,$ownerdomain,$ownerhome).
12743: 
12744: Otherwise return the null string.
12745: 
12746: If second argument 'setpriv' is true, it assigns the privileges,
12747: and returns the same three element list, unless the owner has
12748: blocked "ad hoc" Domain Coordinator access to the Author Space,
12749: in which case the null string is returned.
12750: 
12751: =item *
12752: 
12753: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
12754: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
12755: and course level
12756: 
12757: =item *
12758: 
12759: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
12760: (rolesplain.tab); plain text explanation of a user role term.
12761: $type is Course (default) or Community.
12762: If $forcedefault evaluates to true, text returned will be default 
12763: text for $type. Otherwise, if this is a course, the text returned 
12764: will be a custom name for the role (if defined in the course's 
12765: environment).  If no custom name is defined the default is returned.
12766:    
12767: =item *
12768: 
12769: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
12770: All arguments are optional. Returns a hash of a roles, either for
12771: co-author/assistant author roles for a user's Construction Space
12772: (default), or if $context is 'userroles', roles for the user himself,
12773: In the hash, keys are set to colon-separated $uname,$udom,$role, and
12774: (optionally) if $withsec is true, a fourth colon-separated item - $section.
12775: For each key, value is set to colon-separated start and end times for
12776: the role.  If no username and domain are specified, will default to
12777: current user/domain. Types, roles, and roledoms are references to arrays
12778: of role statuses (active, future or previous), roles 
12779: (e.g., cc,in, st etc.) and domains of the roles which can be used
12780: to restrict the list of roles reported. If no array ref is 
12781: provided for types, will default to return only active roles.
12782: 
12783: =item *
12784: 
12785: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
12786: user: $uname:$udom has a role in the course: $cdom_$cnum.
12787: 
12788: Additional optional arguments are: $type (if role checking is to be restricted
12789: to certain user status types -- previous (expired roles), active (currently
12790: available roles) or future (roles available in the future), and
12791: $hideprivileged -- if true will not report course roles for users who
12792: have active Domain Coordinator role in course's domain or in additional
12793: domains (specified in 'Domains to check for privileged users' in course
12794: environment -- set via:  Course Settings -> Classlists and staff listing).
12795: 
12796: =item *
12797: 
12798: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
12799: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
12800: $possdomains and $possroles are optional array refs -- to domains to check and
12801: roles to check.  If $possdomains is not specified, a dump will be done of the
12802: users' roles.db to check for a dc or su role in any domain. This can be
12803: time consuming if &privileged is called repeatedly (e.g., when displaying a
12804: classlist), so in such cases, supplying a $possdomains array is preferred, as
12805: this then allows &privileged_by_domain() to be used, which caches the identity
12806: of privileged users, eliminating the need for repeated calls to &dump().
12807: 
12808: =item *
12809: 
12810: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
12811: where the outer hash keys are domains specified in the $possdomains array ref,
12812: next inner hash keys are privileged roles specified in the $roles array ref,
12813: and the innermost hash contains key = value pairs for username:domain = end:start
12814: for active or future "privileged" users with that role in that domain. To avoid
12815: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
12816: innerhash are cached using priv_$role and $dom as the identifiers.
12817: 
12818: =back
12819: 
12820: =head2 User Modification
12821: 
12822: =over 4
12823: 
12824: =item *
12825: 
12826: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
12827: user for the level given by URL.  Optional start and end dates (leave empty
12828: string or zero for "no date")
12829: 
12830: =item *
12831: 
12832: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
12833: change a users, password, possible return values are: ok,
12834: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
12835: refused
12836: 
12837: =item *
12838: 
12839: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
12840: 
12841: =item *
12842: 
12843: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
12844:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
12845: 
12846: will update user information (firstname,middlename,lastname,generation,
12847: permanentemail), and if forceid is true, student/employee ID also.
12848: A user's institutional affiliation(s) can also be updated.
12849: User information fields will not be overwritten with empty entries 
12850: unless the field is included in the $candelete array reference.
12851: This array is included when a single user is modified via "Manage Users",
12852: or when Autoupdate.pl is run by cron in a domain.
12853: 
12854: =item *
12855: 
12856: modifystudent
12857: 
12858: modify a student's enrollment and identification information.
12859: The course id is resolved based on the current user's environment.  
12860: This means the invoking user must be a course coordinator or otherwise
12861: associated with a course.
12862: 
12863: This call is essentially a wrapper for lonnet::modifyuser and
12864: lonnet::modify_student_enrollment
12865: 
12866: Inputs: 
12867: 
12868: =over 4
12869: 
12870: =item B<$udom> Student's loncapa domain
12871: 
12872: =item B<$uname> Student's loncapa login name
12873: 
12874: =item B<$uid> Student/Employee ID
12875: 
12876: =item B<$umode> Student's authentication mode
12877: 
12878: =item B<$upass> Student's password
12879: 
12880: =item B<$first> Student's first name
12881: 
12882: =item B<$middle> Student's middle name
12883: 
12884: =item B<$last> Student's last name
12885: 
12886: =item B<$gene> Student's generation
12887: 
12888: =item B<$usec> Student's section in course
12889: 
12890: =item B<$end> Unix time of the roles expiration
12891: 
12892: =item B<$start> Unix time of the roles start date
12893: 
12894: =item B<$forceid> If defined, allow $uid to be changed
12895: 
12896: =item B<$desiredhome> server to use as home server for student
12897: 
12898: =item B<$email> Student's permanent e-mail address
12899: 
12900: =item B<$type> Type of enrollment (auto or manual)
12901: 
12902: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
12903: 
12904: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
12905: 
12906: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
12907: 
12908: =item B<$context> role change context (shown in User Management Logs display in a course)
12909: 
12910: =item B<$inststatus> institutional status of user - : separated string of escaped status types
12911: 
12912: =item B<$credits> Number of credits student will earn from this class - only needs to be supplied if value needs to be different from default credits for class.
12913: 
12914: =back
12915: 
12916: =item *
12917: 
12918: modify_student_enrollment
12919: 
12920: Change a student's enrollment status in a class.  The environment variable
12921: 'role.request.course' must be defined for this function to proceed.
12922: 
12923: Inputs:
12924: 
12925: =over 4
12926: 
12927: =item $udom, student's domain
12928: 
12929: =item $uname, student's name
12930: 
12931: =item $uid, student's user id
12932: 
12933: =item $first, student's first name
12934: 
12935: =item $middle
12936: 
12937: =item $last
12938: 
12939: =item $gene
12940: 
12941: =item $usec
12942: 
12943: =item $end
12944: 
12945: =item $start
12946: 
12947: =item $type
12948: 
12949: =item $locktype
12950: 
12951: =item $cid
12952: 
12953: =item $selfenroll
12954: 
12955: =item $context
12956: 
12957: =item $credits, number of credits student will earn from this class
12958: 
12959: =back
12960: 
12961: 
12962: =item *
12963: 
12964: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
12965: custom role; give a custom role to a user for the level given by URL.  Specify
12966: name and domain of role author, and role name
12967: 
12968: =item *
12969: 
12970: revokerole($udom,$uname,$url,$role) : revoke a role for url
12971: 
12972: =item *
12973: 
12974: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
12975: 
12976: =back
12977: 
12978: =head2 Course Infomation
12979: 
12980: =over 4
12981: 
12982: =item *
12983: 
12984: coursedescription($courseid,$options) : returns a hash of information about the
12985: specified course id, including all environment settings for the
12986: course, the description of the course will be in the hash under the
12987: key 'description'
12988: 
12989: $options is an optional parameter that if supplied is a hash reference that controls
12990: what how this function works.  It has the following key/values:
12991: 
12992: =over 4
12993: 
12994: =item freshen_cache
12995: 
12996: If defined, and the environment cache for the course is valid, it is 
12997: returned in the returned hash.
12998: 
12999: =item one_time
13000: 
13001: If defined, the last cache time is set to _now_
13002: 
13003: =item user
13004: 
13005: If defined, the supplied username is used instead of the current user.
13006: 
13007: 
13008: =back
13009: 
13010: =item *
13011: 
13012: resdata($name,$domain,$type,@which) : request for current parameter
13013: setting for a specific $type, where $type is either 'course' or 'user',
13014: @what should be a list of parameters to ask about. This routine caches
13015: answers for 10 minutes.
13016: 
13017: =item *
13018: 
13019: get_courseresdata($courseid, $domain) : dump the entire course resource
13020: data base, returning a hash that is keyed by the resource name and has
13021: values that are the resource value.  I believe that the timestamps and
13022: versions are also returned.
13023: 
13024: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
13025: supplemental content area. This routine caches the number of files for
13026: 10 minutes.
13027: 
13028: =back
13029: 
13030: =head2 Course Modification
13031: 
13032: =over 4
13033: 
13034: =item *
13035: 
13036: writecoursepref($courseid,%prefs) : write preferences (environment
13037: database) for a course
13038: 
13039: =item *
13040: 
13041: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
13042: 
13043: =item *
13044: 
13045: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
13046: 
13047: =item *
13048: 
13049: is_course($courseid), is_course($cdom, $cnum)
13050: 
13051: Accepts either a combined $courseid (in the form of domain_courseid) or the
13052: two component version $cdom, $cnum. It checks if the specified course exists.
13053: 
13054: Returns:
13055:     undef if the course doesn't exist, otherwise
13056:     in scalar context the combined courseid.
13057:     in list context the two components of the course identifier, domain and 
13058:     courseid.    
13059: 
13060: =back
13061: 
13062: =head2 Resource Subroutines
13063: 
13064: =over 4
13065: 
13066: =item *
13067: 
13068: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
13069: 
13070: =item *
13071: 
13072: repcopy($filename) : subscribes to the requested file, and attempts to
13073: replicate from the owning library server, Might return
13074: 'unavailable', 'not_found', 'forbidden', 'ok', or
13075: 'bad_request', also attempts to grab the metadata for the
13076: resource. Expects the local filesystem pathname
13077: (/home/httpd/html/res/....)
13078: 
13079: =back
13080: 
13081: =head2 Resource Information
13082: 
13083: =over 4
13084: 
13085: =item *
13086: 
13087: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
13088: and returns the value of a variety of different possible values,
13089: $varname should be a request string, and the other parameters can be
13090: used to specify who and what one is asking about. Ordinarily, $cid 
13091: does not need to be specified, as it is retrived from 
13092: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
13093: within lonuserstate::loadmap() when initializing a course, before
13094: $env{'request.course.id'} has been set, so it needs to be provided
13095: in that one case.
13096: 
13097: Possible values for $varname are environment.lastname (or other item
13098: from the envirnment hash), user.name (or someother aspect about the
13099: user), resource.0.maxtries (or some other part and parameter of a
13100: resource)
13101: 
13102: =item *
13103: 
13104: directcondval($number) : get current value of a condition; reads from a state
13105: string
13106: 
13107: =item *
13108: 
13109: condval($condidx) : value of condition index based on state
13110: 
13111: =item *
13112: 
13113: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
13114: resource's metadata, $what should be either a specific key, or either
13115: 'keys' (to get a list of possible keys) or 'packages' to get a list of
13116: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
13117: 
13118: this function automatically caches all requests
13119: 
13120: =item *
13121: 
13122: metadata_query($query,$custom,$customshow) : make a metadata query against the
13123: network of library servers; returns file handle of where SQL and regex results
13124: will be stored for query
13125: 
13126: =item *
13127: 
13128: symbread($filename) : return symbolic list entry (filename argument optional);
13129: returns the data handle
13130: 
13131: =item *
13132: 
13133: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
13134: and is a possible symb for the URL in $thisfn, and if is an encrypted
13135: resource that the user accessed using /enc/ returns a 1 on success, 0
13136: on failure, user must be in a course, as it assumes the existence of
13137: the course initial hash, and uses $env('request.course.id'}.  The third
13138: arg is an optional reference to a scalar.  If this arg is passed in the
13139: call to symbverify, it will be set to 1 if the symb has been set to be 
13140: encrypted; otherwise it will be null.
13141: 
13142: =item *
13143: 
13144: symbclean($symb) : removes versions numbers from a symb, returns the
13145: cleaned symb
13146: 
13147: =item *
13148: 
13149: is_on_map($uri) : checks if the $uri is somewhere on the current
13150: course map, user must be in a course for it to work.
13151: 
13152: =item *
13153: 
13154: numval($salt) : return random seed value (addend for rndseed)
13155: 
13156: =item *
13157: 
13158: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
13159: a random seed, all arguments are optional, if they aren't sent it uses the
13160: environment to derive them. Note: if symb isn't sent and it can't get one
13161: from &symbread it will use the current time as its return value
13162: 
13163: =item *
13164: 
13165: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
13166: unfakeable, receipt
13167: 
13168: =item *
13169: 
13170: receipt() : API to ireceipt working off of env values; given out to users
13171: 
13172: =item *
13173: 
13174: countacc($url) : count the number of accesses to a given URL
13175: 
13176: =item *
13177: 
13178: 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
13179: 
13180: =item *
13181: 
13182: 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)
13183: 
13184: =item *
13185: 
13186: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
13187: 
13188: =item *
13189: 
13190: devalidate($symb) : devalidate temporary spreadsheet calculations,
13191: forcing spreadsheet to reevaluate the resource scores next time.
13192: 
13193: =item *
13194: 
13195: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
13196: when viewing in course context.
13197: 
13198:  input: six args -- filename (decluttered), course number, course domain,
13199:                     url, symb (if registered) and group (if this is a
13200:                     group item -- e.g., bulletin board, group page etc.).
13201: 
13202:  output: array of five scalars --
13203:          $cfile -- url for file editing if editable on current server
13204:          $home -- homeserver of resource (i.e., for author if published,
13205:                                           or course if uploaded.).
13206:          $switchserver --  1 if server switch will be needed.
13207:          $forceedit -- 1 if icon/link should be to go to edit mode
13208:          $forceview -- 1 if icon/link should be to go to view mode
13209: 
13210: =item *
13211: 
13212: is_course_upload($file,$cnum,$cdom)
13213: 
13214: Used in course context to determine if current file was uploaded to
13215: the course (i.e., would be found in /userfiles/docs on the course's
13216: homeserver.
13217: 
13218:   input: 3 args -- filename (decluttered), course number and course domain.
13219:   output: boolean -- 1 if file was uploaded.
13220: 
13221: =back
13222: 
13223: =head2 Storing/Retreiving Data
13224: 
13225: =over 4
13226: 
13227: =item *
13228: 
13229: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
13230: for this url; hashref needs to be given and should be a \%hashname; the
13231: remaining args aren't required and if they aren't passed or are '' they will
13232: be derived from the env
13233: 
13234: =item *
13235: 
13236: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
13237: uses critical subroutine
13238: 
13239: =item *
13240: 
13241: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
13242: all args are optional
13243: 
13244: =item *
13245: 
13246: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
13247: dumps the complete (or key matching regexp) namespace into a hash
13248: ($udom, $uname, $regexp, $range are optional) for a namespace that is
13249: normally &store()ed into
13250: 
13251: $range should be either an integer '100' (give me the first 100
13252:                                            matching records)
13253:               or be  two integers sperated by a - with no spaces
13254:                  '30-50' (give me the 30th through the 50th matching
13255:                           records)
13256: 
13257: 
13258: =item *
13259: 
13260: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
13261: replaces a &store() version of data with a replacement set of data
13262: for a particular resource in a namespace passed in the $storehash hash 
13263: reference
13264: 
13265: =item *
13266: 
13267: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
13268: works very similar to store/cstore, but all data is stored in a
13269: temporary location and can be reset using tmpreset, $storehash should
13270: be a hash reference, returns nothing on success
13271: 
13272: =item *
13273: 
13274: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
13275: similar to restore, but all data is stored in a temporary location and
13276: can be reset using tmpreset. Returns a hash of values on success,
13277: error string otherwise.
13278: 
13279: =item *
13280: 
13281: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
13282: deltes all keys for $symb form the temporary storage hash.
13283: 
13284: =item *
13285: 
13286: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13287: reference filled in from namesp ($udom and $uname are optional)
13288: 
13289: =item *
13290: 
13291: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
13292: namesp ($udom and $uname are optional)
13293: 
13294: =item *
13295: 
13296: dump($namespace,$udom,$uname,$regexp,$range) : 
13297: dumps the complete (or key matching regexp) namespace into a hash
13298: ($udom, $uname, $regexp, $range are optional)
13299: 
13300: $range should be either an integer '100' (give me the first 100
13301:                                            matching records)
13302:               or be  two integers sperated by a - with no spaces
13303:                  '30-50' (give me the 30th through the 50th matching
13304:                           records)
13305: =item *
13306: 
13307: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
13308: $store can be a scalar, an array reference, or if the amount to be 
13309: incremented is > 1, a hash reference.
13310: 
13311: ($udom and $uname are optional)
13312: 
13313: =item *
13314: 
13315: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
13316: ($udom and $uname are optional)
13317: 
13318: =item *
13319: 
13320: cput($namespace,$storehash,$udom,$uname) : critical put
13321: ($udom and $uname are optional)
13322: 
13323: =item *
13324: 
13325: newput($namespace,$storehash,$udom,$uname) :
13326: 
13327: Attempts to store the items in the $storehash, but only if they don't
13328: currently exist, if this succeeds you can be certain that you have 
13329: successfully created a new key value pair in the $namespace db.
13330: 
13331: 
13332: Args:
13333:  $namespace: name of database to store values to
13334:  $storehash: hashref to store to the db
13335:  $udom: (optional) domain of user containing the db
13336:  $uname: (optional) name of user caontaining the db
13337: 
13338: Returns:
13339:  'ok' -> succeeded in storing all keys of $storehash
13340:  'key_exists: <key>' -> failed to anything out of $storehash, as at
13341:                         least <key> already existed in the db (other
13342:                         requested keys may also already exist)
13343:  'error: <msg>' -> unable to tie the DB or other error occurred
13344:  'con_lost' -> unable to contact request server
13345:  'refused' -> action was not allowed by remote machine
13346: 
13347: 
13348: =item *
13349: 
13350: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13351: reference filled in from namesp (encrypts the return communication)
13352: ($udom and $uname are optional)
13353: 
13354: =item *
13355: 
13356: log($udom,$name,$home,$message) : write to permanent log for user; use
13357: critical subroutine
13358: 
13359: =item *
13360: 
13361: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
13362: array reference filled in from namespace found in domain level on either
13363: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
13364: 
13365: =item *
13366: 
13367: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
13368: domain level either on specified domain server ($uhome) or primary domain 
13369: server ($udom and $uhome are optional)
13370: 
13371: =item * 
13372: 
13373: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
13374: for: authentication, language, quotas, timezone, date locale, and portal URL in
13375: the target domain.
13376: 
13377: May also include additional key => value pairs for the following groups:
13378: 
13379: =over
13380: 
13381: =item
13382: disk quotas (MB allocated by default to portfolios and authoring spaces).
13383: 
13384: =over
13385: 
13386: =item defaultquota, authorquota
13387: 
13388: =back
13389: 
13390: =item
13391: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
13392: portfolio for users).
13393: 
13394: =over
13395: 
13396: =item
13397: aboutme, blog, webdav, portfolio
13398: 
13399: =back
13400: 
13401: =item
13402: requestcourses: ability to request courses, and how requests are processed.
13403: 
13404: =over
13405: 
13406: =item
13407: official, unofficial, community, textbook
13408: 
13409: =back
13410: 
13411: =item
13412: inststatus: types of institutional affiliation, and order in which they are displayed.
13413: 
13414: =over
13415: 
13416: =item
13417: inststatustypes, inststatusorder
13418: 
13419: =back
13420: 
13421: =item
13422: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
13423: for course's uploaded content.
13424: 
13425: =over
13426: 
13427: =item
13428: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, communityquota, textbookquota
13429: 
13430: =back
13431: 
13432: =item
13433: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
13434: on your servers.
13435: 
13436: =over
13437: 
13438: =item
13439: remotesessions, hostedsessions
13440: 
13441: =back
13442: 
13443: =back
13444: 
13445: In cases where a domain coordinator has never used the "Set Domain Configuration"
13446: utility to create a configuration.db file on a domain's primary library server
13447: only the following domain defaults: auth_def, auth_arg_def, lang_def
13448: -- corresponding values are authentication type (internal, krb4, krb5,
13449: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
13450: will be available. Values are retrieved from cache (if current), unless the
13451: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
13452: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
13453: 
13454: Typical usage:
13455: 
13456: %domdefaults = &get_domain_defaults($target_domain);
13457: 
13458: =back
13459: 
13460: =head2 Network Status Functions
13461: 
13462: =over 4
13463: 
13464: =item *
13465: 
13466: dirlist() : return directory list based on URI (first arg).
13467: 
13468: Inputs: 1 required, 5 optional.
13469: 
13470: =over
13471: 
13472: =item 
13473: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
13474: 
13475: =item
13476: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
13477: 
13478: =item
13479: $username -  username of user/course to be listed. Extracted from $uri if absent. 
13480: 
13481: =item
13482: $getpropath - boolean: 1 if prepend path using &propath(). 
13483: 
13484: =item
13485: $getuserdir - boolean: 1 if prepend path for "userfiles".
13486: 
13487: =item 
13488: $alternateRoot - path to prepend in place of path from $uri.
13489: 
13490: =back
13491: 
13492: Returns: Array of up to two items.
13493: 
13494: =over
13495: 
13496: a reference to an array of files/subdirectories
13497: 
13498: =over
13499: 
13500: Each element in the array of files/subdirectories is a & separated list of
13501: item name and the result of running stat on the item.  If dirlist was requested
13502: for a file instead of a directory, the item name will be ''. For a directory 
13503: listing, if the item is a metadata file, the element will end &N&M 
13504: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
13505: default copyright set (1).  
13506: 
13507: =back
13508: 
13509: a scalar containing error condition (if encountered).
13510: 
13511: =over
13512: 
13513: =item 
13514: no_host (no homeserver identified for $username:$domain).
13515: 
13516: =item 
13517: no_such_host (server contacted for listing not identified as valid host).
13518: 
13519: =item 
13520: con_lost (connection to remote server failed).
13521: 
13522: =item 
13523: refused (invalid $username:$domain received on lond side).
13524: 
13525: =item 
13526: no_such_dir (directory at specified path on lond side does not exist). 
13527: 
13528: =item 
13529: empty (directory at specified path on lond side is empty).
13530: 
13531: =over
13532: 
13533: This is currently not encountered because the &ls3, &ls2, 
13534: &ls (_handler) routines on the lond side do not filter out
13535: . and .. from a directory listing. 
13536: 
13537: =back
13538: 
13539: =back
13540: 
13541: =back
13542: 
13543: =item *
13544: 
13545: spareserver() : find server with least workload from spare.tab
13546: 
13547: 
13548: =item *
13549: 
13550: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
13551: if there is no corresponding loncapa host.
13552: 
13553: =back
13554: 
13555: 
13556: =head2 Apache Request
13557: 
13558: =over 4
13559: 
13560: =item *
13561: 
13562: ssi($url,%hash) : server side include, does a complete request cycle on url to
13563: localhost, posts hash
13564: 
13565: =back
13566: 
13567: =head2 Data to String to Data
13568: 
13569: =over 4
13570: 
13571: =item *
13572: 
13573: hash2str(%hash) : convert a hash into a string complete with escaping and '='
13574: and '&' separators, supports elements that are arrayrefs and hashrefs
13575: 
13576: =item *
13577: 
13578: hashref2str($hashref) : convert a hashref into a string complete with
13579: escaping and '=' and '&' separators, supports elements that are
13580: arrayrefs and hashrefs
13581: 
13582: =item *
13583: 
13584: arrayref2str($arrayref) : convert an arrayref into a string complete
13585: with escaping and '&' separators, supports elements that are arrayrefs
13586: and hashrefs
13587: 
13588: =item *
13589: 
13590: str2hash($string) : convert string to hash using unescaping and
13591: splitting on '=' and '&', supports elements that are arrayrefs and
13592: hashrefs
13593: 
13594: =item *
13595: 
13596: str2array($string) : convert string to hash using unescaping and
13597: splitting on '&', supports elements that are arrayrefs and hashrefs
13598: 
13599: =back
13600: 
13601: =head2 Logging Routines
13602: 
13603: 
13604: These routines allow one to make log messages in the lonnet.log and
13605: lonnet.perm logfiles.
13606: 
13607: =over 4
13608: 
13609: =item *
13610: 
13611: logtouch() : make sure the logfile, lonnet.log, exists
13612: 
13613: =item *
13614: 
13615: logthis() : append message to the normal lonnet.log file, it gets
13616: preiodically rolled over and deleted.
13617: 
13618: =item *
13619: 
13620: logperm() : append a permanent message to lonnet.perm.log, this log
13621: file never gets deleted by any automated portion of the system, only
13622: messages of critical importance should go in here.
13623: 
13624: 
13625: =back
13626: 
13627: =head2 General File Helper Routines
13628: 
13629: =over 4
13630: 
13631: =item *
13632: 
13633: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
13634: (a) files in /uploaded
13635:   (i) If a local copy of the file exists - 
13636:       compares modification date of local copy with last-modified date for 
13637:       definitive version stored on home server for course. If local copy is 
13638:       stale, requests a new version from the home server and stores it. 
13639:       If the original has been removed from the home server, then local copy 
13640:       is unlinked.
13641:   (ii) If local copy does not exist -
13642:       requests the file from the home server and stores it. 
13643:   
13644:   If $caller is 'uploadrep':  
13645:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
13646:     for request for files originally uploaded via DOCS. 
13647:      - returns 'ok' if fresh local copy now available, -1 otherwise.
13648:   
13649:   Otherwise:
13650:      This indicates a call from the content generation phase of the request.
13651:      -  returns the entire contents of the file or -1.
13652:      
13653: (b) files in /res
13654:    - returns the entire contents of a file or -1; 
13655:    it properly subscribes to and replicates the file if neccessary.
13656: 
13657: 
13658: =item *
13659: 
13660: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
13661:                   reference
13662: 
13663: returns either a stat() list of data about the file or an empty list
13664: if the file doesn't exist or couldn't find out about it (connection
13665: problems or user unknown)
13666: 
13667: =item *
13668: 
13669: filelocation($dir,$file) : returns file system location of a file
13670: based on URI; meant to be "fairly clean" absolute reference, $dir is a
13671: directory that relative $file lookups are to looked in ($dir of /a/dir
13672: and a file of ../bob will become /a/bob)
13673: 
13674: =item *
13675: 
13676: hreflocation($dir,$file) : returns file system location or a URL; same as
13677: filelocation except for hrefs
13678: 
13679: =item *
13680: 
13681: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
13682: 
13683: =back
13684: 
13685: =head2 Usererfile file routines (/uploaded*)
13686: 
13687: =over 4
13688: 
13689: =item *
13690: 
13691: userfileupload(): main rotine for putting a file in a user or course's
13692:                   filespace, arguments are,
13693: 
13694:  formname - required - this is the name of the element in $env where the
13695:            filename, and the contents of the file to create/modifed exist
13696:            the filename is in $env{'form.'.$formname.'.filename'} and the
13697:            contents of the file is located in $env{'form.'.$formname}
13698:  context - if coursedoc, store the file in the course of the active role
13699:              of the current user; 
13700:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
13701:            if 'canceloverwrite': delete file in tmp/overwrites directory
13702:  subdir - required - subdirectory to put the file in under ../userfiles/
13703:          if undefined, it will be placed in "unknown"
13704: 
13705:  (This routine calls clean_filename() to remove any dangerous
13706:  characters from the filename, and then calls finuserfileupload() to
13707:  complete the transaction)
13708: 
13709:  returns either the url of the uploaded file (/uploaded/....) if successful
13710:  and /adm/notfound.html if unsuccessful
13711: 
13712: =item *
13713: 
13714: clean_filename(): routine for cleaing a filename up for storage in
13715:                  userfile space, argument is:
13716: 
13717:  filename - proposed filename
13718: 
13719: returns: the new clean filename
13720: 
13721: =item *
13722: 
13723: finishuserfileupload(): routine that creates and sends the file to
13724: userspace, probably shouldn't be called directly
13725: 
13726:   docuname: username or courseid of destination for the file
13727:   docudom: domain of user/course of destination for the file
13728:   formname: same as for userfileupload()
13729:   fname: filename (including subdirectories) for the file
13730:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
13731:   allfiles: reference to hash used to store objects found by parser
13732:   codebase: reference to hash used for codebases of java objects found by parser
13733:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
13734:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
13735:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
13736:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
13737:   context: if 'overwrite', will move the uploaded file from its temporary location to
13738:             userfiles to facilitate overwriting a previously uploaded file with same name.
13739:   mimetype: reference to scalar to accommodate mime type determined
13740:             from File::MMagic if $parser = parse.
13741: 
13742:  returns either the url of the uploaded file (/uploaded/....) if successful
13743:  and /adm/notfound.html if unsuccessful (or an error message if context 
13744:  was 'overwrite').
13745:  
13746: 
13747: =item *
13748: 
13749: renameuserfile(): renames an existing userfile to a new name
13750: 
13751:   Args:
13752:    docuname: username or courseid of destination for the file
13753:    docudom: domain of user/course of destination for the file
13754:    old: current file name (including any subdirs under userfiles)
13755:    new: desired file name (including any subdirs under userfiles)
13756: 
13757: =item *
13758: 
13759: mkdiruserfile(): creates a directory is a userfiles dir
13760: 
13761:   Args:
13762:    docuname: username or courseid of destination for the file
13763:    docudom: domain of user/course of destination for the file
13764:    dir: dir to create (including any subdirs under userfiles)
13765: 
13766: =item *
13767: 
13768: removeuserfile(): removes a file that exists in userfiles
13769: 
13770:   Args:
13771:    docuname: username or courseid of destination for the file
13772:    docudom: domain of user/course of destination for the file
13773:    fname: filname to delete (including any subdirs under userfiles)
13774: 
13775: =item *
13776: 
13777: removeuploadedurl(): convience function for removeuserfile()
13778: 
13779:   Args:
13780:    url:  a full /uploaded/... url to delete
13781: 
13782: =item * 
13783: 
13784: get_portfile_permissions():
13785:   Args:
13786:     domain: domain of user or course contain the portfolio files
13787:     user: name of user or num of course contain the portfolio files
13788:   Returns:
13789:     hashref of a dump of the proper file_permissions.db
13790:    
13791: 
13792: =item * 
13793: 
13794: get_access_controls():
13795: 
13796: Args:
13797:   current_permissions: the hash ref returned from get_portfile_permissions()
13798:   group: (optional) the group you want the files associated with
13799:   file: (optional) the file you want access info on
13800: 
13801: Returns:
13802:     a hash (keys are file names) of hashes containing
13803:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
13804:         values are XML containing access control settings (see below) 
13805: 
13806: Internal notes:
13807: 
13808:  access controls are stored in file_permissions.db as key=value pairs.
13809:     key -> path to file/file_name\0uniqueID:scope_end_start
13810:         where scope -> public,guest,course,group,domains or users.
13811:               end -> UNIX time for end of access (0 -> no end date)
13812:               start -> UNIX time for start of access
13813: 
13814:     value -> XML description of access control
13815:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
13816:             <start></start>
13817:             <end></end>
13818: 
13819:             <password></password>  for scope type = guest
13820: 
13821:             <domain></domain>     for scope type = course or group
13822:             <number></number>
13823:             <roles id="">
13824:              <role></role>
13825:              <access></access>
13826:              <section></section>
13827:              <group></group>
13828:             </roles>
13829: 
13830:             <dom></dom>         for scope type = domains
13831: 
13832:             <users>             for scope type = users
13833:              <user>
13834:               <uname></uname>
13835:               <udom></udom>
13836:              </user>
13837:             </users>
13838:            </scope> 
13839:               
13840:  Access data is also aggregated for each file in an additional key=value pair:
13841:  key -> path to file/file_name\0accesscontrol 
13842:  value -> reference to hash
13843:           hash contains key = value pairs
13844:           where key = uniqueID:scope_end_start
13845:                 value = UNIX time record was last updated
13846: 
13847:           Used to improve speed of look-ups of access controls for each file.  
13848:  
13849:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
13850: 
13851: =item *
13852: 
13853: modify_access_controls():
13854: 
13855: Modifies access controls for a portfolio file
13856: Args
13857: 1. file name
13858: 2. reference to hash of required changes,
13859: 3. domain
13860: 4. username
13861:   where domain,username are the domain of the portfolio owner 
13862:   (either a user or a course) 
13863: 
13864: Returns:
13865: 1. result of additions or updates ('ok' or 'error', with error message). 
13866: 2. result of deletions ('ok' or 'error', with error message).
13867: 3. reference to hash of any new or updated access controls.
13868: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
13869:    key = integer (inbound ID)
13870:    value = uniqueID
13871: 
13872: =item *
13873: 
13874: get_timebased_id():
13875: 
13876: Attempts to get a unique timestamp-based suffix for use with items added to a
13877: course via the Course Editor (e.g., folders, composite pages,
13878: group bulletin boards).
13879: 
13880: Args: (first three required; six others optional)
13881: 
13882: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
13883:    docssequence, or name of group
13884: 
13885: 2. keyid (alphanumeric): name of temporary locking key in hash,
13886:    e.g., num, boardids
13887: 
13888: 3. namespace: name of gdbm file used to store suffixes already assigned;
13889:    file will be named nohist_namespace.db
13890: 
13891: 4. cdom: domain of course; default is current course domain from %env
13892: 
13893: 5. cnum: course number; default is current course number from %env
13894: 
13895: 6. idtype: set to concat if an additional digit is to be appended to the
13896:    unix timestamp to form the suffix, if the plain timestamp is already
13897:    in use.  Default is to not do this, but simply increment the unix
13898:    timestamp by 1 until a unique key is obtained.
13899: 
13900: 7. who: holder of locking key; defaults to user:domain for user.
13901: 
13902: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
13903:    retrying); default is 3.
13904: 
13905: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
13906: 
13907: Returns:
13908: 
13909: 1. suffix obtained (numeric)
13910: 
13911: 2. result of deleting locking key (ok if deleted, or lock never obtained)
13912: 
13913: 3. error: contains (localized) error message if an error occurred.
13914: 
13915: 
13916: =back
13917: 
13918: =head2 HTTP Helper Routines
13919: 
13920: =over 4
13921: 
13922: =item *
13923: 
13924: escape() : unpack non-word characters into CGI-compatible hex codes
13925: 
13926: =item *
13927: 
13928: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
13929: 
13930: =back
13931: 
13932: =head1 PRIVATE SUBROUTINES
13933: 
13934: =head2 Underlying communication routines (Shouldn't call)
13935: 
13936: =over 4
13937: 
13938: =item *
13939: 
13940: subreply() : tries to pass a message to lonc, returns con_lost if incapable
13941: 
13942: =item *
13943: 
13944: reply() : uses subreply to send a message to remote machine, logs all failures
13945: 
13946: =item *
13947: 
13948: critical() : passes a critical message to another server; if cannot
13949: get through then place message in connection buffer directory and
13950: returns con_delayed, if incapable of saving message, returns
13951: con_failed
13952: 
13953: =item *
13954: 
13955: reconlonc() : tries to reconnect lonc client processes.
13956: 
13957: =back
13958: 
13959: =head2 Resource Access Logging
13960: 
13961: =over 4
13962: 
13963: =item *
13964: 
13965: flushcourselogs() : flush (save) buffer logs and access logs
13966: 
13967: =item *
13968: 
13969: courselog($what) : save message for course in hash
13970: 
13971: =item *
13972: 
13973: courseacclog($what) : save message for course using &courselog().  Perform
13974: special processing for specific resource types (problems, exams, quizzes, etc).
13975: 
13976: =item *
13977: 
13978: goodbye() : flush course logs and log shutting down; it is called in srm.conf
13979: as a PerlChildExitHandler
13980: 
13981: =back
13982: 
13983: =head2 Other
13984: 
13985: =over 4
13986: 
13987: =item *
13988: 
13989: symblist($mapname,%newhash) : update symbolic storage links
13990: 
13991: =back
13992: 
13993: =cut
13994: 

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