File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1182: download - view: text, annotated - select for diffs
Fri Aug 3 10:55:53 2012 UTC (11 years, 11 months ago) by foxr
Branches: MAIN
CVS tags: HEAD
Ensure, if necessary, resources are internally represented as UTF-8

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1182 2012/08/03 10:55:53 foxr 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: 
   79: use Encode;
   80: 
   81: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
   82:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
   83:             %managerstab);
   84: 
   85: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
   86:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
   87:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
   88:     %courseownerbuf, %coursetypebuf,$locknum);
   89: 
   90: use IO::Socket;
   91: use GDBM_File;
   92: use HTML::LCParser;
   93: use Fcntl qw(:flock);
   94: use Storable qw(thaw nfreeze);
   95: use Time::HiRes qw( gettimeofday tv_interval );
   96: use Cache::Memcached;
   97: use Digest::MD5;
   98: use Math::Random;
   99: use File::MMagic;
  100: use LONCAPA qw(:DEFAULT :match);
  101: use LONCAPA::Configuration;
  102: use LONCAPA::lonmetadata;
  103: use LONCAPA::Lond;
  104: 
  105: use File::Copy;
  106: 
  107: my $readit;
  108: my $max_connection_retries = 10;     # Or some such value.
  109: 
  110: require Exporter;
  111: 
  112: our @ISA = qw (Exporter);
  113: our @EXPORT = qw(%env);
  114: 
  115: 
  116: # --------------------------------------------------------------------- Logging
  117: {
  118:     my $logid;
  119:     sub instructor_log {
  120: 	my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
  121:         if (($cnum eq '') || ($cdom eq '')) {
  122:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  123:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  124:         }
  125: 	$logid++;
  126:         my $now = time();
  127: 	my $id=$now.'00000'.$$.'00000'.$logid;
  128: 	return &Apache::lonnet::put('nohist_'.$hash_name,
  129: 				    { $id => {
  130: 					'exe_uname' => $env{'user.name'},
  131: 					'exe_udom'  => $env{'user.domain'},
  132: 					'exe_time'  => $now,
  133: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
  134: 					'delflag'   => $delflag,
  135: 					'logentry'  => $storehash,
  136: 					'uname'     => $uname,
  137: 					'udom'      => $udom,
  138: 				    }
  139: 				  },$cdom,$cnum);
  140:     }
  141: }
  142: 
  143: sub logtouch {
  144:     my $execdir=$perlvar{'lonDaemons'};
  145:     unless (-e "$execdir/logs/lonnet.log") {	
  146: 	open(my $fh,">>$execdir/logs/lonnet.log");
  147: 	close $fh;
  148:     }
  149:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  150:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  151: }
  152: 
  153: sub logthis {
  154:     my $message=shift;
  155:     my $execdir=$perlvar{'lonDaemons'};
  156:     my $now=time;
  157:     my $local=localtime($now);
  158:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
  159: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
  160: 	print $fh $logstring;
  161: 	close($fh);
  162:     }
  163:     return 1;
  164: }
  165: 
  166: sub logperm {
  167:     my $message=shift;
  168:     my $execdir=$perlvar{'lonDaemons'};
  169:     my $now=time;
  170:     my $local=localtime($now);
  171:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
  172: 	print $fh "$now:$message:$local\n";
  173: 	close($fh);
  174:     }
  175:     return 1;
  176: }
  177: 
  178: sub create_connection {
  179:     my ($hostname,$lonid) = @_;
  180:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  181: 				     Type    => SOCK_STREAM,
  182: 				     Timeout => 10);
  183:     return 0 if (!$client);
  184:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
  185:     my $result = <$client>;
  186:     chomp($result);
  187:     return 1 if ($result eq 'done');
  188:     return 0;
  189: }
  190: 
  191: sub get_server_timezone {
  192:     my ($cnum,$cdom) = @_;
  193:     my $home=&homeserver($cnum,$cdom);
  194:     if ($home ne 'no_host') {
  195:         my $cachetime = 24*3600;
  196:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
  197:         if (defined($cached)) {
  198:             return $timezone;
  199:         } else {
  200:             my $timezone = &reply('servertimezone',$home);
  201:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
  202:         }
  203:     }
  204: }
  205: 
  206: sub get_server_distarch {
  207:     my ($lonhost,$ignore_cache) = @_;
  208:     if (defined($lonhost)) {
  209:         if (!defined(&hostname($lonhost))) {
  210:             return;
  211:         }
  212:         my $cachetime = 12*3600;
  213:         if (!$ignore_cache) {
  214:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
  215:             if (defined($cached)) {
  216:                 return $distarch;
  217:             }
  218:         }
  219:         my $rep = &reply('serverdistarch',$lonhost);
  220:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
  221:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
  222:                 $rep eq '') {
  223:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
  224:         }
  225:     }
  226:     return;
  227: }
  228: 
  229: sub get_server_loncaparev {
  230:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
  231:     if (defined($lonhost)) {
  232:         if (!defined(&hostname($lonhost))) {
  233:             undef($lonhost);
  234:         }
  235:     }
  236:     if (!defined($lonhost)) {
  237:         if (defined(&domain($dom,'primary'))) {
  238:             $lonhost=&domain($dom,'primary');
  239:             if ($lonhost eq 'no_host') {
  240:                 undef($lonhost);
  241:             }
  242:         }
  243:     }
  244:     if (defined($lonhost)) {
  245:         my $cachetime = 12*3600;
  246:         if (!$ignore_cache) {
  247:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
  248:             if (defined($cached)) {
  249:                 return $loncaparev;
  250:             }
  251:         }
  252:         my ($answer,$loncaparev);
  253:         my @ids=&current_machine_ids();
  254:         if (grep(/^\Q$lonhost\E$/,@ids)) {
  255:             $answer = $perlvar{'lonVersion'};
  256:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  257:                 $loncaparev = $1;
  258:             }
  259:         } else {
  260:             $answer = &reply('serverloncaparev',$lonhost);
  261:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
  262:                 if ($caller eq 'loncron') {
  263:                     my $ua=new LWP::UserAgent;
  264:                     $ua->timeout(4);
  265:                     my $protocol = $protocol{$lonhost};
  266:                     $protocol = 'http' if ($protocol ne 'https');
  267:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
  268:                     my $request=new HTTP::Request('GET',$url);
  269:                     my $response=$ua->request($request);
  270:                     unless ($response->is_error()) {
  271:                         my $content = $response->content;
  272:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
  273:                             $loncaparev = $1;
  274:                         }
  275:                     }
  276:                 } else {
  277:                     $loncaparev = $loncaparevs{$lonhost};
  278:                 }
  279:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  280:                 $loncaparev = $1;
  281:             }
  282:         }
  283:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
  284:     }
  285: }
  286: 
  287: sub get_server_homeID {
  288:     my ($hostname,$ignore_cache,$caller) = @_;
  289:     unless ($ignore_cache) {
  290:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
  291:         if (defined($cached)) {
  292:             return $serverhomeID;
  293:         }
  294:     }
  295:     my $cachetime = 12*3600;
  296:     my $serverhomeID;
  297:     if ($caller eq 'loncron') { 
  298:         my @machine_ids = &machine_ids($hostname);
  299:         foreach my $id (@machine_ids) {
  300:             my $response = &reply('serverhomeID',$id);
  301:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
  302:                 $serverhomeID = $response;
  303:                 last;
  304:             }
  305:         }
  306:         if ($serverhomeID eq '') {
  307:             $serverhomeID = $machine_ids[-1];
  308:         }
  309:     } else {
  310:         $serverhomeID = $serverhomeIDs{$hostname};
  311:     }
  312:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
  313: }
  314: 
  315: sub get_remote_globals {
  316:     my ($lonhost,$whathash,$ignore_cache) = @_;
  317:     my ($result,%returnhash,%whatneeded);
  318:     if (ref($whathash) eq 'HASH') {
  319:         foreach my $what (sort(keys(%{$whathash}))) {
  320:             my $hashid = $lonhost.'-'.$what;
  321:             my ($response,$cached);
  322:             unless ($ignore_cache) {
  323:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
  324:             }
  325:             if (defined($cached)) {
  326:                 $returnhash{$what} = $response;
  327:             } else {
  328:                 $whatneeded{$what} = 1;
  329:             }
  330:         }
  331:         if (keys(%whatneeded) == 0) {
  332:             $result = 'ok';
  333:         } else {
  334:             my $requested = &freeze_escape(\%whatneeded);
  335:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
  336:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  337:                 ($rep eq 'unknown_cmd')) {
  338:                 $result = $rep;
  339:             } else {
  340:                 $result = 'ok';
  341:                 my @pairs=split(/\&/,$rep);
  342:                 foreach my $item (@pairs) {
  343:                     my ($key,$value)=split(/=/,$item,2);
  344:                     my $what = &unescape($key);
  345:                     my $hashid = $lonhost.'-'.$what;
  346:                     $returnhash{$what}=&thaw_unescape($value);
  347:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
  348:                 }
  349:             }
  350:         }
  351:     }
  352:     return ($result,\%returnhash);
  353: }
  354: 
  355: sub remote_devalidate_cache {
  356:     my ($lonhost,$name,$id) = @_;
  357:     my $response = &reply('devalidatecache:'.&escape($name).':'.&escape($id),$lonhost);
  358:     return $response;
  359: }
  360: 
  361: # -------------------------------------------------- Non-critical communication
  362: sub subreply {
  363:     my ($cmd,$server)=@_;
  364:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  365:     #
  366:     #  With loncnew process trimming, there's a timing hole between lonc server
  367:     #  process exit and the master server picking up the listen on the AF_UNIX
  368:     #  socket.  In that time interval, a lock file will exist:
  369: 
  370:     my $lockfile=$peerfile.".lock";
  371:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  372: 	sleep(1);
  373:     }
  374:     # At this point, either a loncnew parent is listening or an old lonc
  375:     # or loncnew child is listening so we can connect or everything's dead.
  376:     #
  377:     #   We'll give the connection a few tries before abandoning it.  If
  378:     #   connection is not possible, we'll con_lost back to the client.
  379:     #   
  380:     my $client;
  381:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  382: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  383: 				      Type    => SOCK_STREAM,
  384: 				      Timeout => 10);
  385: 	if ($client) {
  386: 	    last;		# Connected!
  387: 	} else {
  388: 	    &create_connection(&hostname($server),$server);
  389: 	}
  390:         sleep(1);		# Try again later if failed connection.
  391:     }
  392:     my $answer;
  393:     if ($client) {
  394: 	print $client "sethost:$server:$cmd\n";
  395: 	$answer=<$client>;
  396: 	if (!$answer) { $answer="con_lost"; }
  397: 	chomp($answer);
  398:     } else {
  399: 	$answer = 'con_lost';	# Failed connection.
  400:     }
  401:     return $answer;
  402: }
  403: 
  404: sub reply {
  405:     my ($cmd,$server)=@_;
  406:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  407:     my $answer=subreply($cmd,$server);
  408:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  409:        &logthis("<font color=\"blue\">WARNING:".
  410:                 " $cmd to $server returned $answer</font>");
  411:     }
  412:     return $answer;
  413: }
  414: 
  415: # ----------------------------------------------------------- Send USR1 to lonc
  416: 
  417: sub reconlonc {
  418:     my ($lonid) = @_;
  419:     my $hostname = &hostname($lonid);
  420:     if ($lonid) {
  421: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  422: 	if ($hostname && -e $peerfile) {
  423: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  424: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  425: 					     Type    => SOCK_STREAM,
  426: 					     Timeout => 10);
  427: 	    if ($client) {
  428: 		print $client ("reset_retries\n");
  429: 		my $answer=<$client>;
  430: 		#reset just this one.
  431: 	    }
  432: 	}
  433: 	return;
  434:     }
  435: 
  436:     &logthis("Trying to reconnect lonc");
  437:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  438:     if (open(my $fh,"<$loncfile")) {
  439: 	my $loncpid=<$fh>;
  440:         chomp($loncpid);
  441:         if (kill 0 => $loncpid) {
  442: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  443:             kill USR1 => $loncpid;
  444:             sleep 1;
  445:          } else {
  446: 	    &logthis(
  447:                "<font color=\"blue\">WARNING:".
  448:                " lonc at pid $loncpid not responding, giving up</font>");
  449:         }
  450:     } else {
  451: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  452:     }
  453: }
  454: 
  455: # ------------------------------------------------------ Critical communication
  456: 
  457: sub critical {
  458:     my ($cmd,$server)=@_;
  459:     unless (&hostname($server)) {
  460:         &logthis("<font color=\"blue\">WARNING:".
  461:                " Critical message to unknown server ($server)</font>");
  462:         return 'no_such_host';
  463:     }
  464:     my $answer=reply($cmd,$server);
  465:     if ($answer eq 'con_lost') {
  466: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
  467: 	my $answer=reply($cmd,$server);
  468:         if ($answer eq 'con_lost') {
  469:             my $now=time;
  470:             my $middlename=$cmd;
  471:             $middlename=substr($middlename,0,16);
  472:             $middlename=~s/\W//g;
  473:             my $dfilename=
  474:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  475:             $dumpcount++;
  476:             {
  477: 		my $dfh;
  478: 		if (open($dfh,">$dfilename")) {
  479: 		    print $dfh "$cmd\n"; 
  480: 		    close($dfh);
  481: 		}
  482:             }
  483:             sleep 2;
  484:             my $wcmd='';
  485:             {
  486: 		my $dfh;
  487: 		if (open($dfh,"<$dfilename")) {
  488: 		    $wcmd=<$dfh>; 
  489: 		    close($dfh);
  490: 		}
  491:             }
  492:             chomp($wcmd);
  493:             if ($wcmd eq $cmd) {
  494: 		&logthis("<font color=\"blue\">WARNING: ".
  495:                          "Connection buffer $dfilename: $cmd</font>");
  496:                 &logperm("D:$server:$cmd");
  497: 	        return 'con_delayed';
  498:             } else {
  499:                 &logthis("<font color=\"red\">CRITICAL:"
  500:                         ." Critical connection failed: $server $cmd</font>");
  501:                 &logperm("F:$server:$cmd");
  502:                 return 'con_failed';
  503:             }
  504:         }
  505:     }
  506:     return $answer;
  507: }
  508: 
  509: # ------------------------------------------- check if return value is an error
  510: 
  511: sub error {
  512:     my ($result) = @_;
  513:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  514: 	if ($2 == 2) { return undef; }
  515: 	return $1;
  516:     }
  517:     return undef;
  518: }
  519: 
  520: sub convert_and_load_session_env {
  521:     my ($lonidsdir,$handle)=@_;
  522:     my @profile;
  523:     {
  524: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  525: 	if (!$opened) {
  526: 	    return 0;
  527: 	}
  528: 	flock($idf,LOCK_SH);
  529: 	@profile=<$idf>;
  530: 	close($idf);
  531:     }
  532:     my %temp_env;
  533:     foreach my $line (@profile) {
  534: 	if ($line !~ m/=/) {
  535: 	    return 0;
  536: 	}
  537: 	chomp($line);
  538: 	my ($envname,$envvalue)=split(/=/,$line,2);
  539: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  540:     }
  541:     unlink("$lonidsdir/$handle.id");
  542:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  543: 	    0640)) {
  544: 	%disk_env = %temp_env;
  545: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  546: 	untie(%disk_env);
  547:     }
  548:     return 1;
  549: }
  550: 
  551: # ------------------------------------------- Transfer profile into environment
  552: my $env_loaded;
  553: sub transfer_profile_to_env {
  554:     my ($lonidsdir,$handle,$force_transfer) = @_;
  555:     if (!$force_transfer && $env_loaded) { return; } 
  556: 
  557:     if (!defined($lonidsdir)) {
  558: 	$lonidsdir = $perlvar{'lonIDsDir'};
  559:     }
  560:     if (!defined($handle)) {
  561:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  562:     }
  563: 
  564:     my $convert;
  565:     {
  566:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  567: 	if (!$opened) {
  568: 	    return;
  569: 	}
  570: 	flock($idf,LOCK_SH);
  571: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  572: 		&GDBM_READER(),0640)) {
  573: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  574: 	    untie(%disk_env);
  575: 	} else {
  576: 	    $convert = 1;
  577: 	}
  578:     }
  579:     if ($convert) {
  580: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  581: 	    &logthis("Failed to load session, or convert session.");
  582: 	}
  583:     }
  584: 
  585:     my %remove;
  586:     while ( my $envname = each(%env) ) {
  587:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  588:             if ($time < time-300) {
  589:                 $remove{$key}++;
  590:             }
  591:         }
  592:     }
  593: 
  594:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  595:     $env_loaded=1;
  596:     foreach my $expired_key (keys(%remove)) {
  597:         &delenv($expired_key);
  598:     }
  599: }
  600: 
  601: # ---------------------------------------------------- Check for valid session 
  602: sub check_for_valid_session {
  603:     my ($r,$name) = @_;
  604:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  605:     if ($name eq '') {
  606:         $name = 'lonID';
  607:     }
  608:     my $lonid=$cookies{$name};
  609:     return undef if (!$lonid);
  610: 
  611:     my $handle=&LONCAPA::clean_handle($lonid->value);
  612:     my $lonidsdir;
  613:     if ($name eq 'lonDAV') {
  614:         $lonidsdir=$r->dir_config('lonDAVsessDir');
  615:     } else {
  616:         $lonidsdir=$r->dir_config('lonIDsDir');
  617:     }
  618:     return undef if (!-e "$lonidsdir/$handle.id");
  619: 
  620:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  621:     return undef if (!$opened);
  622: 
  623:     flock($idf,LOCK_SH);
  624:     my %disk_env;
  625:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  626: 	    &GDBM_READER(),0640)) {
  627: 	return undef;	
  628:     }
  629: 
  630:     if (!defined($disk_env{'user.name'})
  631: 	|| !defined($disk_env{'user.domain'})) {
  632: 	return undef;
  633:     }
  634:     return $handle;
  635: }
  636: 
  637: sub timed_flock {
  638:     my ($file,$lock_type) = @_;
  639:     my $failed=0;
  640:     eval {
  641: 	local $SIG{__DIE__}='DEFAULT';
  642: 	local $SIG{ALRM}=sub {
  643: 	    $failed=1;
  644: 	    die("failed lock");
  645: 	};
  646: 	alarm(13);
  647: 	flock($file,$lock_type);
  648: 	alarm(0);
  649:     };
  650:     if ($failed) {
  651: 	return undef;
  652:     } else {
  653: 	return 1;
  654:     }
  655: }
  656: 
  657: # ---------------------------------------------------------- Append Environment
  658: 
  659: sub appenv {
  660:     my ($newenv,$roles) = @_;
  661:     if (ref($newenv) eq 'HASH') {
  662:         foreach my $key (keys(%{$newenv})) {
  663:             my $refused = 0;
  664: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  665:                 $refused = 1;
  666:                 if (ref($roles) eq 'ARRAY') {
  667:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
  668:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  669:                         $refused = 0;
  670:                     }
  671:                 }
  672:             }
  673:             if ($refused) {
  674:                 &logthis("<font color=\"blue\">WARNING: ".
  675:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  676:                          .'</font>');
  677: 	        delete($newenv->{$key});
  678:             } else {
  679:                 $env{$key}=$newenv->{$key};
  680:             }
  681:         }
  682:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
  683:         if ($opened
  684: 	    && &timed_flock($env_file,LOCK_EX)
  685: 	    &&
  686: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  687: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  688: 	    while (my ($key,$value) = each(%{$newenv})) {
  689: 	        $disk_env{$key} = $value;
  690: 	    }
  691: 	    untie(%disk_env);
  692:         }
  693:     }
  694:     return 'ok';
  695: }
  696: # ----------------------------------------------------- Delete from Environment
  697: 
  698: sub delenv {
  699:     my ($delthis,$regexp,$roles) = @_;
  700:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
  701:         my $refused = 1;
  702:         if (ref($roles) eq 'ARRAY') {
  703:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
  704:             if (grep(/^\Q$role\E$/,@{$roles})) {
  705:                 $refused = 0;
  706:             }
  707:         }
  708:         if ($refused) {
  709:             &logthis("<font color=\"blue\">WARNING: ".
  710:                      "Attempt to delete from environment ".$delthis);
  711:             return 'error';
  712:         }
  713:     }
  714:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  715:     if ($opened
  716: 	&& &timed_flock($env_file,LOCK_EX)
  717: 	&&
  718: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  719: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  720: 	foreach my $key (keys(%disk_env)) {
  721: 	    if ($regexp) {
  722:                 if ($key=~/^$delthis/) {
  723:                     delete($env{$key});
  724:                     delete($disk_env{$key});
  725:                 } 
  726:             } else {
  727:                 if ($key=~/^\Q$delthis\E/) {
  728: 		    delete($env{$key});
  729: 		    delete($disk_env{$key});
  730: 	        }
  731:             }
  732: 	}
  733: 	untie(%disk_env);
  734:     }
  735:     return 'ok';
  736: }
  737: 
  738: sub get_env_multiple {
  739:     my ($name) = @_;
  740:     my @values;
  741:     if (defined($env{$name})) {
  742:         # exists is it an array
  743:         if (ref($env{$name})) {
  744:             @values=@{ $env{$name} };
  745:         } else {
  746:             $values[0]=$env{$name};
  747:         }
  748:     }
  749:     return(@values);
  750: }
  751: 
  752: # ------------------------------------------------------------------- Locking
  753: 
  754: sub set_lock {
  755:     my ($text)=@_;
  756:     $locknum++;
  757:     my $id=$$.'-'.$locknum;
  758:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  759:              'session.lock.'.$id => $text});
  760:     return $id;
  761: }
  762: 
  763: sub get_locks {
  764:     my $num=0;
  765:     my %texts=();
  766:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  767:        if ($lock=~/\w/) {
  768:           $num++;
  769:           $texts{$lock}=$env{'session.lock.'.$lock};
  770:        }
  771:    }
  772:    return ($num,%texts);
  773: }
  774: 
  775: sub remove_lock {
  776:     my ($id)=@_;
  777:     my $newlocks='';
  778:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  779:        if (($lock=~/\w/) && ($lock ne $id)) {
  780:           $newlocks.=','.$lock;
  781:        }
  782:     }
  783:     &appenv({'session.locks' => $newlocks});
  784:     &delenv('session.lock.'.$id);
  785: }
  786: 
  787: sub remove_all_locks {
  788:     my $activelocks=$env{'session.locks'};
  789:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  790:        if ($lock=~/\w/) {
  791:           &remove_lock($lock);
  792:        }
  793:     }
  794: }
  795: 
  796: 
  797: # ------------------------------------------ Find out current server userload
  798: sub userload {
  799:     my $numusers=0;
  800:     {
  801: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  802: 	my $filename;
  803: 	my $curtime=time;
  804: 	while ($filename=readdir(LONIDS)) {
  805: 	    next if ($filename eq '.' || $filename eq '..');
  806: 	    next if ($filename =~ /publicuser_\d+\.id/);
  807: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  808: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  809: 	}
  810: 	closedir(LONIDS);
  811:     }
  812:     my $userloadpercent=0;
  813:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  814:     if ($maxuserload) {
  815: 	$userloadpercent=100*$numusers/$maxuserload;
  816:     }
  817:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  818:     return $userloadpercent;
  819: }
  820: 
  821: # ------------------------------ Find server with least workload from spare.tab
  822: 
  823: sub spareserver {
  824:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
  825:     my $spare_server;
  826:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  827:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  828:                                                      :  $userloadpercent;
  829:     my ($uint_dom,$remotesessions);
  830:     if (($udom ne '') && (&domain($udom) ne '')) {
  831:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
  832:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
  833:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
  834:         $remotesessions = $udomdefaults{'remotesessions'};
  835:     }
  836:     my $spareshash = &this_host_spares($udom);
  837:     if (ref($spareshash) eq 'HASH') {
  838:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  839:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  840:                 if ($uint_dom) {
  841:                     next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
  842:                                                  $try_server));
  843:                 }
  844: 	        ($spare_server, $lowest_load) =
  845: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
  846:             }
  847:         }
  848: 
  849:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
  850: 
  851:         if (!$found_server) {
  852:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
  853: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
  854:                     if ($uint_dom) {
  855:                         next unless (&spare_can_host($udom,$uint_dom,
  856:                                                      $remotesessions,$try_server));
  857:                     }
  858: 	            ($spare_server, $lowest_load) =
  859: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
  860:                 }
  861: 	    }
  862:         }
  863:     }
  864: 
  865:     if (!$want_server_name) {
  866:         my $protocol = 'http';
  867:         if ($protocol{$spare_server} eq 'https') {
  868:             $protocol = $protocol{$spare_server};
  869:         }
  870:         if (defined($spare_server)) {
  871:             my $hostname = &hostname($spare_server);
  872:             if (defined($hostname)) {
  873: 	        $spare_server = $protocol.'://'.$hostname;
  874:             }
  875:         }
  876:     }
  877:     return $spare_server;
  878: }
  879: 
  880: sub compare_server_load {
  881:     my ($try_server, $spare_server, $lowest_load) = @_;
  882: 
  883:     my $loadans     = &reply('load',    $try_server);
  884:     my $userloadans = &reply('userload',$try_server);
  885: 
  886:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  887: 	return ($spare_server, $lowest_load); #didn't get a number from the server
  888:     }
  889: 
  890:     my $load;
  891:     if ($loadans =~ /\d/) {
  892: 	if ($userloadans =~ /\d/) {
  893: 	    #both are numbers, pick the bigger one
  894: 	    $load = ($loadans > $userloadans) ? $loadans 
  895: 		                              : $userloadans;
  896: 	} else {
  897: 	    $load = $loadans;
  898: 	}
  899:     } else {
  900: 	$load = $userloadans;
  901:     }
  902: 
  903:     if (($load =~ /\d/) && ($load < $lowest_load)) {
  904: 	$spare_server = $try_server;
  905: 	$lowest_load  = $load;
  906:     }
  907:     return ($spare_server,$lowest_load);
  908: }
  909: 
  910: # --------------------------- ask offload servers if user already has a session
  911: sub find_existing_session {
  912:     my ($udom,$uname) = @_;
  913:     my $spareshash = &this_host_spares($udom);
  914:     if (ref($spareshash) eq 'HASH') {
  915:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  916:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  917:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
  918:             }
  919:         }
  920:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
  921:             foreach my $try_server (@{ $spareshash->{'default'} }) {
  922:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
  923:             }
  924:         }
  925:     }
  926:     return;
  927: }
  928: 
  929: # -------------------------------- ask if server already has a session for user
  930: sub has_user_session {
  931:     my ($lonid,$udom,$uname) = @_;
  932:     my $result = &reply(join(':','userhassession',
  933: 			     map {&escape($_)} ($udom,$uname)),$lonid);
  934:     return 1 if ($result eq 'ok');
  935: 
  936:     return 0;
  937: }
  938: 
  939: # --------- determine least loaded server in a user's domain which allows login
  940: 
  941: sub choose_server {
  942:     my ($udom,$checkloginvia) = @_;
  943:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
  944:     my %servers = &get_servers($udom);
  945:     my $lowest_load = 30000;
  946:     my ($login_host,$hostname,$portal_path,$isredirect);
  947:     foreach my $lonhost (keys(%servers)) {
  948:         my $loginvia;
  949:         if ($checkloginvia) {
  950:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
  951:             if ($loginvia) {
  952:                 my ($server,$path) = split(/:/,$loginvia);
  953:                 ($login_host, $lowest_load) =
  954:                     &compare_server_load($server, $login_host, $lowest_load);
  955:                 if ($login_host eq $server) {
  956:                     $portal_path = $path;
  957:                     $isredirect = 1;
  958:                 }
  959:             } else {
  960:                 ($login_host, $lowest_load) =
  961:                     &compare_server_load($lonhost, $login_host, $lowest_load);
  962:                 if ($login_host eq $lonhost) {
  963:                     $portal_path = '';
  964:                     $isredirect = ''; 
  965:                 }
  966:             }
  967:         } else {
  968:             ($login_host, $lowest_load) =
  969:                 &compare_server_load($lonhost, $login_host, $lowest_load);
  970:         }
  971:     }
  972:     if ($login_host ne '') {
  973:         $hostname = &hostname($login_host);
  974:     }
  975:     return ($login_host,$hostname,$portal_path,$isredirect);
  976: }
  977: 
  978: # --------------------------------------------- Try to change a user's password
  979: 
  980: sub changepass {
  981:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
  982:     $currentpass = &escape($currentpass);
  983:     $newpass     = &escape($newpass);
  984:     my $lonhost = $perlvar{'lonHostID'};
  985:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
  986: 		       $server);
  987:     if (! $answer) {
  988: 	&logthis("No reply on password change request to $server ".
  989: 		 "by $uname in domain $udom.");
  990:     } elsif ($answer =~ "^ok") {
  991:         &logthis("$uname in $udom successfully changed their password ".
  992: 		 "on $server.");
  993:     } elsif ($answer =~ "^pwchange_failure") {
  994: 	&logthis("$uname in $udom was unable to change their password ".
  995: 		 "on $server.  The action was blocked by either lcpasswd ".
  996: 		 "or pwchange");
  997:     } elsif ($answer =~ "^non_authorized") {
  998:         &logthis("$uname in $udom did not get their password correct when ".
  999: 		 "attempting to change it on $server.");
 1000:     } elsif ($answer =~ "^auth_mode_error") {
 1001:         &logthis("$uname in $udom attempted to change their password despite ".
 1002: 		 "not being locally or internally authenticated on $server.");
 1003:     } elsif ($answer =~ "^unknown_user") {
 1004:         &logthis("$uname in $udom attempted to change their password ".
 1005: 		 "on $server but were unable to because $server is not ".
 1006: 		 "their home server.");
 1007:     } elsif ($answer =~ "^refused") {
 1008: 	&logthis("$server refused to change $uname in $udom password because ".
 1009: 		 "it was sent an unencrypted request to change the password.");
 1010:     } elsif ($answer =~ "invalid_client") {
 1011:         &logthis("$server refused to change $uname in $udom password because ".
 1012:                  "it was a reset by e-mail originating from an invalid server.");
 1013:     }
 1014:     return $answer;
 1015: }
 1016: 
 1017: # ----------------------- Try to determine user's current authentication scheme
 1018: 
 1019: sub queryauthenticate {
 1020:     my ($uname,$udom)=@_;
 1021:     my $uhome=&homeserver($uname,$udom);
 1022:     if (!$uhome) {
 1023: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
 1024: 	return 'no_host';
 1025:     }
 1026:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
 1027:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
 1028: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1029:     }
 1030:     return $answer;
 1031: }
 1032: 
 1033: # --------- Try to authenticate user from domain's lib servers (first this one)
 1034: 
 1035: sub authenticate {
 1036:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
 1037:     $upass=&escape($upass);
 1038:     $uname= &LONCAPA::clean_username($uname);
 1039:     my $uhome=&homeserver($uname,$udom,1);
 1040:     my $newhome;
 1041:     if ((!$uhome) || ($uhome eq 'no_host')) {
 1042: # Maybe the machine was offline and only re-appeared again recently?
 1043:         &reconlonc();
 1044: # One more
 1045: 	$uhome=&homeserver($uname,$udom,1);
 1046:         if (($uhome eq 'no_host') && $checkdefauth) {
 1047:             if (defined(&domain($udom,'primary'))) {
 1048:                 $newhome=&domain($udom,'primary');
 1049:             }
 1050:             if ($newhome ne '') {
 1051:                 $uhome = $newhome;
 1052:             }
 1053:         }
 1054: 	if ((!$uhome) || ($uhome eq 'no_host')) {
 1055: 	    &logthis("User $uname at $udom is unknown in authenticate");
 1056: 	    return 'no_host';
 1057:         }
 1058:     }
 1059:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
 1060:     if ($answer eq 'authorized') {
 1061:         if ($newhome) {
 1062:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
 1063:             return 'no_account_on_host'; 
 1064:         } else {
 1065:             &logthis("User $uname at $udom authorized by $uhome");
 1066:             return $uhome;
 1067:         }
 1068:     }
 1069:     if ($answer eq 'non_authorized') {
 1070: 	&logthis("User $uname at $udom rejected by $uhome");
 1071: 	return 'no_host'; 
 1072:     }
 1073:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1074:     return 'no_host';
 1075: }
 1076: 
 1077: sub can_host_session {
 1078:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
 1079:     my $canhost = 1;
 1080:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
 1081:     if (ref($remotesessions) eq 'HASH') {
 1082:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
 1083:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
 1084:                 $canhost = 0;
 1085:             } else {
 1086:                 $canhost = 1;
 1087:             }
 1088:         }
 1089:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
 1090:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
 1091:                 $canhost = 1;
 1092:             } else {
 1093:                 $canhost = 0;
 1094:             }
 1095:         }
 1096:         if ($canhost) {
 1097:             if ($remotesessions->{'version'} ne '') {
 1098:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
 1099:                 if ($reqmajor ne '' && $reqminor ne '') {
 1100:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
 1101:                         my $major = $1;
 1102:                         my $minor = $2;
 1103:                         if (($major < $reqmajor ) ||
 1104:                             (($major == $reqmajor) && ($minor < $reqminor))) {
 1105:                             $canhost = 0;
 1106:                         }
 1107:                     } else {
 1108:                         $canhost = 0;
 1109:                     }
 1110:                 }
 1111:             }
 1112:         }
 1113:     }
 1114:     if ($canhost) {
 1115:         if (ref($hostedsessions) eq 'HASH') {
 1116:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1117:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 1118:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
 1119:                 if (($uint_dom ne '') && 
 1120:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
 1121:                     $canhost = 0;
 1122:                 } else {
 1123:                     $canhost = 1;
 1124:                 }
 1125:             }
 1126:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
 1127:                 if (($uint_dom ne '') && 
 1128:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
 1129:                     $canhost = 1;
 1130:                 } else {
 1131:                     $canhost = 0;
 1132:                 }
 1133:             }
 1134:         }
 1135:     }
 1136:     return $canhost;
 1137: }
 1138: 
 1139: sub spare_can_host {
 1140:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
 1141:     my $canhost=1;
 1142:     my @intdoms;
 1143:     my $internet_names = &Apache::lonnet::get_internet_names($try_server);
 1144:     if (ref($internet_names) eq 'ARRAY') {
 1145:         @intdoms = @{$internet_names};
 1146:     }
 1147:     unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1148:         my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
 1149:         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
 1150:         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
 1151:         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
 1152:         $canhost = &can_host_session($udom,$try_server,$remoterev,
 1153:                                      $remotesessions,
 1154:                                      $defdomdefaults{'hostedsessions'});
 1155:     }
 1156:     return $canhost;
 1157: }
 1158: 
 1159: sub this_host_spares {
 1160:     my ($dom) = @_;
 1161:     my ($dom_in_use,$lonhost_in_use,$result);
 1162:     my @hosts = &current_machine_ids();
 1163:     foreach my $lonhost (@hosts) {
 1164:         if (&host_domain($lonhost) eq $dom) {
 1165:             $dom_in_use = $dom;
 1166:             $lonhost_in_use = $lonhost;
 1167:             last;
 1168:         }
 1169:     }
 1170:     if ($dom_in_use ne '') {
 1171:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1172:     }
 1173:     if (ref($result) ne 'HASH') {
 1174:         $lonhost_in_use = $perlvar{'lonHostID'};
 1175:         $dom_in_use = &host_domain($lonhost_in_use);
 1176:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1177:         if (ref($result) ne 'HASH') {
 1178:             $result = \%spareid;
 1179:         }
 1180:     }
 1181:     return $result;
 1182: }
 1183: 
 1184: sub spares_for_offload  {
 1185:     my ($dom_in_use,$lonhost_in_use) = @_;
 1186:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
 1187:     if (defined($cached)) {
 1188:         return $result;
 1189:     } else {
 1190:         my $cachetime = 60*60*24;
 1191:         my %domconfig =
 1192:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
 1193:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1194:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
 1195:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
 1196:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
 1197:                 }
 1198:             }
 1199:         }
 1200:     }
 1201:     return;
 1202: }
 1203: 
 1204: sub get_lonbalancer_config {
 1205:     my ($servers) = @_;
 1206:     my ($currbalancer,$currtargets);
 1207:     if (ref($servers) eq 'HASH') {
 1208:         foreach my $server (keys(%{$servers})) {
 1209:             my %what = (
 1210:                          spareid => 1,
 1211:                          perlvar => 1,
 1212:                        );
 1213:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
 1214:             if ($result eq 'ok') {
 1215:                 if (ref($returnhash) eq 'HASH') {
 1216:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
 1217:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
 1218:                             $currbalancer = $server;
 1219:                             $currtargets = {};
 1220:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
 1221:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
 1222:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
 1223:                                 }
 1224:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
 1225:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
 1226:                                 }
 1227:                             }
 1228:                             last;
 1229:                         }
 1230:                     }
 1231:                 }
 1232:             }
 1233:         }
 1234:     }
 1235:     return ($currbalancer,$currtargets);
 1236: }
 1237: 
 1238: sub check_loadbalancing {
 1239:     my ($uname,$udom) = @_;
 1240:     my ($is_balancer,$dom_in_use,$homeintdom,$rule_in_effect,
 1241:         $offloadto,$otherserver);
 1242:     my $lonhost = $perlvar{'lonHostID'};
 1243:     my @hosts = &current_machine_ids();
 1244:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1245:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
 1246:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
 1247:     my $serverhomedom = &host_domain($lonhost);
 1248: 
 1249:     my $cachetime = 60*60*24;
 1250: 
 1251:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1252:         $dom_in_use = $udom;
 1253:         $homeintdom = 1;
 1254:     } else {
 1255:         $dom_in_use = $serverhomedom;
 1256:     }
 1257:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
 1258:     unless (defined($cached)) {
 1259:         my %domconfig =
 1260:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
 1261:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1262:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1263:         }
 1264:     }
 1265:     if (ref($result) eq 'HASH') {
 1266:         my $currbalancer = $result->{'lonhost'};
 1267:         my $currtargets = $result->{'targets'};
 1268:         my $currrules = $result->{'rules'};
 1269:         if ($currbalancer ne '') {
 1270:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
 1271:                 $is_balancer = 1;
 1272:             }
 1273:         }
 1274:         if ($is_balancer) {
 1275:             if (ref($currrules) eq 'HASH') {
 1276:                 if ($homeintdom) {
 1277:                     if ($uname ne '') {
 1278:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
 1279:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
 1280:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
 1281:                                 $rule_in_effect = $currrules->{'_LC_author'};
 1282:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
 1283:                                 $rule_in_effect = $currrules->{'_LC_adv'}
 1284:                             }
 1285:                         }
 1286:                         if ($rule_in_effect eq '') {
 1287:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
 1288:                             if ($userenv{'inststatus'} ne '') {
 1289:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
 1290:                                 my ($othertitle,$usertypes,$types) =
 1291:                                     &Apache::loncommon::sorted_inst_types($udom);
 1292:                                 if (ref($types) eq 'ARRAY') {
 1293:                                     foreach my $type (@{$types}) {
 1294:                                         if (grep(/^\Q$type\E$/,@statuses)) {
 1295:                                             if (exists($currrules->{$type})) {
 1296:                                                 $rule_in_effect = $currrules->{$type};
 1297:                                             }
 1298:                                         }
 1299:                                     }
 1300:                                 }
 1301:                             } else {
 1302:                                 if (exists($currrules->{'default'})) {
 1303:                                     $rule_in_effect = $currrules->{'default'};
 1304:                                 }
 1305:                             }
 1306:                         }
 1307:                     } else {
 1308:                         if (exists($currrules->{'default'})) {
 1309:                             $rule_in_effect = $currrules->{'default'};
 1310:                         }
 1311:                     }
 1312:                 } else {
 1313:                     if ($currrules->{'_LC_external'} ne '') {
 1314:                         $rule_in_effect = $currrules->{'_LC_external'};
 1315:                     }
 1316:                 }
 1317:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1318:                                                        $uname,$udom);
 1319:             }
 1320:         }
 1321:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
 1322:         my ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
 1323:         unless (defined($cached)) {
 1324:             my %domconfig =
 1325:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
 1326:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1327:                 $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1328:             }
 1329:         }
 1330:         if (ref($result) eq 'HASH') {
 1331:             my $currbalancer = $result->{'lonhost'};
 1332:             my $currtargets = $result->{'targets'};
 1333:             my $currrules = $result->{'rules'};
 1334: 
 1335:             if ($currbalancer eq $lonhost) {
 1336:                 $is_balancer = 1;
 1337:                 if (ref($currrules) eq 'HASH') {
 1338:                     if ($currrules->{'_LC_internetdom'} ne '') {
 1339:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
 1340:                     }
 1341:                 }
 1342:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1343:                                                        $uname,$udom);
 1344:             }
 1345:         } else {
 1346:             if ($perlvar{'lonBalancer'} eq 'yes') {
 1347:                 $is_balancer = 1;
 1348:                 $offloadto = &this_host_spares($dom_in_use);
 1349:             }
 1350:         }
 1351:     } else {
 1352:         if ($perlvar{'lonBalancer'} eq 'yes') {
 1353:             $is_balancer = 1;
 1354:             $offloadto = &this_host_spares($dom_in_use);
 1355:         }
 1356:     }
 1357:     if ($is_balancer) {
 1358:         my $lowest_load = 30000;
 1359:         if (ref($offloadto) eq 'HASH') {
 1360:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
 1361:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
 1362:                     ($otherserver,$lowest_load) =
 1363:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1364:                 }
 1365:             }
 1366:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
 1367: 
 1368:             if (!$found_server) {
 1369:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
 1370:                     foreach my $try_server (@{$offloadto->{'default'}}) {
 1371:                         ($otherserver,$lowest_load) =
 1372:                             &compare_server_load($try_server,$otherserver,$lowest_load);
 1373:                     }
 1374:                 }
 1375:             }
 1376:         } elsif (ref($offloadto) eq 'ARRAY') {
 1377:             if (@{$offloadto} == 1) {
 1378:                 $otherserver = $offloadto->[0];
 1379:             } elsif (@{$offloadto} > 1) {
 1380:                 foreach my $try_server (@{$offloadto}) {
 1381:                     ($otherserver,$lowest_load) =
 1382:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1383:                 }
 1384:             }
 1385:         }
 1386:         if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
 1387:             $is_balancer = 0;
 1388:             if ($uname ne '' && $udom ne '') {
 1389:                 if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
 1390:                     
 1391:                     &appenv({'user.loadbalexempt'     => $lonhost,  
 1392:                              'user.loadbalcheck.time' => time});
 1393:                 }
 1394:             }
 1395:         }
 1396:     }
 1397:     return ($is_balancer,$otherserver);
 1398: }
 1399: 
 1400: sub get_loadbalancer_targets {
 1401:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
 1402:     my $offloadto;
 1403:     if ($rule_in_effect eq 'none') {
 1404:         return [$perlvar{'lonHostID'}];
 1405:     } elsif ($rule_in_effect eq '') {
 1406:         $offloadto = $currtargets;
 1407:     } else {
 1408:         if ($rule_in_effect eq 'homeserver') {
 1409:             my $homeserver = &homeserver($uname,$udom);
 1410:             if ($homeserver ne 'no_host') {
 1411:                 $offloadto = [$homeserver];
 1412:             }
 1413:         } elsif ($rule_in_effect eq 'externalbalancer') {
 1414:             my %domconfig =
 1415:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1416:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1417:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
 1418:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
 1419:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
 1420:                     }
 1421:                 }
 1422:             } else {
 1423:                 my %servers = &internet_dom_servers($udom);
 1424:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
 1425:                 if (&hostname($remotebalancer) ne '') {
 1426:                     $offloadto = [$remotebalancer];
 1427:                 }
 1428:             }
 1429:         } elsif (&hostname($rule_in_effect) ne '') {
 1430:             $offloadto = [$rule_in_effect];
 1431:         }
 1432:     }
 1433:     return $offloadto;
 1434: }
 1435: 
 1436: sub internet_dom_servers {
 1437:     my ($dom) = @_;
 1438:     my (%uniqservers,%servers);
 1439:     my $primaryserver = &hostname(&domain($dom,'primary'));
 1440:     my @machinedoms = &machine_domains($primaryserver);
 1441:     foreach my $mdom (@machinedoms) {
 1442:         my %currservers = %servers;
 1443:         my %server = &get_servers($mdom);
 1444:         %servers = (%currservers,%server);
 1445:     }
 1446:     my %by_hostname;
 1447:     foreach my $id (keys(%servers)) {
 1448:         push(@{$by_hostname{$servers{$id}}},$id);
 1449:     }
 1450:     foreach my $hostname (sort(keys(%by_hostname))) {
 1451:         if (@{$by_hostname{$hostname}} > 1) {
 1452:             my $match = 0;
 1453:             foreach my $id (@{$by_hostname{$hostname}}) {
 1454:                 if (&host_domain($id) eq $dom) {
 1455:                     $uniqservers{$id} = $hostname;
 1456:                     $match = 1;
 1457:                 }
 1458:             }
 1459:             unless ($match) {
 1460:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1461:             }
 1462:         } else {
 1463:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1464:         }
 1465:     }
 1466:     return %uniqservers;
 1467: }
 1468: 
 1469: # ---------------------- Find the homebase for a user from domain's lib servers
 1470: 
 1471: my %homecache;
 1472: sub homeserver {
 1473:     my ($uname,$udom,$ignoreBadCache)=@_;
 1474:     my $index="$uname:$udom";
 1475: 
 1476:     if (exists($homecache{$index})) { return $homecache{$index}; }
 1477: 
 1478:     my %servers = &get_servers($udom,'library');
 1479:     foreach my $tryserver (keys(%servers)) {
 1480:         next if ($ignoreBadCache ne 'true' && 
 1481: 		 exists($badServerCache{$tryserver}));
 1482: 
 1483: 	my $answer=reply("home:$udom:$uname",$tryserver);
 1484: 	if ($answer eq 'found') {
 1485: 	    delete($badServerCache{$tryserver}); 
 1486: 	    return $homecache{$index}=$tryserver;
 1487: 	} elsif ($answer eq 'no_host') {
 1488: 	    $badServerCache{$tryserver}=1;
 1489: 	}
 1490:     }    
 1491:     return 'no_host';
 1492: }
 1493: 
 1494: # ------------------------------------- Find the usernames behind a list of IDs
 1495: 
 1496: sub idget {
 1497:     my ($udom,@ids)=@_;
 1498:     my %returnhash=();
 1499:     
 1500:     my %servers = &get_servers($udom,'library');
 1501:     foreach my $tryserver (keys(%servers)) {
 1502: 	my $idlist=join('&',@ids);
 1503: 	$idlist=~tr/A-Z/a-z/; 
 1504: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
 1505: 	my @answer=();
 1506: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
 1507: 	    @answer=split(/\&/,$reply);
 1508: 	}                    ;
 1509: 	my $i;
 1510: 	for ($i=0;$i<=$#ids;$i++) {
 1511: 	    if ($answer[$i]) {
 1512: 		$returnhash{$ids[$i]}=$answer[$i];
 1513: 	    } 
 1514: 	}
 1515:     } 
 1516:     return %returnhash;
 1517: }
 1518: 
 1519: # ------------------------------------- Find the IDs behind a list of usernames
 1520: 
 1521: sub idrget {
 1522:     my ($udom,@unames)=@_;
 1523:     my %returnhash=();
 1524:     foreach my $uname (@unames) {
 1525:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
 1526:     }
 1527:     return %returnhash;
 1528: }
 1529: 
 1530: # ------------------------------- Store away a list of names and associated IDs
 1531: 
 1532: sub idput {
 1533:     my ($udom,%ids)=@_;
 1534:     my %servers=();
 1535:     foreach my $uname (keys(%ids)) {
 1536: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
 1537:         my $uhom=&homeserver($uname,$udom);
 1538:         if ($uhom ne 'no_host') {
 1539:             my $id=&escape($ids{$uname});
 1540:             $id=~tr/A-Z/a-z/;
 1541:             my $esc_unam=&escape($uname);
 1542: 	    if ($servers{$uhom}) {
 1543: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
 1544:             } else {
 1545:                 $servers{$uhom}=$id.'='.$esc_unam;
 1546:             }
 1547:         }
 1548:     }
 1549:     foreach my $server (keys(%servers)) {
 1550:         &critical('idput:'.$udom.':'.$servers{$server},$server);
 1551:     }
 1552: }
 1553: 
 1554: # ------------------------------dump from db file owned by domainconfig user
 1555: sub dump_dom {
 1556:     my ($namespace, $udom, $regexp) = @_;
 1557: 
 1558:     $udom ||= $env{'user.domain'};
 1559: 
 1560:     return () unless $udom;
 1561: 
 1562:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
 1563: }
 1564: 
 1565: # ------------------------------------------ get items from domain db files   
 1566: 
 1567: sub get_dom {
 1568:     my ($namespace,$storearr,$udom,$uhome)=@_;
 1569:     my $items='';
 1570:     foreach my $item (@$storearr) {
 1571:         $items.=&escape($item).'&';
 1572:     }
 1573:     $items=~s/\&$//;
 1574:     if (!$udom) {
 1575:         $udom=$env{'user.domain'};
 1576:         if (defined(&domain($udom,'primary'))) {
 1577:             $uhome=&domain($udom,'primary');
 1578:         } else {
 1579:             undef($uhome);
 1580:         }
 1581:     } else {
 1582:         if (!$uhome) {
 1583:             if (defined(&domain($udom,'primary'))) {
 1584:                 $uhome=&domain($udom,'primary');
 1585:             }
 1586:         }
 1587:     }
 1588:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1589:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 1590:         my %returnhash;
 1591:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 1592:             return %returnhash;
 1593:         }
 1594:         my @pairs=split(/\&/,$rep);
 1595:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 1596:             return @pairs;
 1597:         }
 1598:         my $i=0;
 1599:         foreach my $item (@$storearr) {
 1600:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 1601:             $i++;
 1602:         }
 1603:         return %returnhash;
 1604:     } else {
 1605:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 1606:     }
 1607: }
 1608: 
 1609: # -------------------------------------------- put items in domain db files 
 1610: 
 1611: sub put_dom {
 1612:     my ($namespace,$storehash,$udom,$uhome)=@_;
 1613:     if (!$udom) {
 1614:         $udom=$env{'user.domain'};
 1615:         if (defined(&domain($udom,'primary'))) {
 1616:             $uhome=&domain($udom,'primary');
 1617:         } else {
 1618:             undef($uhome);
 1619:         }
 1620:     } else {
 1621:         if (!$uhome) {
 1622:             if (defined(&domain($udom,'primary'))) {
 1623:                 $uhome=&domain($udom,'primary');
 1624:             }
 1625:         }
 1626:     } 
 1627:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1628:         my $items='';
 1629:         foreach my $item (keys(%$storehash)) {
 1630:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 1631:         }
 1632:         $items=~s/\&$//;
 1633:         return &reply("putdom:$udom:$namespace:$items",$uhome);
 1634:     } else {
 1635:         &logthis("put_dom failed - no homeserver and/or domain");
 1636:     }
 1637: }
 1638: 
 1639: # --------------------- newput for items in db file owned by domainconfig user
 1640: sub newput_dom {
 1641:     my ($namespace,$storehash,$udom) = @_;
 1642:     my $result;
 1643:     if (!$udom) {
 1644:         $udom=$env{'user.domain'};
 1645:     }
 1646:     if ($udom) {
 1647:         my $uname = &get_domainconfiguser($udom);
 1648:         $result = &newput($namespace,$storehash,$udom,$uname);
 1649:     }
 1650:     return $result;
 1651: }
 1652: 
 1653: # --------------------- delete for items in db file owned by domainconfig user
 1654: sub del_dom {
 1655:     my ($namespace,$storearr,$udom)=@_;
 1656:     if (ref($storearr) eq 'ARRAY') {
 1657:         if (!$udom) {
 1658:             $udom=$env{'user.domain'};
 1659:         }
 1660:         if ($udom) {
 1661:             my $uname = &get_domainconfiguser($udom); 
 1662:             return &del($namespace,$storearr,$udom,$uname);
 1663:         }
 1664:     }
 1665: }
 1666: 
 1667: # ----------------------------------construct domainconfig user for a domain 
 1668: sub get_domainconfiguser {
 1669:     my ($udom) = @_;
 1670:     return $udom.'-domainconfig';
 1671: }
 1672: 
 1673: sub retrieve_inst_usertypes {
 1674:     my ($udom) = @_;
 1675:     my (%returnhash,@order);
 1676:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 1677:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 1678:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 1679:         %returnhash = %{$domdefs{'inststatustypes'}};
 1680:         @order = @{$domdefs{'inststatusorder'}};
 1681:     } else {
 1682:         if (defined(&domain($udom,'primary'))) {
 1683:             my $uhome=&domain($udom,'primary');
 1684:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 1685:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 1686:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
 1687:                 return (\%returnhash,\@order);
 1688:             }
 1689:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 1690:             my @pairs=split(/\&/,$hashitems);
 1691:             foreach my $item (@pairs) {
 1692:                 my ($key,$value)=split(/=/,$item,2);
 1693:                 $key = &unescape($key);
 1694:                 next if ($key =~ /^error: 2 /);
 1695:                 $returnhash{$key}=&thaw_unescape($value);
 1696:             }
 1697:             my @esc_order = split(/\&/,$orderitems);
 1698:             foreach my $item (@esc_order) {
 1699:                 push(@order,&unescape($item));
 1700:             }
 1701:         } else {
 1702:             &logthis("get_dom failed - no primary domain server for $udom");
 1703:         }
 1704:     }
 1705:     return (\%returnhash,\@order);
 1706: }
 1707: 
 1708: sub is_domainimage {
 1709:     my ($url) = @_;
 1710:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
 1711:         if (&domain($1) ne '') {
 1712:             return '1';
 1713:         }
 1714:     }
 1715:     return;
 1716: }
 1717: 
 1718: sub inst_directory_query {
 1719:     my ($srch) = @_;
 1720:     my $udom = $srch->{'srchdomain'};
 1721:     my %results;
 1722:     my $homeserver = &domain($udom,'primary');
 1723:     my $outcome;
 1724:     if ($homeserver ne '') {
 1725: 	my $queryid=&reply("querysend:instdirsearch:".
 1726: 			   &escape($srch->{'srchby'}).':'.
 1727: 			   &escape($srch->{'srchterm'}).':'.
 1728: 			   &escape($srch->{'srchtype'}),$homeserver);
 1729: 	my $host=&hostname($homeserver);
 1730: 	if ($queryid !~/^\Q$host\E\_/) {
 1731: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1732: 	    return;
 1733: 	}
 1734: 	my $response = &get_query_reply($queryid);
 1735: 	my $maxtries = 5;
 1736: 	my $tries = 1;
 1737: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1738: 	    $response = &get_query_reply($queryid);
 1739: 	    $tries ++;
 1740: 	}
 1741: 
 1742:         if (!&error($response) && $response ne 'refused') {
 1743:             if ($response eq 'unavailable') {
 1744:                 $outcome = $response;
 1745:             } else {
 1746:                 $outcome = 'ok';
 1747:                 my @matches = split(/\n/,$response);
 1748:                 foreach my $match (@matches) {
 1749:                     my ($key,$value) = split(/=/,$match);
 1750:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 1751:                 }
 1752:             }
 1753:         }
 1754:     }
 1755:     return ($outcome,%results);
 1756: }
 1757: 
 1758: sub usersearch {
 1759:     my ($srch) = @_;
 1760:     my $dom = $srch->{'srchdomain'};
 1761:     my %results;
 1762:     my %libserv = &all_library();
 1763:     my $query = 'usersearch';
 1764:     foreach my $tryserver (keys(%libserv)) {
 1765:         if (&host_domain($tryserver) eq $dom) {
 1766:             my $host=&hostname($tryserver);
 1767:             my $queryid=
 1768:                 &reply("querysend:".&escape($query).':'.
 1769:                        &escape($srch->{'srchby'}).':'.
 1770:                        &escape($srch->{'srchtype'}).':'.
 1771:                        &escape($srch->{'srchterm'}),$tryserver);
 1772:             if ($queryid !~/^\Q$host\E\_/) {
 1773:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 1774:                 next;
 1775:             }
 1776:             my $reply = &get_query_reply($queryid);
 1777:             my $maxtries = 1;
 1778:             my $tries = 1;
 1779:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 1780:                 $reply = &get_query_reply($queryid);
 1781:                 $tries ++;
 1782:             }
 1783:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 1784:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 1785:             } else {
 1786:                 my @matches;
 1787:                 if ($reply =~ /\n/) {
 1788:                     @matches = split(/\n/,$reply);
 1789:                 } else {
 1790:                     @matches = split(/\&/,$reply);
 1791:                 }
 1792:                 foreach my $match (@matches) {
 1793:                     my ($uname,$udom,%userhash);
 1794:                     foreach my $entry (split(/:/,$match)) {
 1795:                         my ($key,$value) =
 1796:                             map {&unescape($_);} split(/=/,$entry);
 1797:                         $userhash{$key} = $value;
 1798:                         if ($key eq 'username') {
 1799:                             $uname = $value;
 1800:                         } elsif ($key eq 'domain') {
 1801:                             $udom = $value;
 1802:                         }
 1803:                     }
 1804:                     $results{$uname.':'.$udom} = \%userhash;
 1805:                 }
 1806:             }
 1807:         }
 1808:     }
 1809:     return %results;
 1810: }
 1811: 
 1812: sub get_instuser {
 1813:     my ($udom,$uname,$id) = @_;
 1814:     my $homeserver = &domain($udom,'primary');
 1815:     my ($outcome,%results);
 1816:     if ($homeserver ne '') {
 1817:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 1818:                            &escape($id).':'.&escape($udom),$homeserver);
 1819:         my $host=&hostname($homeserver);
 1820:         if ($queryid !~/^\Q$host\E\_/) {
 1821:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1822:             return;
 1823:         }
 1824:         my $response = &get_query_reply($queryid);
 1825:         my $maxtries = 5;
 1826:         my $tries = 1;
 1827:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1828:             $response = &get_query_reply($queryid);
 1829:             $tries ++;
 1830:         }
 1831:         if (!&error($response) && $response ne 'refused') {
 1832:             if ($response eq 'unavailable') {
 1833:                 $outcome = $response;
 1834:             } else {
 1835:                 $outcome = 'ok';
 1836:                 my @matches = split(/\n/,$response);
 1837:                 foreach my $match (@matches) {
 1838:                     my ($key,$value) = split(/=/,$match);
 1839:                     $results{&unescape($key)} = &thaw_unescape($value);
 1840:                 }
 1841:             }
 1842:         }
 1843:     }
 1844:     my %userinfo;
 1845:     if (ref($results{$uname}) eq 'HASH') {
 1846:         %userinfo = %{$results{$uname}};
 1847:     } 
 1848:     return ($outcome,%userinfo);
 1849: }
 1850: 
 1851: sub inst_rulecheck {
 1852:     my ($udom,$uname,$id,$item,$rules) = @_;
 1853:     my %returnhash;
 1854:     if ($udom ne '') {
 1855:         if (ref($rules) eq 'ARRAY') {
 1856:             @{$rules} = map {&escape($_);} (@{$rules});
 1857:             my $rulestr = join(':',@{$rules});
 1858:             my $homeserver=&domain($udom,'primary');
 1859:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1860:                 my $response;
 1861:                 if ($item eq 'username') {                
 1862:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 1863:                                               ':'.&escape($uname).':'.$rulestr,
 1864:                                               $homeserver));
 1865:                 } elsif ($item eq 'id') {
 1866:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 1867:                                               ':'.&escape($id).':'.$rulestr,
 1868:                                               $homeserver));
 1869:                 } elsif ($item eq 'selfcreate') {
 1870:                     $response=&unescape(&reply('instselfcreatecheck:'.
 1871:                                                &escape($udom).':'.&escape($uname).
 1872:                                               ':'.$rulestr,$homeserver));
 1873:                 }
 1874:                 if ($response ne 'refused') {
 1875:                     my @pairs=split(/\&/,$response);
 1876:                     foreach my $item (@pairs) {
 1877:                         my ($key,$value)=split(/=/,$item,2);
 1878:                         $key = &unescape($key);
 1879:                         next if ($key =~ /^error: 2 /);
 1880:                         $returnhash{$key}=&thaw_unescape($value);
 1881:                     }
 1882:                 }
 1883:             }
 1884:         }
 1885:     }
 1886:     return %returnhash;
 1887: }
 1888: 
 1889: sub inst_userrules {
 1890:     my ($udom,$check) = @_;
 1891:     my (%ruleshash,@ruleorder);
 1892:     if ($udom ne '') {
 1893:         my $homeserver=&domain($udom,'primary');
 1894:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1895:             my $response;
 1896:             if ($check eq 'id') {
 1897:                 $response=&reply('instidrules:'.&escape($udom),
 1898:                                  $homeserver);
 1899:             } elsif ($check eq 'email') {
 1900:                 $response=&reply('instemailrules:'.&escape($udom),
 1901:                                  $homeserver);
 1902:             } else {
 1903:                 $response=&reply('instuserrules:'.&escape($udom),
 1904:                                  $homeserver);
 1905:             }
 1906:             if (($response ne 'refused') && ($response ne 'error') && 
 1907:                 ($response ne 'unknown_cmd') && 
 1908:                 ($response ne 'no_such_host')) {
 1909:                 my ($hashitems,$orderitems) = split(/:/,$response);
 1910:                 my @pairs=split(/\&/,$hashitems);
 1911:                 foreach my $item (@pairs) {
 1912:                     my ($key,$value)=split(/=/,$item,2);
 1913:                     $key = &unescape($key);
 1914:                     next if ($key =~ /^error: 2 /);
 1915:                     $ruleshash{$key}=&thaw_unescape($value);
 1916:                 }
 1917:                 my @esc_order = split(/\&/,$orderitems);
 1918:                 foreach my $item (@esc_order) {
 1919:                     push(@ruleorder,&unescape($item));
 1920:                 }
 1921:             }
 1922:         }
 1923:     }
 1924:     return (\%ruleshash,\@ruleorder);
 1925: }
 1926: 
 1927: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 1928: 
 1929: sub get_domain_defaults {
 1930:     my ($domain) = @_;
 1931:     my $cachetime = 60*60*24;
 1932:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 1933:     if (defined($cached)) {
 1934:         if (ref($result) eq 'HASH') {
 1935:             return %{$result};
 1936:         }
 1937:     }
 1938:     my %domdefaults;
 1939:     my %domconfig =
 1940:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 1941:                                   'requestcourses','inststatus',
 1942:                                   'coursedefaults','usersessions'],$domain);
 1943:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 1944:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 1945:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 1946:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 1947:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 1948:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 1949:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
 1950:     } else {
 1951:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 1952:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 1953:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 1954:     }
 1955:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 1956:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 1957:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 1958:         } else {
 1959:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 1960:         } 
 1961:         my @usertools = ('aboutme','blog','webdav','portfolio');
 1962:         foreach my $item (@usertools) {
 1963:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 1964:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 1965:             }
 1966:         }
 1967:     }
 1968:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 1969:         foreach my $item ('official','unofficial','community') {
 1970:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 1971:         }
 1972:     }
 1973:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 1974:         foreach my $item ('inststatustypes','inststatusorder') {
 1975:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 1976:         }
 1977:     }
 1978:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 1979:         foreach my $item ('canuse_pdfforms') {
 1980:             $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
 1981:         }
 1982:     }
 1983:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1984:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 1985:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 1986:         }
 1987:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 1988:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 1989:         }
 1990:     }
 1991:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
 1992:                                   $cachetime);
 1993:     return %domdefaults;
 1994: }
 1995: 
 1996: # --------------------------------------------------- Assign a key to a student
 1997: 
 1998: sub assign_access_key {
 1999: #
 2000: # a valid key looks like uname:udom#comments
 2001: # comments are being appended
 2002: #
 2003:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 2004:     $kdom=
 2005:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 2006:     $knum=
 2007:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 2008:     $cdom=
 2009:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2010:     $cnum=
 2011:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2012:     $udom=$env{'user.name'} unless (defined($udom));
 2013:     $uname=$env{'user.domain'} unless (defined($uname));
 2014:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 2015:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 2016:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 2017:                                                   # assigned to this person
 2018:                                                   # - this should not happen,
 2019:                                                   # unless something went wrong
 2020:                                                   # the first time around
 2021: # ready to assign
 2022:         $logentry=$1.'; '.$logentry;
 2023:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 2024:                                                  $kdom,$knum) eq 'ok') {
 2025: # key now belongs to user
 2026: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 2027:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 2028:                 &appenv({'environment.'.$envkey => $ckey});
 2029:                 return 'ok';
 2030:             } else {
 2031:                 return 
 2032:   'error: Count not permanently assign key, will need to be re-entered later.';
 2033: 	    }
 2034:         } else {
 2035:             return 'error: Could not assign key, try again later.';
 2036:         }
 2037:     } elsif (!$existing{$ckey}) {
 2038: # the key does not exist
 2039: 	return 'error: The key does not exist';
 2040:     } else {
 2041: # the key is somebody else's
 2042: 	return 'error: The key is already in use';
 2043:     }
 2044: }
 2045: 
 2046: # ------------------------------------------ put an additional comment on a key
 2047: 
 2048: sub comment_access_key {
 2049: #
 2050: # a valid key looks like uname:udom#comments
 2051: # comments are being appended
 2052: #
 2053:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 2054:     $cdom=
 2055:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2056:     $cnum=
 2057:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2058:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2059:     if ($existing{$ckey}) {
 2060:         $existing{$ckey}.='; '.$logentry;
 2061: # ready to assign
 2062:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 2063:                                                  $cdom,$cnum) eq 'ok') {
 2064: 	    return 'ok';
 2065:         } else {
 2066: 	    return 'error: Count not store comment.';
 2067:         }
 2068:     } else {
 2069: # the key does not exist
 2070: 	return 'error: The key does not exist';
 2071:     }
 2072: }
 2073: 
 2074: # ------------------------------------------------------ Generate a set of keys
 2075: 
 2076: sub generate_access_keys {
 2077:     my ($number,$cdom,$cnum,$logentry)=@_;
 2078:     $cdom=
 2079:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2080:     $cnum=
 2081:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2082:     unless (&allowed('mky',$cdom)) { return 0; }
 2083:     unless (($cdom) && ($cnum)) { return 0; }
 2084:     if ($number>10000) { return 0; }
 2085:     sleep(2); # make sure don't get same seed twice
 2086:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 2087:     my $total=0;
 2088:     for (my $i=1;$i<=$number;$i++) {
 2089:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 2090:                   sprintf("%lx",int(100000*rand)).'-'.
 2091:                   sprintf("%lx",int(100000*rand));
 2092:        $newkey=~s/1/g/g; # folks mix up 1 and l
 2093:        $newkey=~s/0/h/g; # and also 0 and O
 2094:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 2095:        if ($existing{$newkey}) {
 2096:            $i--;
 2097:        } else {
 2098: 	  if (&put('accesskeys',
 2099:               { $newkey => '# generated '.localtime().
 2100:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 2101:                            '; '.$logentry },
 2102: 		   $cdom,$cnum) eq 'ok') {
 2103:               $total++;
 2104: 	  }
 2105:        }
 2106:     }
 2107:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 2108:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 2109:     return $total;
 2110: }
 2111: 
 2112: # ------------------------------------------------------- Validate an accesskey
 2113: 
 2114: sub validate_access_key {
 2115:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 2116:     $cdom=
 2117:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2118:     $cnum=
 2119:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2120:     $udom=$env{'user.domain'} unless (defined($udom));
 2121:     $uname=$env{'user.name'} unless (defined($uname));
 2122:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2123:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 2124: }
 2125: 
 2126: # ------------------------------------- Find the section of student in a course
 2127: sub devalidate_getsection_cache {
 2128:     my ($udom,$unam,$courseid)=@_;
 2129:     my $hashid="$udom:$unam:$courseid";
 2130:     &devalidate_cache_new('getsection',$hashid);
 2131: }
 2132: 
 2133: sub courseid_to_courseurl {
 2134:     my ($courseid) = @_;
 2135:     #already url style courseid
 2136:     return $courseid if ($courseid =~ m{^/});
 2137: 
 2138:     if (exists($env{'course.'.$courseid.'.num'})) {
 2139: 	my $cnum = $env{'course.'.$courseid.'.num'};
 2140: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 2141: 	return "/$cdom/$cnum";
 2142:     }
 2143: 
 2144:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 2145:     if (exists($courseinfo{'num'})) {
 2146: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 2147:     }
 2148: 
 2149:     return undef;
 2150: }
 2151: 
 2152: sub getsection {
 2153:     my ($udom,$unam,$courseid)=@_;
 2154:     my $cachetime=1800;
 2155: 
 2156:     my $hashid="$udom:$unam:$courseid";
 2157:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 2158:     if (defined($cached)) { return $result; }
 2159: 
 2160:     my %Pending; 
 2161:     my %Expired;
 2162:     #
 2163:     # Each role can either have not started yet (pending), be active, 
 2164:     #    or have expired.
 2165:     #
 2166:     # If there is an active role, we are done.
 2167:     #
 2168:     # If there is more than one role which has not started yet, 
 2169:     #     choose the one which will start sooner
 2170:     # If there is one role which has not started yet, return it.
 2171:     #
 2172:     # If there is more than one expired role, choose the one which ended last.
 2173:     # If there is a role which has expired, return it.
 2174:     #
 2175:     $courseid = &courseid_to_courseurl($courseid);
 2176:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 2177:     foreach my $key (keys(%roleshash)) {
 2178:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 2179:         my $section=$1;
 2180:         if ($key eq $courseid.'_st') { $section=''; }
 2181:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 2182:         my $now=time;
 2183:         if (defined($end) && $end && ($now > $end)) {
 2184:             $Expired{$end}=$section;
 2185:             next;
 2186:         }
 2187:         if (defined($start) && $start && ($now < $start)) {
 2188:             $Pending{$start}=$section;
 2189:             next;
 2190:         }
 2191:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 2192:     }
 2193:     #
 2194:     # Presumedly there will be few matching roles from the above
 2195:     # loop and the sorting time will be negligible.
 2196:     if (scalar(keys(%Pending))) {
 2197:         my ($time) = sort {$a <=> $b} keys(%Pending);
 2198:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 2199:     } 
 2200:     if (scalar(keys(%Expired))) {
 2201:         my @sorted = sort {$a <=> $b} keys(%Expired);
 2202:         my $time = pop(@sorted);
 2203:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 2204:     }
 2205:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 2206: }
 2207: 
 2208: sub save_cache {
 2209:     &purge_remembered();
 2210:     #&Apache::loncommon::validate_page();
 2211:     undef(%env);
 2212:     undef($env_loaded);
 2213: }
 2214: 
 2215: my $to_remember=-1;
 2216: my %remembered;
 2217: my %accessed;
 2218: my $kicks=0;
 2219: my $hits=0;
 2220: sub make_key {
 2221:     my ($name,$id) = @_;
 2222:     if (length($id) > 65 
 2223: 	&& length(&escape($id)) > 200) {
 2224: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 2225:     }
 2226:     return &escape($name.':'.$id);
 2227: }
 2228: 
 2229: sub devalidate_cache_new {
 2230:     my ($name,$id,$debug) = @_;
 2231:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 2232:     $id=&make_key($name,$id);
 2233:     $memcache->delete($id);
 2234:     delete($remembered{$id});
 2235:     delete($accessed{$id});
 2236: }
 2237: 
 2238: sub is_cached_new {
 2239:     my ($name,$id,$debug) = @_;
 2240:     $id=&make_key($name,$id);
 2241:     if (exists($remembered{$id})) {
 2242: 	if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
 2243: 	$accessed{$id}=[&gettimeofday()];
 2244: 	$hits++;
 2245: 	return ($remembered{$id},1);
 2246:     }
 2247:     my $value = $memcache->get($id);
 2248:     if (!(defined($value))) {
 2249: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 2250: 	return (undef,undef);
 2251:     }
 2252:     if ($value eq '__undef__') {
 2253: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 2254: 	$value=undef;
 2255:     }
 2256:     &make_room($id,$value,$debug);
 2257:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 2258:     return ($value,1);
 2259: }
 2260: 
 2261: sub do_cache_new {
 2262:     my ($name,$id,$value,$time,$debug) = @_;
 2263:     $id=&make_key($name,$id);
 2264:     my $setvalue=$value;
 2265:     if (!defined($setvalue)) {
 2266: 	$setvalue='__undef__';
 2267:     }
 2268:     if (!defined($time) ) {
 2269: 	$time=600;
 2270:     }
 2271:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 2272:     my $result = $memcache->set($id,$setvalue,$time);
 2273:     if (! $result) {
 2274: 	&logthis("caching of id -> $id  failed");
 2275: 	$memcache->disconnect_all();
 2276:     }
 2277:     # need to make a copy of $value
 2278:     &make_room($id,$value,$debug);
 2279:     return $value;
 2280: }
 2281: 
 2282: sub make_room {
 2283:     my ($id,$value,$debug)=@_;
 2284: 
 2285:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
 2286:                                     : $value;
 2287:     if ($to_remember<0) { return; }
 2288:     $accessed{$id}=[&gettimeofday()];
 2289:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 2290:     my $to_kick;
 2291:     my $max_time=0;
 2292:     foreach my $other (keys(%accessed)) {
 2293: 	if (&tv_interval($accessed{$other}) > $max_time) {
 2294: 	    $to_kick=$other;
 2295: 	    $max_time=&tv_interval($accessed{$other});
 2296: 	}
 2297:     }
 2298:     delete($remembered{$to_kick});
 2299:     delete($accessed{$to_kick});
 2300:     $kicks++;
 2301:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 2302:     return;
 2303: }
 2304: 
 2305: sub purge_remembered {
 2306:     #&logthis("Tossing ".scalar(keys(%remembered)));
 2307:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 2308:     undef(%remembered);
 2309:     undef(%accessed);
 2310: }
 2311: # ------------------------------------- Read an entry from a user's environment
 2312: 
 2313: sub userenvironment {
 2314:     my ($udom,$unam,@what)=@_;
 2315:     my $items;
 2316:     foreach my $item (@what) {
 2317:         $items.=&escape($item).'&';
 2318:     }
 2319:     $items=~s/\&$//;
 2320:     my %returnhash=();
 2321:     my $uhome = &homeserver($unam,$udom);
 2322:     unless ($uhome eq 'no_host') {
 2323:         my @answer=split(/\&/, 
 2324:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 2325:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 2326:             return %returnhash;
 2327:         }
 2328:         my $i;
 2329:         for ($i=0;$i<=$#what;$i++) {
 2330: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 2331:         }
 2332:     }
 2333:     return %returnhash;
 2334: }
 2335: 
 2336: # ---------------------------------------------------------- Get a studentphoto
 2337: sub studentphoto {
 2338:     my ($udom,$unam,$ext) = @_;
 2339:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2340:     if (defined($env{'request.course.id'})) {
 2341:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 2342:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 2343:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 2344:             } else {
 2345:                 my ($result,$perm_reqd)=
 2346: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2347:                 if ($result eq 'ok') {
 2348:                     if (!($perm_reqd eq 'yes')) {
 2349:                         return(&retrievestudentphoto($udom,$unam,$ext));
 2350:                     }
 2351:                 }
 2352:             }
 2353:         }
 2354:     } else {
 2355:         my ($result,$perm_reqd) = 
 2356: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2357:         if ($result eq 'ok') {
 2358:             if (!($perm_reqd eq 'yes')) {
 2359:                 return(&retrievestudentphoto($udom,$unam,$ext));
 2360:             }
 2361:         }
 2362:     }
 2363:     return '/adm/lonKaputt/lonlogo_broken.gif';
 2364: }
 2365: 
 2366: sub retrievestudentphoto {
 2367:     my ($udom,$unam,$ext,$type) = @_;
 2368:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2369:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 2370:     if ($ret eq 'ok') {
 2371:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 2372:         if ($type eq 'thumbnail') {
 2373:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 2374:         }
 2375:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 2376:         return $tokenurl;
 2377:     } else {
 2378:         if ($type eq 'thumbnail') {
 2379:             return '/adm/lonKaputt/genericstudent_tn.gif';
 2380:         } else { 
 2381:             return '/adm/lonKaputt/lonlogo_broken.gif';
 2382:         }
 2383:     }
 2384: }
 2385: 
 2386: # -------------------------------------------------------------------- New chat
 2387: 
 2388: sub chatsend {
 2389:     my ($newentry,$anon,$group)=@_;
 2390:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 2391:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2392:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 2393:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 2394: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 2395: 		   &escape($newentry)).':'.$group,$chome);
 2396: }
 2397: 
 2398: # ------------------------------------------ Find current version of a resource
 2399: 
 2400: sub getversion {
 2401:     my $fname=&clutter(shift);
 2402:     unless ($fname=~/^\/res\//) { return -1; }
 2403:     return &currentversion(&filelocation('',$fname));
 2404: }
 2405: 
 2406: sub currentversion {
 2407:     my $fname=shift;
 2408:     my $author=$fname;
 2409:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2410:     my ($udom,$uname)=split(/\//,$author);
 2411:     my $home=&homeserver($uname,$udom);
 2412:     if ($home eq 'no_host') { 
 2413:         return -1; 
 2414:     }
 2415:     my $answer=&reply("currentversion:$fname",$home);
 2416:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 2417: 	return -1;
 2418:     }
 2419:     return $answer;
 2420: }
 2421: 
 2422: #
 2423: # Return special version number of resource if set by override, empty otherwise
 2424: #
 2425: sub usedversion {
 2426:     my $fname=shift;
 2427:     unless ($fname) { $fname=$env{'request.uri'}; }
 2428:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 2429:     if ($urlversion) { return $urlversion; }
 2430:     return '';
 2431: }
 2432: 
 2433: # ----------------------------- Subscribe to a resource, return URL if possible
 2434: 
 2435: sub subscribe {
 2436:     my $fname=shift;
 2437:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 2438:     $fname=~s/[\n\r]//g;
 2439:     my $author=$fname;
 2440:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2441:     my ($udom,$uname)=split(/\//,$author);
 2442:     my $home=homeserver($uname,$udom);
 2443:     if ($home eq 'no_host') {
 2444:         return 'not_found';
 2445:     }
 2446:     my $answer=reply("sub:$fname",$home);
 2447:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 2448: 	$answer.=' by '.$home;
 2449:     }
 2450:     return $answer;
 2451: }
 2452:     
 2453: # -------------------------------------------------------------- Replicate file
 2454: 
 2455: sub repcopy {
 2456:     my $filename=shift;
 2457:     $filename=~s/\/+/\//g;
 2458:     my $londocroot = $perlvar{'lonDocRoot'};
 2459:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 2460:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
 2461:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 2462: 	$filename=~m{^/*(uploaded|editupload)/}) {
 2463: 	return &repcopy_userfile($filename);
 2464:     }
 2465:     $filename=~s/[\n\r]//g;
 2466:     my $transname="$filename.in.transfer";
 2467: # FIXME: this should flock
 2468:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 2469:     my $remoteurl=subscribe($filename);
 2470:     if ($remoteurl =~ /^con_lost by/) {
 2471: 	   &logthis("Subscribe returned $remoteurl: $filename");
 2472:            return 'unavailable';
 2473:     } elsif ($remoteurl eq 'not_found') {
 2474: 	   #&logthis("Subscribe returned not_found: $filename");
 2475: 	   return 'not_found';
 2476:     } elsif ($remoteurl =~ /^rejected by/) {
 2477: 	   &logthis("Subscribe returned $remoteurl: $filename");
 2478:            return 'forbidden';
 2479:     } elsif ($remoteurl eq 'directory') {
 2480:            return 'ok';
 2481:     } else {
 2482:         my $author=$filename;
 2483:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2484:         my ($udom,$uname)=split(/\//,$author);
 2485:         my $home=homeserver($uname,$udom);
 2486:         unless ($home eq $perlvar{'lonHostID'}) {
 2487:            my @parts=split(/\//,$filename);
 2488:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 2489:            if ($path ne "$londocroot/res") {
 2490:                &logthis("Malconfiguration for replication: $filename");
 2491: 	       return 'bad_request';
 2492:            }
 2493:            my $count;
 2494:            for ($count=5;$count<$#parts;$count++) {
 2495:                $path.="/$parts[$count]";
 2496:                if ((-e $path)!=1) {
 2497: 		   mkdir($path,0777);
 2498:                }
 2499:            }
 2500:            my $ua=new LWP::UserAgent;
 2501:            my $request=new HTTP::Request('GET',"$remoteurl");
 2502:            my $response=$ua->request($request,$transname);
 2503:            if ($response->is_error()) {
 2504: 	       unlink($transname);
 2505:                my $message=$response->status_line;
 2506:                &logthis("<font color=\"blue\">WARNING:"
 2507:                        ." LWP get: $message: $filename</font>");
 2508:                return 'unavailable';
 2509:            } else {
 2510: 	       if ($remoteurl!~/\.meta$/) {
 2511:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 2512:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 2513:                   if ($mresponse->is_error()) {
 2514: 		      unlink($filename.'.meta');
 2515:                       &logthis(
 2516:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 2517:                   }
 2518: 	       }
 2519:                rename($transname,$filename);
 2520:                return 'ok';
 2521:            }
 2522:        }
 2523:     }
 2524: }
 2525: 
 2526: # ------------------------------------------------ Get server side include body
 2527: sub ssi_body {
 2528:     my ($filelink,%form)=@_;
 2529:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 2530:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 2531:     }
 2532:     my $output='';
 2533:     my $response;
 2534:     if ($filelink=~/^https?\:/) {
 2535:        ($output,$response)=&externalssi($filelink);
 2536:     } else {
 2537:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 2538:        $filelink .= 'inhibitmenu=yes';
 2539:        ($output,$response)=&ssi($filelink,%form);
 2540:     }
 2541:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 2542:     $output=~s/^.*?\<body[^\>]*\>//si;
 2543:     $output=~s/\<\/body\s*\>.*?$//si;
 2544:     if (wantarray) {
 2545:         return ($output, $response);
 2546:     } else {
 2547:         return $output;
 2548:     }
 2549: }
 2550: 
 2551: # --------------------------------------------------------- Server Side Include
 2552: 
 2553: sub absolute_url {
 2554:     my ($host_name) = @_;
 2555:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 2556:     if ($host_name eq '') {
 2557: 	$host_name = $ENV{'SERVER_NAME'};
 2558:     }
 2559:     return $protocol.$host_name;
 2560: }
 2561: 
 2562: #
 2563: #   Server side include.
 2564: # Parameters:
 2565: #  fn     Possibly encrypted resource name/id.
 2566: #  form   Hash that describes how the rendering should be done
 2567: #         and other things.
 2568: # Returns:
 2569: #   Scalar context: The content of the response.
 2570: #   Array context:  2 element list of the content and the full response object.
 2571: #     
 2572: sub ssi {
 2573: 
 2574:     my ($fn,%form)=@_;
 2575:     my $ua=new LWP::UserAgent;
 2576:     my $request;
 2577: 
 2578:     $form{'no_update_last_known'}=1;
 2579:     &Apache::lonenc::check_encrypt(\$fn);
 2580:     if (%form) {
 2581:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 2582:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
 2583:     } else {
 2584:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 2585:     }
 2586: 
 2587:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 2588:     my $response= $ua->request($request);
 2589:     my $content = $response->content;
 2590: 
 2591: 
 2592:     if (wantarray) {
 2593: 	return ($content, $response);
 2594:     } else {
 2595: 	return $content;
 2596:     }
 2597: }
 2598: 
 2599: sub externalssi {
 2600:     my ($url)=@_;
 2601:     my $ua=new LWP::UserAgent;
 2602:     my $request=new HTTP::Request('GET',$url);
 2603:     my $response=$ua->request($request);
 2604:     if (wantarray) {
 2605:         return ($response->content, $response);
 2606:     } else {
 2607:         return $response->content;
 2608:     }
 2609: }
 2610: 
 2611: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 2612: 
 2613: sub allowuploaded {
 2614:     my ($srcurl,$url)=@_;
 2615:     $url=&clutter(&declutter($url));
 2616:     my $dir=$url;
 2617:     $dir=~s/\/[^\/]+$//;
 2618:     my %httpref=();
 2619:     my $httpurl=&hreflocation('',$url);
 2620:     $httpref{'httpref.'.$httpurl}=$srcurl;
 2621:     &Apache::lonnet::appenv(\%httpref);
 2622: }
 2623: 
 2624: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 2625: # input: action, courseID, current domain, intended
 2626: #        path to file, source of file, instruction to parse file for objects,
 2627: #        ref to hash for embedded objects,
 2628: #        ref to hash for codebase of java objects.
 2629: #        reference to scalar to accommodate mime type determined
 2630: #          from File::MMagic if $parser = parse.
 2631: #
 2632: # output: url to file (if action was uploaddoc), 
 2633: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 2634: #
 2635: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 2636: # course.
 2637: #
 2638: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2639: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 2640: #          course's home server.
 2641: #
 2642: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 2643: #          be copied from $source (current location) to 
 2644: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2645: #         and will then be copied to
 2646: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 2647: #         course's home server.
 2648: #
 2649: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2650: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 2651: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2652: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 2653: #         in course's home server.
 2654: #
 2655: 
 2656: sub process_coursefile {
 2657:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 2658:         $mimetype)=@_;
 2659:     my $fetchresult;
 2660:     my $home=&homeserver($docuname,$docudom);
 2661:     if ($action eq 'propagate') {
 2662:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2663: 			     $home);
 2664:     } else {
 2665:         my $fpath = '';
 2666:         my $fname = $file;
 2667:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 2668:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 2669:         my $filepath = &build_filepath($fpath);
 2670:         if ($action eq 'copy') {
 2671:             if ($source eq '') {
 2672:                 $fetchresult = 'no source file';
 2673:                 return $fetchresult;
 2674:             } else {
 2675:                 my $destination = $filepath.'/'.$fname;
 2676:                 rename($source,$destination);
 2677:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2678:                                  $home);
 2679:             }
 2680:         } elsif ($action eq 'uploaddoc') {
 2681:             open(my $fh,'>'.$filepath.'/'.$fname);
 2682:             print $fh $env{'form.'.$source};
 2683:             close($fh);
 2684:             if ($parser eq 'parse') {
 2685:                 my $mm = new File::MMagic;
 2686:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 2687:                 if ($type eq 'text/html') {
 2688:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 2689:                     unless ($parse_result eq 'ok') {
 2690:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 2691:                     }
 2692:                 }
 2693:                 if (ref($mimetype)) {
 2694:                     $$mimetype = $type;
 2695:                 } 
 2696:             }
 2697:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2698:                                  $home);
 2699:             if ($fetchresult eq 'ok') {
 2700:                 return '/uploaded/'.$fpath.'/'.$fname;
 2701:             } else {
 2702:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2703:                         ' to host '.$home.': '.$fetchresult);
 2704:                 return '/adm/notfound.html';
 2705:             }
 2706:         }
 2707:     }
 2708:     unless ( $fetchresult eq 'ok') {
 2709:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2710:              ' to host '.$home.': '.$fetchresult);
 2711:     }
 2712:     return $fetchresult;
 2713: }
 2714: 
 2715: sub build_filepath {
 2716:     my ($fpath) = @_;
 2717:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 2718:     unless ($fpath eq '') {
 2719:         my @parts=split('/',$fpath);
 2720:         foreach my $part (@parts) {
 2721:             $filepath.= '/'.$part;
 2722:             if ((-e $filepath)!=1) {
 2723:                 mkdir($filepath,0777);
 2724:             }
 2725:         }
 2726:     }
 2727:     return $filepath;
 2728: }
 2729: 
 2730: sub store_edited_file {
 2731:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 2732:     my $file = $primary_url;
 2733:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 2734:     my $fpath = '';
 2735:     my $fname = $file;
 2736:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 2737:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 2738:     my $filepath = &build_filepath($fpath);
 2739:     open(my $fh,'>'.$filepath.'/'.$fname);
 2740:     print $fh $content;
 2741:     close($fh);
 2742:     my $home=&homeserver($docuname,$docudom);
 2743:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2744: 			  $home);
 2745:     if ($$fetchresult eq 'ok') {
 2746:         return '/uploaded/'.$fpath.'/'.$fname;
 2747:     } else {
 2748:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2749: 		 ' to host '.$home.': '.$$fetchresult);
 2750:         return '/adm/notfound.html';
 2751:     }
 2752: }
 2753: 
 2754: sub clean_filename {
 2755:     my ($fname,$args)=@_;
 2756: # Replace Windows backslashes by forward slashes
 2757:     $fname=~s/\\/\//g;
 2758:     if (!$args->{'keep_path'}) {
 2759:         # Get rid of everything but the actual filename
 2760: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 2761:     }
 2762: # Replace spaces by underscores
 2763:     $fname=~s/\s+/\_/g;
 2764: # Replace all other weird characters by nothing
 2765:     $fname=~s{[^/\w\.\-]}{}g;
 2766: # Replace all .\d. sequences with _\d. so they no longer look like version
 2767: # numbers
 2768:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 2769:     return $fname;
 2770: }
 2771: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 2772: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 2773: # image with the same aspect ratio as the original, but with dimensions which do 
 2774: # not exceed $resizewidth and $resizeheight.
 2775:  
 2776: sub resizeImage {
 2777:     my ($img_path,$resizewidth,$resizeheight) = @_;
 2778:     my $ima = Image::Magick->new;
 2779:     my $resized;
 2780:     if (-e $img_path) {
 2781:         $ima->Read($img_path);
 2782:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 2783:             my $width = $ima->Get('width');
 2784:             my $height = $ima->Get('height');
 2785:             if ($width > $resizewidth) {
 2786: 	        my $factor = $width/$resizewidth;
 2787:                 my $newheight = $height/$factor;
 2788:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 2789:                 $resized = 1;
 2790:             }
 2791:         }
 2792:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 2793:             my $width = $ima->Get('width');
 2794:             my $height = $ima->Get('height');
 2795:             if ($height > $resizeheight) {
 2796:                 my $factor = $height/$resizeheight;
 2797:                 my $newwidth = $width/$factor;
 2798:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 2799:                 $resized = 1;
 2800:             }
 2801:         }
 2802:         if ($resized) {
 2803:             $ima->Write($img_path);
 2804:         }
 2805:     }
 2806:     return;
 2807: }
 2808: 
 2809: # --------------- Take an uploaded file and put it into the userfiles directory
 2810: # input: $formname - the contents of the file are in $env{"form.$formname"}
 2811: #                    the desired filename is in $env{"form.$formname.filename"}
 2812: #        $context - possible values: coursedoc, existingfile, overwrite, 
 2813: #                                    canceloverwrite, or ''. 
 2814: #                   if 'coursedoc': upload to the current course
 2815: #                   if 'existingfile': write file to tmp/overwrites directory 
 2816: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 2817: #                   $context is passed as argument to &finishuserfileupload
 2818: #        $subdir - directory in userfile to store the file into
 2819: #        $parser - instruction to parse file for objects ($parser = parse)    
 2820: #        $allfiles - reference to hash for embedded objects
 2821: #        $codebase - reference to hash for codebase of java objects
 2822: #        $desuname - username for permanent storage of uploaded file
 2823: #        $dsetudom - domain for permanaent storage of uploaded file
 2824: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 2825: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 2826: #        $resizewidth - width (pixels) to which to resize uploaded image
 2827: #        $resizeheight - height (pixels) to which to resize uploaded image
 2828: #        $mimetype - reference to scalar to accommodate mime type determined
 2829: #                    from File::MMagic.
 2830: # 
 2831: # output: url of file in userspace, or error: <message> 
 2832: #             or /adm/notfound.html if failure to upload occurse
 2833: 
 2834: sub userfileupload {
 2835:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 2836:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 2837:     if (!defined($subdir)) { $subdir='unknown'; }
 2838:     my $fname=$env{'form.'.$formname.'.filename'};
 2839:     $fname=&clean_filename($fname);
 2840:     # See if there is anything left
 2841:     unless ($fname) { return 'error: no uploaded file'; }
 2842:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 2843:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 2844:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 2845:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 2846:         my $now = time;
 2847:         my $filepath;
 2848:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 2849:              $filepath = 'tmp/helprequests/'.$now;
 2850:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 2851:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 2852:                          '_'.$env{'user.domain'}.'/pending';
 2853:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 2854:             my ($docuname,$docudom);
 2855:             if ($destudom) {
 2856:                 $docudom = $destudom;
 2857:             } else {
 2858:                 $docudom = $env{'user.domain'};
 2859:             }
 2860:             if ($destuname) {
 2861:                 $docuname = $destuname;
 2862:             } else {
 2863:                 $docuname = $env{'user.name'};
 2864:             }
 2865:             if (exists($env{'form.group'})) {
 2866:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2867:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2868:             }
 2869:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 2870:             if ($context eq 'canceloverwrite') {
 2871:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 2872:                 if (-e  $tempfile) {
 2873:                     my @info = stat($tempfile);
 2874:                     if ($info[9] eq $env{'form.timestamp'}) {
 2875:                         unlink($tempfile);
 2876:                     }
 2877:                 }
 2878:                 return;
 2879:             }
 2880:         }
 2881:         # Create the directory if not present
 2882:         my @parts=split(/\//,$filepath);
 2883:         my $fullpath = $perlvar{'lonDaemons'};
 2884:         for (my $i=0;$i<@parts;$i++) {
 2885:             $fullpath .= '/'.$parts[$i];
 2886:             if ((-e $fullpath)!=1) {
 2887:                 mkdir($fullpath,0777);
 2888:             }
 2889:         }
 2890:         open(my $fh,'>'.$fullpath.'/'.$fname);
 2891:         print $fh $env{'form.'.$formname};
 2892:         close($fh);
 2893:         if ($context eq 'existingfile') {
 2894:             my @info = stat($fullpath.'/'.$fname);
 2895:             return ($fullpath.'/'.$fname,$info[9]);
 2896:         } else {
 2897:             return $fullpath.'/'.$fname;
 2898:         }
 2899:     }
 2900:     if ($subdir eq 'scantron') {
 2901:         $fname = 'scantron_orig_'.$fname;
 2902:     } else {
 2903:         $fname="$subdir/$fname";
 2904:     }
 2905:     if ($context eq 'coursedoc') {
 2906: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2907: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2908:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 2909:             return &finishuserfileupload($docuname,$docudom,
 2910: 					 $formname,$fname,$parser,$allfiles,
 2911: 					 $codebase,$thumbwidth,$thumbheight,
 2912:                                          $resizewidth,$resizeheight,$context,$mimetype);
 2913:         } else {
 2914:             $fname=$env{'form.folder'}.'/'.$fname;
 2915:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 2916: 				       $fname,$formname,$parser,
 2917: 				       $allfiles,$codebase,$mimetype);
 2918:         }
 2919:     } elsif (defined($destuname)) {
 2920:         my $docuname=$destuname;
 2921:         my $docudom=$destudom;
 2922: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 2923: 				     $parser,$allfiles,$codebase,
 2924:                                      $thumbwidth,$thumbheight,
 2925:                                      $resizewidth,$resizeheight,$context,$mimetype);
 2926:     } else {
 2927:         my $docuname=$env{'user.name'};
 2928:         my $docudom=$env{'user.domain'};
 2929:         if (exists($env{'form.group'})) {
 2930:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2931:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2932:         }
 2933: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 2934: 				     $parser,$allfiles,$codebase,
 2935:                                      $thumbwidth,$thumbheight,
 2936:                                      $resizewidth,$resizeheight,$context,$mimetype);
 2937:     }
 2938: }
 2939: 
 2940: sub finishuserfileupload {
 2941:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 2942:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 2943:     my $path=$docudom.'/'.$docuname.'/';
 2944:     my $filepath=$perlvar{'lonDocRoot'};
 2945:   
 2946:     my ($fnamepath,$file,$fetchthumb);
 2947:     $file=$fname;
 2948:     if ($fname=~m|/|) {
 2949:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 2950: 	$path.=$fnamepath.'/';
 2951:     }
 2952:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 2953:     my $count;
 2954:     for ($count=4;$count<=$#parts;$count++) {
 2955:         $filepath.="/$parts[$count]";
 2956:         if ((-e $filepath)!=1) {
 2957: 	    mkdir($filepath,0777);
 2958:         }
 2959:     }
 2960: 
 2961: # Save the file
 2962:     {
 2963: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 2964: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 2965: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 2966: 	    return '/adm/notfound.html';
 2967: 	}
 2968:         if ($context eq 'overwrite') {
 2969:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 2970:             my $target = $filepath.'/'.$file;
 2971:             if (-e $source) {
 2972:                 my @info = stat($source);
 2973:                 if ($info[9] eq $env{'form.timestamp'}) {   
 2974:                     unless (&File::Copy::move($source,$target)) {
 2975:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 2976:                         return "Moving from $source failed";
 2977:                     }
 2978:                 } else {
 2979:                     return "Temporary file: $source had unexpected date/time for last modification";
 2980:                 }
 2981:             } else {
 2982:                 return "Temporary file: $source missing";
 2983:             }
 2984:         } elsif (!print FH ($env{'form.'.$formname})) {
 2985: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 2986: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 2987: 	    return '/adm/notfound.html';
 2988: 	}
 2989: 	close(FH);
 2990:         if ($resizewidth && $resizeheight) {
 2991:             my $mm = new File::MMagic;
 2992:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 2993:             if ($mime_type =~ m{^image/}) {
 2994: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 2995:             }  
 2996: 	}
 2997:     }
 2998:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 2999:         if (ref($mimetype)) {
 3000:             if ($$mimetype eq '') {
 3001:                 my $mm = new File::MMagic;
 3002:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 3003:                 $$mimetype = $type;
 3004:             }
 3005:         }
 3006:     }
 3007:     if ($parser eq 'parse') {
 3008:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 3009:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 3010:                                                        $allfiles,$codebase);
 3011:             unless ($parse_result eq 'ok') {
 3012:                 &logthis('Failed to parse '.$filepath.$file.
 3013: 	   	         ' for embedded media: '.$parse_result); 
 3014:             }
 3015:         }
 3016:     }
 3017:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 3018:         my $input = $filepath.'/'.$file;
 3019:         my $output = $filepath.'/'.'tn-'.$file;
 3020:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 3021:         system("convert -sample $thumbsize $input $output");
 3022:         if (-e $filepath.'/'.'tn-'.$file) {
 3023:             $fetchthumb  = 1; 
 3024:         }
 3025:     }
 3026:  
 3027: # Notify homeserver to grep it
 3028: #
 3029:     my $docuhome=&homeserver($docuname,$docudom);	
 3030:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 3031:     if ($fetchresult eq 'ok') {
 3032:         if ($fetchthumb) {
 3033:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 3034:             if ($thumbresult ne 'ok') {
 3035:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 3036:                          $docuhome.': '.$thumbresult);
 3037:             }
 3038:         }
 3039: #
 3040: # Return the URL to it
 3041:         return '/uploaded/'.$path.$file;
 3042:     } else {
 3043:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 3044: 		 ': '.$fetchresult);
 3045:         return '/adm/notfound.html';
 3046:     }
 3047: }
 3048: 
 3049: sub extract_embedded_items {
 3050:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 3051:     my @state = ();
 3052:     my (%lastids,%related,%shockwave,%flashvars);
 3053:     my %javafiles = (
 3054:                       codebase => '',
 3055:                       code => '',
 3056:                       archive => ''
 3057:                     );
 3058:     my %mediafiles = (
 3059:                       src => '',
 3060:                       movie => '',
 3061:                      );
 3062:     my $p;
 3063:     if ($content) {
 3064:         $p = HTML::LCParser->new($content);
 3065:     } else {
 3066:         $p = HTML::LCParser->new($fullpath);
 3067:     }
 3068:     while (my $t=$p->get_token()) {
 3069: 	if ($t->[0] eq 'S') {
 3070: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 3071: 	    push(@state, $tagname);
 3072:             if (lc($tagname) eq 'allow') {
 3073:                 &add_filetype($allfiles,$attr->{'src'},'src');
 3074:             }
 3075: 	    if (lc($tagname) eq 'img') {
 3076: 		&add_filetype($allfiles,$attr->{'src'},'src');
 3077: 	    }
 3078: 	    if (lc($tagname) eq 'a') {
 3079: 		&add_filetype($allfiles,$attr->{'href'},'href');
 3080: 	    }
 3081:             if (lc($tagname) eq 'script') {
 3082:                 my $src;
 3083:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 3084:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 3085:                 } else {
 3086:                     if ($attr->{'src'} ne '') {
 3087:                         $src = $attr->{'src'};
 3088:                         &add_filetype($allfiles,$src,'src');
 3089:                     }
 3090:                 }
 3091:                 my $text = $p->get_trimmed_text();
 3092:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 3093:                     my @swfargs = split(/,/,$1);
 3094:                     foreach my $item (@swfargs) {
 3095:                         $item =~ s/["']//g;
 3096:                         $item =~ s/^\s+//;
 3097:                         $item =~ s/\s+$//;
 3098:                     }
 3099:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 3100:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 3101:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 3102:                         } else {
 3103:                             $related{$swfargs[0]} = [$swfargs[2]];
 3104:                         }
 3105:                     }
 3106:                 }
 3107:             }
 3108:             if (lc($tagname) eq 'link') {
 3109:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 3110:                     &add_filetype($allfiles,$attr->{'href'},'href');
 3111:                 }
 3112:             }
 3113: 	    if (lc($tagname) eq 'object' ||
 3114: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 3115: 		foreach my $item (keys(%javafiles)) {
 3116: 		    $javafiles{$item} = '';
 3117: 		}
 3118:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 3119:                     $lastids{lc($tagname)} = $attr->{'id'};
 3120:                 }
 3121: 	    }
 3122: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 3123: 		my $name = lc($attr->{'name'});
 3124: 		foreach my $item (keys(%javafiles)) {
 3125: 		    if ($name eq $item) {
 3126: 			$javafiles{$item} = $attr->{'value'};
 3127: 			last;
 3128: 		    }
 3129: 		}
 3130:                 my $pathfrom;
 3131: 		foreach my $item (keys(%mediafiles)) {
 3132: 		    if ($name eq $item) {
 3133:                         $pathfrom = $attr->{'value'};
 3134:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 3135: 			&add_filetype($allfiles,$pathfrom,$name);
 3136: 			last;
 3137: 		    }
 3138: 		}
 3139:                 if ($name eq 'flashvars') {
 3140:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 3141:                 }
 3142:                 if ($pathfrom ne '') {
 3143:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 3144:                                          $pathfrom);
 3145:                 }
 3146: 	    }
 3147: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 3148: 		foreach my $item (keys(%javafiles)) {
 3149: 		    if ($attr->{$item}) {
 3150: 			$javafiles{$item} = $attr->{$item};
 3151: 			last;
 3152: 		    }
 3153: 		}
 3154: 		foreach my $item (keys(%mediafiles)) {
 3155: 		    if ($attr->{$item}) {
 3156: 			&add_filetype($allfiles,$attr->{$item},$item);
 3157: 			last;
 3158: 		    }
 3159: 		}
 3160:                 if (lc($tagname) eq 'embed') {
 3161:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 3162:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 3163:                                              $attr->{'src'});
 3164:                     }
 3165:                 }
 3166: 	    }
 3167:             if ($t->[4] =~ m{/>$}) {
 3168:                 pop(@state);  
 3169:             }
 3170: 	} elsif ($t->[0] eq 'E') {
 3171: 	    my ($tagname) = ($t->[1]);
 3172: 	    if ($javafiles{'codebase'} ne '') {
 3173: 		$javafiles{'codebase'} .= '/';
 3174: 	    }  
 3175: 	    if (lc($tagname) eq 'applet' ||
 3176: 		lc($tagname) eq 'object' ||
 3177: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 3178: 		) {
 3179: 		foreach my $item (keys(%javafiles)) {
 3180: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 3181: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 3182: 			&add_filetype($allfiles,$file,$item);
 3183: 		    }
 3184: 		}
 3185: 	    } 
 3186: 	    pop @state;
 3187: 	}
 3188:     }
 3189:     foreach my $id (sort(keys(%flashvars))) {
 3190:         if ($shockwave{$id} ne '') {
 3191:             my @pairs = split(/\&/,$flashvars{$id});
 3192:             foreach my $pair (@pairs) {
 3193:                 my ($key,$value) = split(/\=/,$pair);
 3194:                 if ($key eq 'thumb') {
 3195:                     &add_filetype($allfiles,$value,$key);
 3196:                 } elsif ($key eq 'content') {
 3197:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 3198:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 3199:                     if ($ext ne '') {
 3200:                         &add_filetype($allfiles,$path.$value,$ext);
 3201:                     }
 3202:                 }
 3203:             }
 3204:         }
 3205:     }
 3206:     return 'ok';
 3207: }
 3208: 
 3209: sub add_filetype {
 3210:     my ($allfiles,$file,$type)=@_;
 3211:     if (exists($allfiles->{$file})) {
 3212: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 3213: 	    push(@{$allfiles->{$file}}, &escape($type));
 3214: 	}
 3215:     } else {
 3216: 	@{$allfiles->{$file}} = (&escape($type));
 3217:     }
 3218: }
 3219: 
 3220: sub embedded_dependency {
 3221:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 3222:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 3223:         if (($identifier ne '') &&
 3224:             (ref($related->{$identifier}) eq 'ARRAY') &&
 3225:             ($pathfrom ne '')) {
 3226:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 3227:             foreach my $dep (@{$related->{$identifier}}) {
 3228:                 &add_filetype($allfiles,$path.$dep,'object');
 3229:             }
 3230:         }
 3231:     }
 3232:     return;
 3233: }
 3234: 
 3235: sub removeuploadedurl {
 3236:     my ($url)=@_;	
 3237:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 3238:     return &removeuserfile($uname,$udom,$fname);
 3239: }
 3240: 
 3241: sub removeuserfile {
 3242:     my ($docuname,$docudom,$fname)=@_;
 3243:     my $home=&homeserver($docuname,$docudom);    
 3244:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 3245:     if ($result eq 'ok') {	
 3246:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 3247:             my $metafile = $fname.'.meta';
 3248:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 3249: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 3250:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 3251:             my $sqlresult = 
 3252:                 &update_portfolio_table($docuname,$docudom,$file,
 3253:                                         'portfolio_metadata',$group,
 3254:                                         'delete');
 3255:         }
 3256:     }
 3257:     return $result;
 3258: }
 3259: 
 3260: sub mkdiruserfile {
 3261:     my ($docuname,$docudom,$dir)=@_;
 3262:     my $home=&homeserver($docuname,$docudom);
 3263:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 3264: }
 3265: 
 3266: sub renameuserfile {
 3267:     my ($docuname,$docudom,$old,$new)=@_;
 3268:     my $home=&homeserver($docuname,$docudom);
 3269:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 3270:                         &escape("$old").':'.&escape("$new"),$home);
 3271:     if ($result eq 'ok') {
 3272:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 3273:             my $oldmeta = $old.'.meta';
 3274:             my $newmeta = $new.'.meta';
 3275:             my $metaresult = 
 3276:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 3277: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 3278:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 3279:             my $sqlresult = 
 3280:                 &update_portfolio_table($docuname,$docudom,$file,
 3281:                                         'portfolio_metadata',$group,
 3282:                                         'delete');
 3283:         }
 3284:     }
 3285:     return $result;
 3286: }
 3287: 
 3288: # ------------------------------------------------------------------------- Log
 3289: 
 3290: sub log {
 3291:     my ($dom,$nam,$hom,$what)=@_;
 3292:     return critical("log:$dom:$nam:$what",$hom);
 3293: }
 3294: 
 3295: # ------------------------------------------------------------------ Course Log
 3296: #
 3297: # This routine flushes several buffers of non-mission-critical nature
 3298: #
 3299: 
 3300: sub flushcourselogs {
 3301:     &logthis('Flushing log buffers');
 3302: #
 3303: # course logs
 3304: # This is a log of all transactions in a course, which can be used
 3305: # for data mining purposes
 3306: #
 3307: # It also collects the courseid database, which lists last transaction
 3308: # times and course titles for all courseids
 3309: #
 3310:     my %courseidbuffer=();
 3311:     foreach my $crsid (keys(%courselogs)) {
 3312:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 3313: 		          &escape($courselogs{$crsid}),
 3314: 		          $coursehombuf{$crsid}) eq 'ok') {
 3315: 	    delete $courselogs{$crsid};
 3316:         } else {
 3317:             &logthis('Failed to flush log buffer for '.$crsid);
 3318:             if (length($courselogs{$crsid})>40000) {
 3319:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 3320:                         " exceeded maximum size, deleting.</font>");
 3321:                delete $courselogs{$crsid};
 3322:             }
 3323:         }
 3324:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 3325:             'description' => $coursedescrbuf{$crsid},
 3326:             'inst_code'    => $courseinstcodebuf{$crsid},
 3327:             'type'        => $coursetypebuf{$crsid},
 3328:             'owner'       => $courseownerbuf{$crsid},
 3329:         };
 3330:     }
 3331: #
 3332: # Write course id database (reverse lookup) to homeserver of courses 
 3333: # Is used in pickcourse
 3334: #
 3335:     foreach my $crs_home (keys(%courseidbuffer)) {
 3336:         my $response = &courseidput(&host_domain($crs_home),
 3337:                                     $courseidbuffer{$crs_home},
 3338:                                     $crs_home,'timeonly');
 3339:     }
 3340: #
 3341: # File accesses
 3342: # Writes to the dynamic metadata of resources to get hit counts, etc.
 3343: #
 3344:     foreach my $entry (keys(%accesshash)) {
 3345:         if ($entry =~ /___count$/) {
 3346:             my ($dom,$name);
 3347:             ($dom,$name,undef)=
 3348: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 3349:             if (! defined($dom) || $dom eq '' || 
 3350:                 ! defined($name) || $name eq '') {
 3351:                 my $cid = $env{'request.course.id'};
 3352:                 $dom  = $env{'request.'.$cid.'.domain'};
 3353:                 $name = $env{'request.'.$cid.'.num'};
 3354:             }
 3355:             my $value = $accesshash{$entry};
 3356:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 3357:             my %temphash=($url => $value);
 3358:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 3359:             if ($result eq 'ok') {
 3360:                 delete $accesshash{$entry};
 3361:             }
 3362:         } else {
 3363:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 3364:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 3365:             my %temphash=($entry => $accesshash{$entry});
 3366:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 3367:                 delete $accesshash{$entry};
 3368:             }
 3369:         }
 3370:     }
 3371: #
 3372: # Roles
 3373: # Reverse lookup of user roles for course faculty/staff and co-authorship
 3374: #
 3375:     foreach my $entry (keys(%userrolehash)) {
 3376:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 3377: 	    split(/\:/,$entry);
 3378:         if (&Apache::lonnet::put('nohist_userroles',
 3379:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 3380:                 $rudom,$runame) eq 'ok') {
 3381: 	    delete $userrolehash{$entry};
 3382:         }
 3383:     }
 3384: #
 3385: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 3386: #
 3387:     my %domrolebuffer = ();
 3388:     foreach my $entry (keys(%domainrolehash)) {
 3389:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 3390:         if ($domrolebuffer{$rudom}) {
 3391:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 3392:                       '='.&escape($domainrolehash{$entry});
 3393:         } else {
 3394:             $domrolebuffer{$rudom}.=&escape($entry).
 3395:                       '='.&escape($domainrolehash{$entry});
 3396:         }
 3397:         delete $domainrolehash{$entry};
 3398:     }
 3399:     foreach my $dom (keys(%domrolebuffer)) {
 3400: 	my %servers = &get_servers($dom,'library');
 3401: 	foreach my $tryserver (keys(%servers)) {
 3402: 	    unless (&reply('domroleput:'.$dom.':'.
 3403: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 3404: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 3405: 	    }
 3406:         }
 3407:     }
 3408:     $dumpcount++;
 3409: }
 3410: 
 3411: sub courselog {
 3412:     my $what=shift;
 3413:     $what=time.':'.$what;
 3414:     unless ($env{'request.course.id'}) { return ''; }
 3415:     $coursedombuf{$env{'request.course.id'}}=
 3416:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 3417:     $coursenumbuf{$env{'request.course.id'}}=
 3418:        $env{'course.'.$env{'request.course.id'}.'.num'};
 3419:     $coursehombuf{$env{'request.course.id'}}=
 3420:        $env{'course.'.$env{'request.course.id'}.'.home'};
 3421:     $coursedescrbuf{$env{'request.course.id'}}=
 3422:        $env{'course.'.$env{'request.course.id'}.'.description'};
 3423:     $courseinstcodebuf{$env{'request.course.id'}}=
 3424:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 3425:     $courseownerbuf{$env{'request.course.id'}}=
 3426:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 3427:     $coursetypebuf{$env{'request.course.id'}}=
 3428:        $env{'course.'.$env{'request.course.id'}.'.type'};
 3429:     if (defined $courselogs{$env{'request.course.id'}}) {
 3430: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 3431:     } else {
 3432: 	$courselogs{$env{'request.course.id'}}.=$what;
 3433:     }
 3434:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 3435: 	&flushcourselogs();
 3436:     }
 3437: }
 3438: 
 3439: sub courseacclog {
 3440:     my $fnsymb=shift;
 3441:     unless ($env{'request.course.id'}) { return ''; }
 3442:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 3443:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 3444:         $what.=':POST';
 3445:         # FIXME: Probably ought to escape things....
 3446: 	foreach my $key (keys(%env)) {
 3447:             if ($key=~/^form\.(.*)/) {
 3448:                 my $formitem = $1;
 3449:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 3450:                     $what.=':'.$formitem.'='.$env{$key};
 3451:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 3452:                     $what.=':'.$formitem.'='.$env{$key};
 3453:                 }
 3454:             }
 3455:         }
 3456:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 3457:         # FIXME: We should not be depending on a form parameter that someone
 3458:         # editing lonsearchcat.pm might change in the future.
 3459:         if ($env{'form.phase'} eq 'course_search') {
 3460:             $what.= ':POST';
 3461:             # FIXME: Probably ought to escape things....
 3462:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 3463:                                  'crsdiscuss') {
 3464:                 $what.=':'.$element.'='.$env{'form.'.$element};
 3465:             }
 3466:         }
 3467:     }
 3468:     &courselog($what);
 3469: }
 3470: 
 3471: sub countacc {
 3472:     my $url=&declutter(shift);
 3473:     return if (! defined($url) || $url eq '');
 3474:     unless ($env{'request.course.id'}) { return ''; }
 3475: #
 3476: # Mark that this url was used in this course
 3477: #
 3478:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 3479: #
 3480: # Increase the access count for this resource in this child process
 3481: #
 3482:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 3483:     $accesshash{$key}++;
 3484: }
 3485: 
 3486: sub linklog {
 3487:     my ($from,$to)=@_;
 3488:     $from=&declutter($from);
 3489:     $to=&declutter($to);
 3490:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 3491:     $accesshash{$to.'___'.$from.'___goto'}=1;
 3492: }
 3493: 
 3494: sub statslog {
 3495:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 3496:     if ($users<2) { return; }
 3497:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 3498:             'course'       => $env{'request.course.id'},
 3499:             'sections'     => '"all"',
 3500:             'num_students' => $users,
 3501:             'part'         => $part,
 3502:             'symb'         => $symb,
 3503:             'mean_tries'   => $av_attempts,
 3504:             'deg_of_diff'  => $degdiff});
 3505:     foreach my $key (keys(%dynstore)) {
 3506:         $accesshash{$key}=$dynstore{$key};
 3507:     }
 3508: }
 3509:   
 3510: sub userrolelog {
 3511:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 3512:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
 3513:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 3514:        $userrolehash
 3515:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 3516:                     =$tend.':'.$tstart;
 3517:     }
 3518:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
 3519:        $userrolehash
 3520:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 3521:                     =$tend.':'.$tstart;
 3522:     }
 3523:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
 3524:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 3525:        $domainrolehash
 3526:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 3527:                     = $tend.':'.$tstart;
 3528:     }
 3529: }
 3530: 
 3531: sub courserolelog {
 3532:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 3533:     if (($trole eq 'cc') || ($trole eq 'in') ||
 3534:         ($trole eq 'ep') || ($trole eq 'ad') ||
 3535:         ($trole eq 'ta') || ($trole eq 'st') ||
 3536:         ($trole=~/^cr/) || ($trole eq 'gr') ||
 3537:         ($trole eq 'co')) {
 3538:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 3539:             my $cdom = $1;
 3540:             my $cnum = $2;
 3541:             my $sec = $3;
 3542:             my $namespace = 'rolelog';
 3543:             my %storehash = (
 3544:                                role    => $trole,
 3545:                                start   => $tstart,
 3546:                                end     => $tend,
 3547:                                selfenroll => $selfenroll,
 3548:                                context    => $context,
 3549:                             );
 3550:             if ($trole eq 'gr') {
 3551:                 $namespace = 'groupslog';
 3552:                 $storehash{'group'} = $sec;
 3553:             } else {
 3554:                 $storehash{'section'} = $sec;
 3555:             }
 3556:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
 3557:             if (($trole ne 'st') || ($sec ne '')) {
 3558:                 &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 3559:             }
 3560:         }
 3561:     }
 3562:     return;
 3563: }
 3564: 
 3565: sub get_course_adv_roles {
 3566:     my ($cid,$codes) = @_;
 3567:     $cid=$env{'request.course.id'} unless (defined($cid));
 3568:     my %coursehash=&coursedescription($cid);
 3569:     my $crstype = &Apache::loncommon::course_type($cid);
 3570:     my %nothide=();
 3571:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3572:         if ($user !~ /:/) {
 3573: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 3574:         } else {
 3575:             $nothide{$user}=1;
 3576:         }
 3577:     }
 3578:     my %returnhash=();
 3579:     my %dumphash=
 3580:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 3581:     my $now=time;
 3582:     my %privileged;
 3583:     foreach my $entry (keys(%dumphash)) {
 3584: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 3585:         if (($tstart) && ($tstart<0)) { next; }
 3586:         if (($tend) && ($tend<$now)) { next; }
 3587:         if (($tstart) && ($now<$tstart)) { next; }
 3588:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 3589: 	if ($username eq '' || $domain eq '') { next; }
 3590:         unless (ref($privileged{$domain}) eq 'HASH') {
 3591:             my %dompersonnel =
 3592:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
 3593:             $privileged{$domain} = {};
 3594:             foreach my $server (keys(%dompersonnel)) {
 3595:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 3596:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
 3597:                         my ($trole,$uname,$udom) = split(/:/,$user);
 3598:                         $privileged{$udom}{$uname} = 1;
 3599:                     }
 3600:                 }
 3601:             }
 3602:         }
 3603:         if ((exists($privileged{$domain}{$username})) && 
 3604:             (!$nothide{$username.':'.$domain})) { next; }
 3605: 	if ($role eq 'cr') { next; }
 3606:         if ($codes) {
 3607:             if ($section) { $role .= ':'.$section; }
 3608:             if ($returnhash{$role}) {
 3609:                 $returnhash{$role}.=','.$username.':'.$domain;
 3610:             } else {
 3611:                 $returnhash{$role}=$username.':'.$domain;
 3612:             }
 3613:         } else {
 3614:             my $key=&plaintext($role,$crstype);
 3615:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 3616:             if ($returnhash{$key}) {
 3617: 	        $returnhash{$key}.=','.$username.':'.$domain;
 3618:             } else {
 3619:                 $returnhash{$key}=$username.':'.$domain;
 3620:             }
 3621:         }
 3622:     }
 3623:     return %returnhash;
 3624: }
 3625: 
 3626: sub get_my_roles {
 3627:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 3628:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 3629:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 3630:     my (%dumphash,%nothide);
 3631:     if ($context eq 'userroles') {
 3632:         %dumphash = &dump('roles',$udom,$uname);
 3633:     } else {
 3634:         %dumphash=
 3635:             &dump('nohist_userroles',$udom,$uname);
 3636:         if ($hidepriv) {
 3637:             my %coursehash=&coursedescription($udom.'_'.$uname);
 3638:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3639:                 if ($user !~ /:/) {
 3640:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 3641:                 } else {
 3642:                     $nothide{$user} = 1;
 3643:                 }
 3644:             }
 3645:         }
 3646:     }
 3647:     my %returnhash=();
 3648:     my $now=time;
 3649:     my %privileged;
 3650:     foreach my $entry (keys(%dumphash)) {
 3651:         my ($role,$tend,$tstart);
 3652:         if ($context eq 'userroles') {
 3653:             next if ($entry =~ /^rolesdef/);
 3654: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 3655:         } else {
 3656:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 3657:         }
 3658:         if (($tstart) && ($tstart<0)) { next; }
 3659:         my $status = 'active';
 3660:         if (($tend) && ($tend<=$now)) {
 3661:             $status = 'previous';
 3662:         } 
 3663:         if (($tstart) && ($now<$tstart)) {
 3664:             $status = 'future';
 3665:         }
 3666:         if (ref($types) eq 'ARRAY') {
 3667:             if (!grep(/^\Q$status\E$/,@{$types})) {
 3668:                 next;
 3669:             } 
 3670:         } else {
 3671:             if ($status ne 'active') {
 3672:                 next;
 3673:             }
 3674:         }
 3675:         my ($rolecode,$username,$domain,$section,$area);
 3676:         if ($context eq 'userroles') {
 3677:             ($area,$rolecode) = split(/_/,$entry);
 3678:             (undef,$domain,$username,$section) = split(/\//,$area);
 3679:         } else {
 3680:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 3681:         }
 3682:         if (ref($roledoms) eq 'ARRAY') {
 3683:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 3684:                 next;
 3685:             }
 3686:         }
 3687:         if (ref($roles) eq 'ARRAY') {
 3688:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 3689:                 if ($role =~ /^cr\//) {
 3690:                     if (!grep(/^cr$/,@{$roles})) {
 3691:                         next;
 3692:                     }
 3693:                 } elsif ($role =~ /^gr\//) {
 3694:                     if (!grep(/^gr$/,@{$roles})) {
 3695:                         next;
 3696:                     }
 3697:                 } else {
 3698:                     next;
 3699:                 }
 3700:             }
 3701:         }
 3702:         if ($hidepriv) {
 3703:             if ($context eq 'userroles') {
 3704:                 if ((&privileged($username,$domain)) &&
 3705:                     (!$nothide{$username.':'.$domain})) {
 3706:                     next;
 3707:                 }
 3708:             } else {
 3709:                 unless (ref($privileged{$domain}) eq 'HASH') {
 3710:                     my %dompersonnel =
 3711:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
 3712:                     $privileged{$domain} = {};
 3713:                     if (keys(%dompersonnel)) {
 3714:                         foreach my $server (keys(%dompersonnel)) {
 3715:                             if (ref($dompersonnel{$server}) eq 'HASH') {
 3716:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
 3717:                                     my ($trole,$uname,$udom) = split(/:/,$user);
 3718:                                     $privileged{$udom}{$uname} = $trole;
 3719:                                 }
 3720:                             }
 3721:                         }
 3722:                     }
 3723:                 }
 3724:                 if (exists($privileged{$domain}{$username})) {
 3725:                     if (!$nothide{$username.':'.$domain}) {
 3726:                         next;
 3727:                     }
 3728:                 }
 3729:             }
 3730:         }
 3731:         if ($withsec) {
 3732:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 3733:                 $tstart.':'.$tend;
 3734:         } else {
 3735:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 3736:         }
 3737:     }
 3738:     return %returnhash;
 3739: }
 3740: 
 3741: # ----------------------------------------------------- Frontpage Announcements
 3742: #
 3743: #
 3744: 
 3745: sub postannounce {
 3746:     my ($server,$text)=@_;
 3747:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 3748:     unless ($text=~/\w/) { $text=''; }
 3749:     return &reply('setannounce:'.&escape($text),$server);
 3750: }
 3751: 
 3752: sub getannounce {
 3753: 
 3754:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 3755: 	my $announcement='';
 3756: 	while (my $line = <$fh>) { $announcement .= $line; }
 3757: 	close($fh);
 3758: 	if ($announcement=~/\w/) { 
 3759: 	    return 
 3760:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 3761:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 3762: 	} else {
 3763: 	    return '';
 3764: 	}
 3765:     } else {
 3766: 	return '';
 3767:     }
 3768: }
 3769: 
 3770: # ---------------------------------------------------------- Course ID routines
 3771: # Deal with domain's nohist_courseid.db files
 3772: #
 3773: 
 3774: sub courseidput {
 3775:     my ($domain,$storehash,$coursehome,$caller) = @_;
 3776:     return unless (ref($storehash) eq 'HASH');
 3777:     my $outcome;
 3778:     if ($caller eq 'timeonly') {
 3779:         my $cids = '';
 3780:         foreach my $item (keys(%$storehash)) {
 3781:             $cids.=&escape($item).'&';
 3782:         }
 3783:         $cids=~s/\&$//;
 3784:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 3785:                           $coursehome);       
 3786:     } else {
 3787:         my $items = '';
 3788:         foreach my $item (keys(%$storehash)) {
 3789:             $items.= &escape($item).'='.
 3790:                      &freeze_escape($$storehash{$item}).'&';
 3791:         }
 3792:         $items=~s/\&$//;
 3793:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 3794:                           $coursehome);
 3795:     }
 3796:     if ($outcome eq 'unknown_cmd') {
 3797:         my $what;
 3798:         foreach my $cid (keys(%$storehash)) {
 3799:             $what .= &escape($cid).'=';
 3800:             foreach my $item ('description','inst_code','owner','type') {
 3801:                 $what .= &escape($storehash->{$cid}{$item}).':';
 3802:             }
 3803:             $what =~ s/\:$/&/;
 3804:         }
 3805:         $what =~ s/\&$//;  
 3806:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 3807:     } else {
 3808:         return $outcome;
 3809:     }
 3810: }
 3811: 
 3812: sub courseiddump {
 3813:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 3814:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 3815:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 3816:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
 3817:     my $as_hash = 1;
 3818:     my %returnhash;
 3819:     if (!$domfilter) { $domfilter=''; }
 3820:     my %libserv = &all_library();
 3821:     foreach my $tryserver (keys(%libserv)) {
 3822:         if ( (  $hostidflag == 1 
 3823: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 3824: 	     || (!defined($hostidflag)) ) {
 3825: 
 3826: 	    if (($domfilter eq '') ||
 3827: 		(&host_domain($tryserver) eq $domfilter)) {
 3828:                 my $rep;
 3829:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
 3830:                     $rep = LONCAPA::Lond::dump_course_id_handler(
 3831:                         join(":", (&host_domain($tryserver), $sincefilter, 
 3832:                                 &escape($descfilter), &escape($instcodefilter), 
 3833:                                 &escape($ownerfilter), &escape($coursefilter),
 3834:                                 &escape($typefilter), &escape($regexp_ok), 
 3835:                                 $as_hash, &escape($selfenrollonly), 
 3836:                                 &escape($catfilter), $showhidden, $caller, 
 3837:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
 3838:                                 &escape($createdbefore), &escape($createdafter), 
 3839:                                 &escape($creationcontext), $domcloner)));
 3840:                 } else {
 3841:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
 3842:                              $sincefilter.':'.&escape($descfilter).':'.
 3843:                              &escape($instcodefilter).':'.&escape($ownerfilter).
 3844:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
 3845:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
 3846:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
 3847:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
 3848:                              &escape($cc_clone).':'.$cloneonly.':'.
 3849:                              &escape($createdbefore).':'.&escape($createdafter).':'.
 3850:                              &escape($creationcontext).':'.$domcloner,
 3851:                              $tryserver);
 3852:                 }
 3853:                      
 3854:                 my @pairs=split(/\&/,$rep);
 3855:                 foreach my $item (@pairs) {
 3856:                     my ($key,$value)=split(/\=/,$item,2);
 3857:                     $key = &unescape($key);
 3858:                     next if ($key =~ /^error: 2 /);
 3859:                     my $result = &thaw_unescape($value);
 3860:                     if (ref($result) eq 'HASH') {
 3861:                         $returnhash{$key}=$result;
 3862:                     } else {
 3863:                         my @responses = split(/:/,$value);
 3864:                         my @items = ('description','inst_code','owner','type');
 3865:                         for (my $i=0; $i<@responses; $i++) {
 3866:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 3867:                         }
 3868:                     }
 3869:                 }
 3870:             }
 3871:         }
 3872:     }
 3873:     return %returnhash;
 3874: }
 3875: 
 3876: sub courselastaccess {
 3877:     my ($cdom,$cnum,$hostidref) = @_;
 3878:     my %returnhash;
 3879:     if ($cdom && $cnum) {
 3880:         my $chome = &homeserver($cnum,$cdom);
 3881:         if ($chome ne 'no_host') {
 3882:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 3883:             &extract_lastaccess(\%returnhash,$rep);
 3884:         }
 3885:     } else {
 3886:         if (!$cdom) { $cdom=''; }
 3887:         my %libserv = &all_library();
 3888:         foreach my $tryserver (keys(%libserv)) {
 3889:             if (ref($hostidref) eq 'ARRAY') {
 3890:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 3891:             } 
 3892:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 3893:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 3894:                 &extract_lastaccess(\%returnhash,$rep);
 3895:             }
 3896:         }
 3897:     }
 3898:     return %returnhash;
 3899: }
 3900: 
 3901: sub extract_lastaccess {
 3902:     my ($returnhash,$rep) = @_;
 3903:     if (ref($returnhash) eq 'HASH') {
 3904:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 3905:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 3906:                  $rep eq '') {
 3907:             my @pairs=split(/\&/,$rep);
 3908:             foreach my $item (@pairs) {
 3909:                 my ($key,$value)=split(/\=/,$item,2);
 3910:                 $key = &unescape($key);
 3911:                 next if ($key =~ /^error: 2 /);
 3912:                 $returnhash->{$key} = &thaw_unescape($value);
 3913:             }
 3914:         }
 3915:     }
 3916:     return;
 3917: }
 3918: 
 3919: # ---------------------------------------------------------- DC e-mail
 3920: 
 3921: sub dcmailput {
 3922:     my ($domain,$msgid,$message,$server)=@_;
 3923:     my $status = &Apache::lonnet::critical(
 3924:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 3925:        &escape($message),$server);
 3926:     return $status;
 3927: }
 3928: 
 3929: sub dcmaildump {
 3930:     my ($dom,$startdate,$enddate,$senders) = @_;
 3931:     my %returnhash=();
 3932: 
 3933:     if (defined(&domain($dom,'primary'))) {
 3934:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 3935:                                                          &escape($enddate).':';
 3936: 	my @esc_senders=map { &escape($_)} @$senders;
 3937: 	$cmd.=&escape(join('&',@esc_senders));
 3938: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 3939:             my ($key,$value) = split(/\=/,$line,2);
 3940:             if (($key) && ($value)) {
 3941:                 $returnhash{&unescape($key)} = &unescape($value);
 3942:             }
 3943:         }
 3944:     }
 3945:     return %returnhash;
 3946: }
 3947: # ---------------------------------------------------------- Domain roles
 3948: 
 3949: sub get_domain_roles {
 3950:     my ($dom,$roles,$startdate,$enddate)=@_;
 3951:     if ((!defined($startdate)) || ($startdate eq '')) {
 3952:         $startdate = '.';
 3953:     }
 3954:     if ((!defined($enddate)) || ($enddate eq '')) {
 3955:         $enddate = '.';
 3956:     }
 3957:     my $rolelist;
 3958:     if (ref($roles) eq 'ARRAY') {
 3959:         $rolelist = join(':',@{$roles});
 3960:     }
 3961:     my %personnel = ();
 3962: 
 3963:     my %servers = &get_servers($dom,'library');
 3964:     foreach my $tryserver (keys(%servers)) {
 3965: 	%{$personnel{$tryserver}}=();
 3966: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 3967: 					    &escape($startdate).':'.
 3968: 					    &escape($enddate).':'.
 3969: 					    &escape($rolelist), $tryserver))) {
 3970: 	    my ($key,$value) = split(/\=/,$line,2);
 3971: 	    if (($key) && ($value)) {
 3972: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 3973: 	    }
 3974: 	}
 3975:     }
 3976:     return %personnel;
 3977: }
 3978: 
 3979: # ----------------------------------------------------------- Interval timing 
 3980: 
 3981: {
 3982: # Caches needed for speedup of navmaps
 3983: # We don't want to cache this for very long at all (5 seconds at most)
 3984: # 
 3985: # The user for whom we cache
 3986: my $cachedkey='';
 3987: # The cached times for this user
 3988: my %cachedtimes=();
 3989: # When this was last done
 3990: my $cachedtime=();
 3991: 
 3992: sub load_all_first_access {
 3993:     my ($uname,$udom)=@_;
 3994:     if (($cachedkey eq $uname.':'.$udom) &&
 3995:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
 3996:         return;
 3997:     }
 3998:     $cachedtime=time;
 3999:     $cachedkey=$uname.':'.$udom;
 4000:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 4001: }
 4002: 
 4003: sub get_first_access {
 4004:     my ($type,$argsymb,$argmap)=@_;
 4005:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 4006:     if ($argsymb) { $symb=$argsymb; }
 4007:     my ($map,$id,$res)=&decode_symb($symb);
 4008:     if ($argmap) { $map = $argmap; }
 4009:     if ($type eq 'course') {
 4010: 	$res='course';
 4011:     } elsif ($type eq 'map') {
 4012: 	$res=&symbread($map);
 4013:     } else {
 4014: 	$res=$symb;
 4015:     }
 4016:     &load_all_first_access($uname,$udom);
 4017:     return $cachedtimes{"$courseid\0$res"};
 4018: }
 4019: 
 4020: sub set_first_access {
 4021:     my ($type,$interval)=@_;
 4022:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 4023:     my ($map,$id,$res)=&decode_symb($symb);
 4024:     if ($type eq 'course') {
 4025: 	$res='course';
 4026:     } elsif ($type eq 'map') {
 4027: 	$res=&symbread($map);
 4028:     } else {
 4029: 	$res=$symb;
 4030:     }
 4031:     $cachedkey='';
 4032:     my $firstaccess=&get_first_access($type,$symb,$map);
 4033:     if (!$firstaccess) {
 4034:         my $start = time;
 4035: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 4036:                           $udom,$uname);
 4037:         if ($putres eq 'ok') {
 4038:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 4039:                  $udom,$uname); 
 4040:             &appenv(
 4041:                      {
 4042:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 4043:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 4044:                      }
 4045:                   );
 4046:         }
 4047:         return $putres;
 4048:     }
 4049:     return 'already_set';
 4050: }
 4051: }
 4052: # --------------------------------------------- Set Expire Date for Spreadsheet
 4053: 
 4054: sub expirespread {
 4055:     my ($uname,$udom,$stype,$usymb)=@_;
 4056:     my $cid=$env{'request.course.id'}; 
 4057:     if ($cid) {
 4058:        my $now=time;
 4059:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 4060:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 4061:                             $env{'course.'.$cid.'.num'}.
 4062: 	        	    ':nohist_expirationdates:'.
 4063:                             &escape($key).'='.$now,
 4064:                             $env{'course.'.$cid.'.home'})
 4065:     }
 4066:     return 'ok';
 4067: }
 4068: 
 4069: # ----------------------------------------------------- Devalidate Spreadsheets
 4070: 
 4071: sub devalidate {
 4072:     my ($symb,$uname,$udom)=@_;
 4073:     my $cid=$env{'request.course.id'}; 
 4074:     if ($cid) {
 4075:         # delete the stored spreadsheets for
 4076:         # - the student level sheet of this user in course's homespace
 4077:         # - the assessment level sheet for this resource 
 4078:         #   for this user in user's homespace
 4079: 	# - current conditional state info
 4080: 	my $key=$uname.':'.$udom.':';
 4081:         my $status=
 4082: 	    &del('nohist_calculatedsheets',
 4083: 		 [$key.'studentcalc:'],
 4084: 		 $env{'course.'.$cid.'.domain'},
 4085: 		 $env{'course.'.$cid.'.num'})
 4086: 		.' '.
 4087: 	    &del('nohist_calculatedsheets_'.$cid,
 4088: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 4089:         unless ($status eq 'ok ok') {
 4090:            &logthis('Could not devalidate spreadsheet '.
 4091:                     $uname.' at '.$udom.' for '.
 4092: 		    $symb.': '.$status);
 4093:         }
 4094: 	&delenv('user.state.'.$cid);
 4095:     }
 4096: }
 4097: 
 4098: sub get_scalar {
 4099:     my ($string,$end) = @_;
 4100:     my $value;
 4101:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 4102: 	$value = $1;
 4103:     } elsif ($$string =~ s/^([^&]*?)&//) {
 4104: 	$value = $1;
 4105:     }
 4106:     return &unescape($value);
 4107: }
 4108: 
 4109: sub array2str {
 4110:   my (@array) = @_;
 4111:   my $result=&arrayref2str(\@array);
 4112:   $result=~s/^__ARRAY_REF__//;
 4113:   $result=~s/__END_ARRAY_REF__$//;
 4114:   return $result;
 4115: }
 4116: 
 4117: sub arrayref2str {
 4118:   my ($arrayref) = @_;
 4119:   my $result='__ARRAY_REF__';
 4120:   foreach my $elem (@$arrayref) {
 4121:     if(ref($elem) eq 'ARRAY') {
 4122:       $result.=&arrayref2str($elem).'&';
 4123:     } elsif(ref($elem) eq 'HASH') {
 4124:       $result.=&hashref2str($elem).'&';
 4125:     } elsif(ref($elem)) {
 4126:       #print("Got a ref of ".(ref($elem))." skipping.");
 4127:     } else {
 4128:       $result.=&escape($elem).'&';
 4129:     }
 4130:   }
 4131:   $result=~s/\&$//;
 4132:   $result .= '__END_ARRAY_REF__';
 4133:   return $result;
 4134: }
 4135: 
 4136: sub hash2str {
 4137:   my (%hash) = @_;
 4138:   my $result=&hashref2str(\%hash);
 4139:   $result=~s/^__HASH_REF__//;
 4140:   $result=~s/__END_HASH_REF__$//;
 4141:   return $result;
 4142: }
 4143: 
 4144: sub hashref2str {
 4145:   my ($hashref)=@_;
 4146:   my $result='__HASH_REF__';
 4147:   foreach my $key (sort(keys(%$hashref))) {
 4148:     if (ref($key) eq 'ARRAY') {
 4149:       $result.=&arrayref2str($key).'=';
 4150:     } elsif (ref($key) eq 'HASH') {
 4151:       $result.=&hashref2str($key).'=';
 4152:     } elsif (ref($key)) {
 4153:       $result.='=';
 4154:       #print("Got a ref of ".(ref($key))." skipping.");
 4155:     } else {
 4156: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 4157:     }
 4158: 
 4159:     if(ref($hashref->{$key}) eq 'ARRAY') {
 4160:       $result.=&arrayref2str($hashref->{$key}).'&';
 4161:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 4162:       $result.=&hashref2str($hashref->{$key}).'&';
 4163:     } elsif(ref($hashref->{$key})) {
 4164:        $result.='&';
 4165:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 4166:     } else {
 4167:       $result.=&escape($hashref->{$key}).'&';
 4168:     }
 4169:   }
 4170:   $result=~s/\&$//;
 4171:   $result .= '__END_HASH_REF__';
 4172:   return $result;
 4173: }
 4174: 
 4175: sub str2hash {
 4176:     my ($string)=@_;
 4177:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 4178:     return %$hash;
 4179: }
 4180: 
 4181: sub str2hashref {
 4182:   my ($string) = @_;
 4183: 
 4184:   my %hash;
 4185: 
 4186:   if($string !~ /^__HASH_REF__/) {
 4187:       if (! ($string eq '' || !defined($string))) {
 4188: 	  $hash{'error'}='Not hash reference';
 4189:       }
 4190:       return (\%hash, $string);
 4191:   }
 4192: 
 4193:   $string =~ s/^__HASH_REF__//;
 4194: 
 4195:   while($string !~ /^__END_HASH_REF__/) {
 4196:       #key
 4197:       my $key='';
 4198:       if($string =~ /^__HASH_REF__/) {
 4199:           ($key, $string)=&str2hashref($string);
 4200:           if(defined($key->{'error'})) {
 4201:               $hash{'error'}='Bad data';
 4202:               return (\%hash, $string);
 4203:           }
 4204:       } elsif($string =~ /^__ARRAY_REF__/) {
 4205:           ($key, $string)=&str2arrayref($string);
 4206:           if($key->[0] eq 'Array reference error') {
 4207:               $hash{'error'}='Bad data';
 4208:               return (\%hash, $string);
 4209:           }
 4210:       } else {
 4211:           $string =~ s/^(.*?)=//;
 4212: 	  $key=&unescape($1);
 4213:       }
 4214:       $string =~ s/^=//;
 4215: 
 4216:       #value
 4217:       my $value='';
 4218:       if($string =~ /^__HASH_REF__/) {
 4219:           ($value, $string)=&str2hashref($string);
 4220:           if(defined($value->{'error'})) {
 4221:               $hash{'error'}='Bad data';
 4222:               return (\%hash, $string);
 4223:           }
 4224:       } elsif($string =~ /^__ARRAY_REF__/) {
 4225:           ($value, $string)=&str2arrayref($string);
 4226:           if($value->[0] eq 'Array reference error') {
 4227:               $hash{'error'}='Bad data';
 4228:               return (\%hash, $string);
 4229:           }
 4230:       } else {
 4231: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 4232:       }
 4233:       $string =~ s/^&//;
 4234: 
 4235:       $hash{$key}=$value;
 4236:   }
 4237: 
 4238:   $string =~ s/^__END_HASH_REF__//;
 4239: 
 4240:   return (\%hash, $string);
 4241: }
 4242: 
 4243: sub str2array {
 4244:     my ($string)=@_;
 4245:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 4246:     return @$array;
 4247: }
 4248: 
 4249: sub str2arrayref {
 4250:   my ($string) = @_;
 4251:   my @array;
 4252: 
 4253:   if($string !~ /^__ARRAY_REF__/) {
 4254:       if (! ($string eq '' || !defined($string))) {
 4255: 	  $array[0]='Array reference error';
 4256:       }
 4257:       return (\@array, $string);
 4258:   }
 4259: 
 4260:   $string =~ s/^__ARRAY_REF__//;
 4261: 
 4262:   while($string !~ /^__END_ARRAY_REF__/) {
 4263:       my $value='';
 4264:       if($string =~ /^__HASH_REF__/) {
 4265:           ($value, $string)=&str2hashref($string);
 4266:           if(defined($value->{'error'})) {
 4267:               $array[0] ='Array reference error';
 4268:               return (\@array, $string);
 4269:           }
 4270:       } elsif($string =~ /^__ARRAY_REF__/) {
 4271:           ($value, $string)=&str2arrayref($string);
 4272:           if($value->[0] eq 'Array reference error') {
 4273:               $array[0] ='Array reference error';
 4274:               return (\@array, $string);
 4275:           }
 4276:       } else {
 4277: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 4278:       }
 4279:       $string =~ s/^&//;
 4280: 
 4281:       push(@array, $value);
 4282:   }
 4283: 
 4284:   $string =~ s/^__END_ARRAY_REF__//;
 4285: 
 4286:   return (\@array, $string);
 4287: }
 4288: 
 4289: # -------------------------------------------------------------------Temp Store
 4290: 
 4291: sub tmpreset {
 4292:   my ($symb,$namespace,$domain,$stuname) = @_;
 4293:   if (!$symb) {
 4294:     $symb=&symbread();
 4295:     if (!$symb) { $symb= $env{'request.url'}; }
 4296:   }
 4297:   $symb=escape($symb);
 4298: 
 4299:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4300:   $namespace=~s/\//\_/g;
 4301:   $namespace=~s/\W//g;
 4302: 
 4303:   if (!$domain) { $domain=$env{'user.domain'}; }
 4304:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4305:   if ($domain eq 'public' && $stuname eq 'public') {
 4306:       $stuname=$ENV{'REMOTE_ADDR'};
 4307:   }
 4308:   my $path=LONCAPA::tempdir();
 4309:   my %hash;
 4310:   if (tie(%hash,'GDBM_File',
 4311: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4312: 	  &GDBM_WRCREAT(),0640)) {
 4313:     foreach my $key (keys(%hash)) {
 4314:       if ($key=~ /:$symb/) {
 4315: 	delete($hash{$key});
 4316:       }
 4317:     }
 4318:   }
 4319: }
 4320: 
 4321: sub tmpstore {
 4322:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4323: 
 4324:   if (!$symb) {
 4325:     $symb=&symbread();
 4326:     if (!$symb) { $symb= $env{'request.url'}; }
 4327:   }
 4328:   $symb=escape($symb);
 4329: 
 4330:   if (!$namespace) {
 4331:     # I don't think we would ever want to store this for a course.
 4332:     # it seems this will only be used if we don't have a course.
 4333:     #$namespace=$env{'request.course.id'};
 4334:     #if (!$namespace) {
 4335:       $namespace=$env{'request.state'};
 4336:     #}
 4337:   }
 4338:   $namespace=~s/\//\_/g;
 4339:   $namespace=~s/\W//g;
 4340:   if (!$domain) { $domain=$env{'user.domain'}; }
 4341:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4342:   if ($domain eq 'public' && $stuname eq 'public') {
 4343:       $stuname=$ENV{'REMOTE_ADDR'};
 4344:   }
 4345:   my $now=time;
 4346:   my %hash;
 4347:   my $path=LONCAPA::tempdir();
 4348:   if (tie(%hash,'GDBM_File',
 4349: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4350: 	  &GDBM_WRCREAT(),0640)) {
 4351:     $hash{"version:$symb"}++;
 4352:     my $version=$hash{"version:$symb"};
 4353:     my $allkeys=''; 
 4354:     foreach my $key (keys(%$storehash)) {
 4355:       $allkeys.=$key.':';
 4356:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 4357:     }
 4358:     $hash{"$version:$symb:timestamp"}=$now;
 4359:     $allkeys.='timestamp';
 4360:     $hash{"$version:keys:$symb"}=$allkeys;
 4361:     if (untie(%hash)) {
 4362:       return 'ok';
 4363:     } else {
 4364:       return "error:$!";
 4365:     }
 4366:   } else {
 4367:     return "error:$!";
 4368:   }
 4369: }
 4370: 
 4371: # -----------------------------------------------------------------Temp Restore
 4372: 
 4373: sub tmprestore {
 4374:   my ($symb,$namespace,$domain,$stuname) = @_;
 4375: 
 4376:   if (!$symb) {
 4377:     $symb=&symbread();
 4378:     if (!$symb) { $symb= $env{'request.url'}; }
 4379:   }
 4380:   $symb=escape($symb);
 4381: 
 4382:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4383: 
 4384:   if (!$domain) { $domain=$env{'user.domain'}; }
 4385:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4386:   if ($domain eq 'public' && $stuname eq 'public') {
 4387:       $stuname=$ENV{'REMOTE_ADDR'};
 4388:   }
 4389:   my %returnhash;
 4390:   $namespace=~s/\//\_/g;
 4391:   $namespace=~s/\W//g;
 4392:   my %hash;
 4393:   my $path=LONCAPA::tempdir();
 4394:   if (tie(%hash,'GDBM_File',
 4395: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4396: 	  &GDBM_READER(),0640)) {
 4397:     my $version=$hash{"version:$symb"};
 4398:     $returnhash{'version'}=$version;
 4399:     my $scope;
 4400:     for ($scope=1;$scope<=$version;$scope++) {
 4401:       my $vkeys=$hash{"$scope:keys:$symb"};
 4402:       my @keys=split(/:/,$vkeys);
 4403:       my $key;
 4404:       $returnhash{"$scope:keys"}=$vkeys;
 4405:       foreach $key (@keys) {
 4406: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4407: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4408:       }
 4409:     }
 4410:     if (!(untie(%hash))) {
 4411:       return "error:$!";
 4412:     }
 4413:   } else {
 4414:     return "error:$!";
 4415:   }
 4416:   return %returnhash;
 4417: }
 4418: 
 4419: # ----------------------------------------------------------------------- Store
 4420: 
 4421: sub store {
 4422:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4423:     my $home='';
 4424: 
 4425:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4426: 
 4427:     $symb=&symbclean($symb);
 4428:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 4429: 
 4430:     if (!$domain) { $domain=$env{'user.domain'}; }
 4431:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4432: 
 4433:     &devalidate($symb,$stuname,$domain);
 4434: 
 4435:     $symb=escape($symb);
 4436:     if (!$namespace) { 
 4437:        unless ($namespace=$env{'request.course.id'}) { 
 4438:           return ''; 
 4439:        } 
 4440:     }
 4441:     if (!$home) { $home=$env{'user.home'}; }
 4442: 
 4443:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 4444:     $$storehash{'host'}=$perlvar{'lonHostID'};
 4445: 
 4446:     my $namevalue='';
 4447:     foreach my $key (keys(%$storehash)) {
 4448:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4449:     }
 4450:     $namevalue=~s/\&$//;
 4451:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 4452:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 4453: }
 4454: 
 4455: # -------------------------------------------------------------- Critical Store
 4456: 
 4457: sub cstore {
 4458:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4459:     my $home='';
 4460: 
 4461:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4462: 
 4463:     $symb=&symbclean($symb);
 4464:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 4465: 
 4466:     if (!$domain) { $domain=$env{'user.domain'}; }
 4467:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4468: 
 4469:     &devalidate($symb,$stuname,$domain);
 4470: 
 4471:     $symb=escape($symb);
 4472:     if (!$namespace) { 
 4473:        unless ($namespace=$env{'request.course.id'}) { 
 4474:           return ''; 
 4475:        } 
 4476:     }
 4477:     if (!$home) { $home=$env{'user.home'}; }
 4478: 
 4479:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 4480:     $$storehash{'host'}=$perlvar{'lonHostID'};
 4481: 
 4482:     my $namevalue='';
 4483:     foreach my $key (keys(%$storehash)) {
 4484:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4485:     }
 4486:     $namevalue=~s/\&$//;
 4487:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 4488:     return critical
 4489:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 4490: }
 4491: 
 4492: # --------------------------------------------------------------------- Restore
 4493: 
 4494: sub restore {
 4495:     my ($symb,$namespace,$domain,$stuname) = @_;
 4496:     my $home='';
 4497: 
 4498:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4499: 
 4500:     if (!$symb) {
 4501:       unless ($symb=escape(&symbread())) { return ''; }
 4502:     } else {
 4503:       $symb=&escape(&symbclean($symb));
 4504:     }
 4505:     if (!$namespace) { 
 4506:        unless ($namespace=$env{'request.course.id'}) { 
 4507:           return ''; 
 4508:        } 
 4509:     }
 4510:     if (!$domain) { $domain=$env{'user.domain'}; }
 4511:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4512:     if (!$home) { $home=$env{'user.home'}; }
 4513:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 4514: 
 4515:     my %returnhash=();
 4516:     foreach my $line (split(/\&/,$answer)) {
 4517: 	my ($name,$value)=split(/\=/,$line);
 4518:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 4519:     }
 4520:     my $version;
 4521:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 4522:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 4523:           $returnhash{$item}=$returnhash{$version.':'.$item};
 4524:        }
 4525:     }
 4526:     return %returnhash;
 4527: }
 4528: 
 4529: # ---------------------------------------------------------- Course Description
 4530: #
 4531: #  
 4532: 
 4533: sub coursedescription {
 4534:     my ($courseid,$args)=@_;
 4535:     $courseid=~s/^\///;
 4536:     $courseid=~s/\_/\//g;
 4537:     my ($cdomain,$cnum)=split(/\//,$courseid);
 4538:     my $chome=&homeserver($cnum,$cdomain);
 4539:     my $normalid=$cdomain.'_'.$cnum;
 4540:     # need to always cache even if we get errors otherwise we keep 
 4541:     # trying and trying and trying to get the course description.
 4542:     my %envhash=();
 4543:     my %returnhash=();
 4544:     
 4545:     my $expiretime=600;
 4546:     if ($env{'request.course.id'} eq $normalid) {
 4547: 	$expiretime=120;
 4548:     }
 4549: 
 4550:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 4551:     if (!$args->{'freshen_cache'}
 4552: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 4553: 	foreach my $key (keys(%env)) {
 4554: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 4555: 	    my ($setting) = $1;
 4556: 	    $returnhash{$setting} = $env{$key};
 4557: 	}
 4558: 	return %returnhash;
 4559:     }
 4560: 
 4561:     # get the data again
 4562: 
 4563:     if (!$args->{'one_time'}) {
 4564: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 4565:     }
 4566: 
 4567:     if ($chome ne 'no_host') {
 4568:        %returnhash=&dump('environment',$cdomain,$cnum);
 4569:        if (!exists($returnhash{'con_lost'})) {
 4570: 	   my $username = $env{'user.name'}; # Defult username
 4571: 	   if(defined $args->{'user'}) {
 4572: 	       $username = $args->{'user'};
 4573: 	   }
 4574:            $returnhash{'home'}= $chome;
 4575: 	   $returnhash{'domain'} = $cdomain;
 4576: 	   $returnhash{'num'} = $cnum;
 4577:            if (!defined($returnhash{'type'})) {
 4578:                $returnhash{'type'} = 'Course';
 4579:            }
 4580:            while (my ($name,$value) = each %returnhash) {
 4581:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 4582:            }
 4583:            $returnhash{'url'}=&clutter($returnhash{'url'});
 4584:            $returnhash{'fn'}=LONCAPA::tempdir() .
 4585: 	       $username.'_'.$cdomain.'_'.$cnum;
 4586:            $envhash{'course.'.$normalid.'.home'}=$chome;
 4587:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 4588:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 4589:        }
 4590:     }
 4591:     if (!$args->{'one_time'}) {
 4592: 	&appenv(\%envhash);
 4593:     }
 4594:     return %returnhash;
 4595: }
 4596: 
 4597: sub update_released_required {
 4598:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 4599:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 4600:         $cid = $env{'request.course.id'};
 4601:         $cdom = $env{'course.'.$cid.'.domain'};
 4602:         $cnum = $env{'course.'.$cid.'.num'};
 4603:         $chome = $env{'course.'.$cid.'.home'};
 4604:     }
 4605:     if ($needsrelease) {
 4606:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 4607:         my $needsupdate;
 4608:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 4609:             $needsupdate = 1;
 4610:         } else {
 4611:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 4612:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 4613:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 4614:                 $needsupdate = 1;
 4615:             }
 4616:         }
 4617:         if ($needsupdate) {
 4618:             my %needshash = (
 4619:                              'internal.releaserequired' => $needsrelease,
 4620:                             );
 4621:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 4622:             if ($putresult eq 'ok') {
 4623:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 4624:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 4625:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 4626:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 4627:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 4628:                 }
 4629:             }
 4630:         }
 4631:     }
 4632:     return;
 4633: }
 4634: 
 4635: # -------------------------------------------------See if a user is privileged
 4636: 
 4637: sub privileged {
 4638:     my ($username,$domain)=@_;
 4639: 
 4640:     my %rolesdump = &dump("roles", $domain, $username) or return 0;
 4641:     my $now = time;
 4642: 
 4643:     for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
 4644:             my ($trole, $tend, $tstart) = split(/_/, $role);
 4645:             if (($trole eq 'dc') || ($trole eq 'su')) {
 4646:                 return 1 unless ($tend && $tend < $now) 
 4647:                     or ($tstart && $tstart > $now);
 4648:             }
 4649: 	}
 4650: 
 4651:     return 0;
 4652: }
 4653: 
 4654: # -------------------------------------------------------- Get user privileges
 4655: 
 4656: sub rolesinit {
 4657:     my ($domain, $username) = @_;
 4658:     my %userroles = ('user.login.time' => time);
 4659:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 4660: 
 4661:     # firstaccess and timerinterval are related to timed maps/resources. 
 4662:     # also, blocking can be triggered by an activating timer
 4663:     # it's saved in the user's %env.
 4664:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 4665:     my %timerinterval = &dump('timerinterval', $domain, $username);
 4666:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 4667:         %timerintchk, %timerintenv);
 4668: 
 4669:     foreach my $key (keys(%firstaccess)) {
 4670:         my ($cid, $rest) = split(/\0/, $key);
 4671:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 4672:     }
 4673: 
 4674:     foreach my $key (keys(%timerinterval)) {
 4675:         my ($cid,$rest) = split(/\0/,$key);
 4676:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 4677:     }
 4678: 
 4679:     my %allroles=();
 4680:     my %allgroups=();
 4681: 
 4682:     for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
 4683:         my $role = $rolesdump{$area};
 4684:         $area =~ s/\_\w\w$//;
 4685: 
 4686:         my ($trole, $tend, $tstart, $group_privs);
 4687: 
 4688:         if ($role =~ /^cr/) {
 4689:         # Custom role, defined by a user 
 4690:         # e.g., user.role.cr/msu/smith/mynewrole
 4691:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 4692:                 $trole = $1;
 4693:                 ($tend, $tstart) = split('_', $2);
 4694:             } else {
 4695:                 $trole = $role;
 4696:             }
 4697:         } elsif ($role =~ m|^gr/|) {
 4698:         # Role of member in a group, defined within a course/community
 4699:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 4700:             ($trole, $tend, $tstart) = split(/_/, $role);
 4701:             next if $tstart eq '-1';
 4702:             ($trole, $group_privs) = split(/\//, $trole);
 4703:             $group_privs = &unescape($group_privs);
 4704:         } else {
 4705:         # Just a normal role, defined in roles.tab
 4706:             ($trole, $tend, $tstart) = split(/_/,$role);
 4707:         }
 4708: 
 4709:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 4710:                  $username);
 4711:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 4712: 
 4713:         # role expired or not available yet?
 4714:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 4715:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 4716: 
 4717:         next if $area eq '' or $trole eq '';
 4718: 
 4719:         my $spec = "$trole.$area";
 4720:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 4721: 
 4722:         if ($trole =~ /^cr\//) {
 4723:         # Custom role, defined by a user
 4724:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 4725:         } elsif ($trole eq 'gr') {
 4726:         # Role of a member in a group, defined within a course/community
 4727:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 4728:             next;
 4729:         } else {
 4730:         # Normal role, defined in roles.tab
 4731:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 4732:         }
 4733: 
 4734:         my $cid = $tdomain.'_'.$trest;
 4735:         unless ($firstaccchk{$cid}) {
 4736:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 4737:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 4738:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 4739:                         $coursetimerstarts{$cid}{$item}; 
 4740:                 }
 4741:             }
 4742:             $firstaccchk{$cid} = 1;
 4743:         }
 4744:         unless ($timerintchk{$cid}) {
 4745:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 4746:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 4747:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 4748:                        $coursetimerintervals{$cid}{$item};
 4749:                 }
 4750:             }
 4751:             $timerintchk{$cid} = 1;
 4752:         }
 4753:     }
 4754: 
 4755:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
 4756:         \%allroles, \%allgroups);
 4757:     $env{'user.adv'} = $userroles{'user.adv'};
 4758: 
 4759:     return (\%userroles,\%firstaccenv,\%timerintenv);
 4760: }
 4761: 
 4762: sub set_arearole {
 4763:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
 4764: # log the associated role with the area
 4765:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 4766:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 4767: }
 4768: 
 4769: sub custom_roleprivs {
 4770:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 4771:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 4772:     my $homsvr=homeserver($rauthor,$rdomain);
 4773:     if (&hostname($homsvr) ne '') {
 4774:         my ($rdummy,$roledef)=
 4775:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 4776:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 4777:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 4778:             if (defined($syspriv)) {
 4779:                 if ($trest =~ /^$match_community$/) {
 4780:                     $syspriv =~ s/bre\&S//; 
 4781:                 }
 4782:                 $$allroles{'cm./'}.=':'.$syspriv;
 4783:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 4784:             }
 4785:             if ($tdomain ne '') {
 4786:                 if (defined($dompriv)) {
 4787:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 4788:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 4789:                 }
 4790:                 if (($trest ne '') && (defined($coursepriv))) {
 4791:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 4792:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 4793:                 }
 4794:             }
 4795:         }
 4796:     }
 4797: }
 4798: 
 4799: sub group_roleprivs {
 4800:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 4801:     my $access = 1;
 4802:     my $now = time;
 4803:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 4804:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 4805:     if ($access) {
 4806:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 4807:         $$allgroups{$course}{$group} .=':'.$group_privs;
 4808:     }
 4809: }
 4810: 
 4811: sub standard_roleprivs {
 4812:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 4813:     if (defined($pr{$trole.':s'})) {
 4814:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 4815:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 4816:     }
 4817:     if ($tdomain ne '') {
 4818:         if (defined($pr{$trole.':d'})) {
 4819:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 4820:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 4821:         }
 4822:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 4823:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 4824:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 4825:         }
 4826:     }
 4827: }
 4828: 
 4829: sub set_userprivs {
 4830:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 4831:     my $author=0;
 4832:     my $adv=0;
 4833:     my %grouproles = ();
 4834:     if (keys(%{$allgroups}) > 0) {
 4835:         my @groupkeys; 
 4836:         foreach my $role (keys(%{$allroles})) {
 4837:             push(@groupkeys,$role);
 4838:         }
 4839:         if (ref($groups_roles) eq 'HASH') {
 4840:             foreach my $key (keys(%{$groups_roles})) {
 4841:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 4842:                     push(@groupkeys,$key);
 4843:                 }
 4844:             }
 4845:         }
 4846:         if (@groupkeys > 0) {
 4847:             foreach my $role (@groupkeys) {
 4848:                 my ($trole,$area,$sec,$extendedarea);
 4849:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 4850:                     $trole = $1;
 4851:                     $area = $2;
 4852:                     $sec = $3;
 4853:                     $extendedarea = $area.$sec;
 4854:                     if (exists($$allgroups{$area})) {
 4855:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 4856:                             my $spec = $trole.'.'.$extendedarea;
 4857:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 4858:                                                 $$allgroups{$area}{$group};
 4859:                         }
 4860:                     }
 4861:                 }
 4862:             }
 4863:         }
 4864:     }
 4865:     foreach my $group (keys(%grouproles)) {
 4866:         $$allroles{$group} = $grouproles{$group};
 4867:     }
 4868:     foreach my $role (keys(%{$allroles})) {
 4869:         my %thesepriv;
 4870:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 4871:         foreach my $item (split(/:/,$$allroles{$role})) {
 4872:             if ($item ne '') {
 4873:                 my ($privilege,$restrictions)=split(/&/,$item);
 4874:                 if ($restrictions eq '') {
 4875:                     $thesepriv{$privilege}='F';
 4876:                 } elsif ($thesepriv{$privilege} ne 'F') {
 4877:                     $thesepriv{$privilege}.=$restrictions;
 4878:                 }
 4879:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 4880:             }
 4881:         }
 4882:         my $thesestr='';
 4883:         foreach my $priv (sort(keys(%thesepriv))) {
 4884: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 4885: 	}
 4886:         $userroles->{'user.priv.'.$role} = $thesestr;
 4887:     }
 4888:     return ($author,$adv);
 4889: }
 4890: 
 4891: sub role_status {
 4892:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 4893:     my @pwhere = ();
 4894:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 4895:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
 4896:         unless (!defined($$role) || $$role eq '') {
 4897:             $$where=join('.',@pwhere);
 4898:             $$trolecode=$$role.'.'.$$where;
 4899:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 4900:             $$tstatus='is';
 4901:             if ($$tstart && $$tstart>$update) {
 4902:                 $$tstatus='future';
 4903:                 if ($$tstart<$now) {
 4904:                     if ($$tstart && $$tstart>$refresh) {
 4905:                         if (($$where ne '') && ($$role ne '')) {
 4906:                             my (%allroles,%allgroups,$group_privs,
 4907:                                 %groups_roles,@rolecodes);
 4908:                             my %userroles = (
 4909:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 4910:                             );
 4911:                             @rolecodes = ('cm'); 
 4912:                             my $spec=$$role.'.'.$$where;
 4913:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 4914:                             if ($$role =~ /^cr\//) {
 4915:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 4916:                                 push(@rolecodes,'cr');
 4917:                             } elsif ($$role eq 'gr') {
 4918:                                 push(@rolecodes,$$role);
 4919:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 4920:                                                     $env{'user.name'});
 4921:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 4922:                                 (undef,my $group_privs) = split(/\//,$trole);
 4923:                                 $group_privs = &unescape($group_privs);
 4924:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 4925:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 4926:                                 &get_groups_roles($tdomain,$trest,
 4927:                                                   \%course_roles,\@rolecodes,
 4928:                                                   \%groups_roles);
 4929:                             } else {
 4930:                                 push(@rolecodes,$$role);
 4931:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 4932:                             }
 4933:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
 4934:                             &appenv(\%userroles,\@rolecodes);
 4935:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 4936:                         }
 4937:                     }
 4938:                     $$tstatus = 'is';
 4939:                 }
 4940:             }
 4941:             if ($$tend) {
 4942:                 if ($$tend<$update) {
 4943:                     $$tstatus='expired';
 4944:                 } elsif ($$tend<$now) {
 4945:                     $$tstatus='will_not';
 4946:                 }
 4947:             }
 4948:         }
 4949:     }
 4950: }
 4951: 
 4952: sub get_groups_roles {
 4953:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 4954:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 4955:                   (ref($rolecodes) eq 'ARRAY') && 
 4956:                   (ref($groups_roles) eq 'HASH')); 
 4957:     if (keys(%{$cdom_courseroles}) > 0) {
 4958:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 4959:         if ($cdom ne '' && $cnum ne '') {
 4960:             foreach my $key (keys(%{$cdom_courseroles})) {
 4961:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 4962:                     my $crsrole = $1;
 4963:                     my $crssec = $2;
 4964:                     if ($crsrole =~ /^cr/) {
 4965:                         unless (grep(/^cr$/,@{$rolecodes})) {
 4966:                             push(@{$rolecodes},'cr');
 4967:                         }
 4968:                     } else {
 4969:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 4970:                             push(@{$rolecodes},$crsrole);
 4971:                         }
 4972:                     }
 4973:                     my $rolekey = "$crsrole./$cdom/$cnum";
 4974:                     if ($crssec ne '') {
 4975:                         $rolekey .= "/$crssec";
 4976:                     }
 4977:                     $rolekey .= './';
 4978:                     $groups_roles->{$rolekey} = $rolecodes;
 4979:                 }
 4980:             }
 4981:         }
 4982:     }
 4983:     return;
 4984: }
 4985: 
 4986: sub delete_env_groupprivs {
 4987:     my ($where,$courseroles,$possroles) = @_;
 4988:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 4989:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 4990:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 4991:         %{$courseroles->{$udom}} =
 4992:             &get_my_roles('','','userroles',['active'],
 4993:                           $possroles,[$udom],1);
 4994:     }
 4995:     if (ref($courseroles->{$udom}) eq 'HASH') {
 4996:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 4997:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 4998:             my $area = '/'.$cdom.'/'.$cnum;
 4999:             my $privkey = "user.priv.$crsrole.$area";
 5000:             if ($crssec ne '') {
 5001:                 $privkey .= '/'.$crssec;
 5002:             }
 5003:             $privkey .= ".$area/$group";
 5004:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 5005:         }
 5006:     }
 5007:     return;
 5008: }
 5009: 
 5010: sub check_adhoc_privs {
 5011:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
 5012:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 5013:     if ($env{$cckey}) {
 5014:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 5015:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 5016:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 5017:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 5018:         }
 5019:     } else {
 5020:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 5021:     }
 5022: }
 5023: 
 5024: sub set_adhoc_privileges {
 5025: # role can be cc or ca
 5026:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
 5027:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 5028:     my $spec = $role.'.'.$area;
 5029:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 5030:                                   $env{'user.name'});
 5031:     my %ccrole = ();
 5032:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
 5033:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
 5034:     &appenv(\%userroles,[$role,'cm']);
 5035:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 5036:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
 5037:         &appenv( {'request.role'        => $spec,
 5038:                   'request.role.domain' => $dcdom,
 5039:                   'request.course.sec'  => ''
 5040:                  }
 5041:                );
 5042:         my $tadv=0;
 5043:         if (&allowed('adv') eq 'F') { $tadv=1; }
 5044:         &appenv({'request.role.adv'    => $tadv});
 5045:     }
 5046: }
 5047: 
 5048: # --------------------------------------------------------------- get interface
 5049: 
 5050: sub get {
 5051:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5052:    my $items='';
 5053:    foreach my $item (@$storearr) {
 5054:        $items.=&escape($item).'&';
 5055:    }
 5056:    $items=~s/\&$//;
 5057:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5058:    if (!$uname) { $uname=$env{'user.name'}; }
 5059:    my $uhome=&homeserver($uname,$udomain);
 5060: 
 5061:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 5062:    my @pairs=split(/\&/,$rep);
 5063:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 5064:      return @pairs;
 5065:    }
 5066:    my %returnhash=();
 5067:    my $i=0;
 5068:    foreach my $item (@$storearr) {
 5069:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 5070:       $i++;
 5071:    }
 5072:    return %returnhash;
 5073: }
 5074: 
 5075: # --------------------------------------------------------------- del interface
 5076: 
 5077: sub del {
 5078:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5079:    my $items='';
 5080:    foreach my $item (@$storearr) {
 5081:        $items.=&escape($item).'&';
 5082:    }
 5083: 
 5084:    $items=~s/\&$//;
 5085:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5086:    if (!$uname) { $uname=$env{'user.name'}; }
 5087:    my $uhome=&homeserver($uname,$udomain);
 5088:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 5089: }
 5090: 
 5091: # -------------------------------------------------------------- dump interface
 5092: 
 5093: sub unserialize {
 5094:     my ($rep, $escapedkeys) = @_;
 5095: 
 5096:     return {} if $rep =~ /^error/;
 5097: 
 5098:     my %returnhash=();
 5099: 	foreach my $item (split /\&/, $rep) {
 5100: 	    my ($key, $value) = split(/=/, $item, 2);
 5101: 	    $key = unescape($key) unless $escapedkeys;
 5102: 	    next if $key =~ /^error: 2 /;
 5103: 	    $returnhash{$key} = Apache::lonnet::thaw_unescape($value);
 5104: 	}
 5105:     #return %returnhash;
 5106:     return \%returnhash;
 5107: }        
 5108: 
 5109: # see Lond::dump_with_regexp
 5110: # if $escapedkeys hash keys won't get unescaped.
 5111: sub dump {
 5112:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
 5113:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5114:     if (!$uname) { $uname=$env{'user.name'}; }
 5115:     my $uhome=&homeserver($uname,$udomain);
 5116: 
 5117:     my $reply;
 5118:     if (grep { $_ eq $uhome } current_machine_ids()) {
 5119:         # user is hosted on this machine
 5120:         $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
 5121:                     $uname, $namespace, $regexp, $range)), $loncaparevs{$uhome});
 5122:         return %{unserialize($reply, $escapedkeys)};
 5123:     }
 5124:     if ($regexp) {
 5125: 	$regexp=&escape($regexp);
 5126:     } else {
 5127: 	$regexp='.';
 5128:     }
 5129:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 5130:     my @pairs=split(/\&/,$rep);
 5131:     my %returnhash=();
 5132:     if (!($rep =~ /^error/ )) {
 5133: 	foreach my $item (@pairs) {
 5134: 	    my ($key,$value)=split(/=/,$item,2);
 5135:         $key = unescape($key) unless $escapedkeys;
 5136:         #$key = &unescape($key);
 5137: 	    next if ($key =~ /^error: 2 /);
 5138: 	    $returnhash{$key}=&thaw_unescape($value);
 5139: 	}
 5140:     }
 5141:     return %returnhash;
 5142: }
 5143: 
 5144: 
 5145: # --------------------------------------------------------- dumpstore interface
 5146: 
 5147: sub dumpstore {
 5148:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 5149:    # same as dump but keys must be escaped. They may contain colon separated
 5150:    # lists of values that may themself contain colons (e.g. symbs).
 5151:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
 5152: }
 5153: 
 5154: # -------------------------------------------------------------- keys interface
 5155: 
 5156: sub getkeys {
 5157:    my ($namespace,$udomain,$uname)=@_;
 5158:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5159:    if (!$uname) { $uname=$env{'user.name'}; }
 5160:    my $uhome=&homeserver($uname,$udomain);
 5161:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 5162:    my @keyarray=();
 5163:    foreach my $key (split(/\&/,$rep)) {
 5164:       next if ($key =~ /^error: 2 /);
 5165:       push(@keyarray,&unescape($key));
 5166:    }
 5167:    return @keyarray;
 5168: }
 5169: 
 5170: # --------------------------------------------------------------- currentdump
 5171: sub currentdump {
 5172:    my ($courseid,$sdom,$sname)=@_;
 5173:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 5174:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 5175:    $sname    = $env{'user.name'}         if (! defined($sname));
 5176:    my $uhome = &homeserver($sname,$sdom);
 5177:    my $rep;
 5178: 
 5179:    if (grep { $_ eq $uhome } current_machine_ids()) {
 5180:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
 5181:                    $courseid)));
 5182:    } else {
 5183:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 5184:    }
 5185: 
 5186:    return if ($rep =~ /^(error:|no_such_host)/);
 5187:    #
 5188:    my %returnhash=();
 5189:    #
 5190:    if ($rep eq "unknown_cmd") { 
 5191:        # an old lond will not know currentdump
 5192:        # Do a dump and make it look like a currentdump
 5193:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 5194:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 5195:        my %hash = @tmp;
 5196:        @tmp=();
 5197:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 5198:    } else {
 5199:        my @pairs=split(/\&/,$rep);
 5200:        foreach my $pair (@pairs) {
 5201:            my ($key,$value)=split(/=/,$pair,2);
 5202:            my ($symb,$param) = split(/:/,$key);
 5203:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 5204:                                                         &thaw_unescape($value);
 5205:        }
 5206:    }
 5207:    return %returnhash;
 5208: }
 5209: 
 5210: sub convert_dump_to_currentdump{
 5211:     my %hash = %{shift()};
 5212:     my %returnhash;
 5213:     # Code ripped from lond, essentially.  The only difference
 5214:     # here is the unescaping done by lonnet::dump().  Conceivably
 5215:     # we might run in to problems with parameter names =~ /^v\./
 5216:     while (my ($key,$value) = each(%hash)) {
 5217:         my ($v,$symb,$param) = split(/:/,$key);
 5218: 	$symb  = &unescape($symb);
 5219: 	$param = &unescape($param);
 5220:         next if ($v eq 'version' || $symb eq 'keys');
 5221:         next if (exists($returnhash{$symb}) &&
 5222:                  exists($returnhash{$symb}->{$param}) &&
 5223:                  $returnhash{$symb}->{'v.'.$param} > $v);
 5224:         $returnhash{$symb}->{$param}=$value;
 5225:         $returnhash{$symb}->{'v.'.$param}=$v;
 5226:     }
 5227:     #
 5228:     # Remove all of the keys in the hashes which keep track of
 5229:     # the version of the parameter.
 5230:     while (my ($symb,$param_hash) = each(%returnhash)) {
 5231:         # use a foreach because we are going to delete from the hash.
 5232:         foreach my $key (keys(%$param_hash)) {
 5233:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 5234:         }
 5235:     }
 5236:     return \%returnhash;
 5237: }
 5238: 
 5239: # ------------------------------------------------------ critical inc interface
 5240: 
 5241: sub cinc {
 5242:     return &inc(@_,'critical');
 5243: }
 5244: 
 5245: # --------------------------------------------------------------- inc interface
 5246: 
 5247: sub inc {
 5248:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 5249:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5250:     if (!$uname) { $uname=$env{'user.name'}; }
 5251:     my $uhome=&homeserver($uname,$udomain);
 5252:     my $items='';
 5253:     if (! ref($store)) {
 5254:         # got a single value, so use that instead
 5255:         $items = &escape($store).'=&';
 5256:     } elsif (ref($store) eq 'SCALAR') {
 5257:         $items = &escape($$store).'=&';        
 5258:     } elsif (ref($store) eq 'ARRAY') {
 5259:         $items = join('=&',map {&escape($_);} @{$store});
 5260:     } elsif (ref($store) eq 'HASH') {
 5261:         while (my($key,$value) = each(%{$store})) {
 5262:             $items.= &escape($key).'='.&escape($value).'&';
 5263:         }
 5264:     }
 5265:     $items=~s/\&$//;
 5266:     if ($critical) {
 5267: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 5268:     } else {
 5269: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 5270:     }
 5271: }
 5272: 
 5273: # --------------------------------------------------------------- put interface
 5274: 
 5275: sub put {
 5276:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5277:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5278:    if (!$uname) { $uname=$env{'user.name'}; }
 5279:    my $uhome=&homeserver($uname,$udomain);
 5280:    my $items='';
 5281:    foreach my $item (keys(%$storehash)) {
 5282:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5283:    }
 5284:    $items=~s/\&$//;
 5285:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5286: }
 5287: 
 5288: # ------------------------------------------------------------ newput interface
 5289: 
 5290: sub newput {
 5291:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5292:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5293:    if (!$uname) { $uname=$env{'user.name'}; }
 5294:    my $uhome=&homeserver($uname,$udomain);
 5295:    my $items='';
 5296:    foreach my $key (keys(%$storehash)) {
 5297:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 5298:    }
 5299:    $items=~s/\&$//;
 5300:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 5301: }
 5302: 
 5303: # ---------------------------------------------------------  putstore interface
 5304: 
 5305: sub putstore {
 5306:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 5307:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5308:    if (!$uname) { $uname=$env{'user.name'}; }
 5309:    my $uhome=&homeserver($uname,$udomain);
 5310:    my $items='';
 5311:    foreach my $key (keys(%$storehash)) {
 5312:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 5313:    }
 5314:    $items=~s/\&$//;
 5315:    my $esc_symb=&escape($symb);
 5316:    my $esc_v=&escape($version);
 5317:    my $reply =
 5318:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 5319: 	      $uhome);
 5320:    if ($reply eq 'unknown_cmd') {
 5321:        # gfall back to way things use to be done
 5322:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 5323: 			    $uname);
 5324:    }
 5325:    return $reply;
 5326: }
 5327: 
 5328: sub old_putstore {
 5329:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 5330:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5331:     if (!$uname) { $uname=$env{'user.name'}; }
 5332:     my $uhome=&homeserver($uname,$udomain);
 5333:     my %newstorehash;
 5334:     foreach my $item (keys(%$storehash)) {
 5335: 	my $key = $version.':'.&escape($symb).':'.$item;
 5336: 	$newstorehash{$key} = $storehash->{$item};
 5337:     }
 5338:     my $items='';
 5339:     my %allitems = ();
 5340:     foreach my $item (keys(%newstorehash)) {
 5341: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 5342: 	    my $key = $1.':keys:'.$2;
 5343: 	    $allitems{$key} .= $3.':';
 5344: 	}
 5345: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 5346:     }
 5347:     foreach my $item (keys(%allitems)) {
 5348: 	$allitems{$item} =~ s/\:$//;
 5349: 	$items.= $item.'='.$allitems{$item}.'&';
 5350:     }
 5351:     $items=~s/\&$//;
 5352:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5353: }
 5354: 
 5355: # ------------------------------------------------------ critical put interface
 5356: 
 5357: sub cput {
 5358:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5359:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5360:    if (!$uname) { $uname=$env{'user.name'}; }
 5361:    my $uhome=&homeserver($uname,$udomain);
 5362:    my $items='';
 5363:    foreach my $item (keys(%$storehash)) {
 5364:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5365:    }
 5366:    $items=~s/\&$//;
 5367:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 5368: }
 5369: 
 5370: # -------------------------------------------------------------- eget interface
 5371: 
 5372: sub eget {
 5373:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5374:    my $items='';
 5375:    foreach my $item (@$storearr) {
 5376:        $items.=&escape($item).'&';
 5377:    }
 5378:    $items=~s/\&$//;
 5379:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5380:    if (!$uname) { $uname=$env{'user.name'}; }
 5381:    my $uhome=&homeserver($uname,$udomain);
 5382:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 5383:    my @pairs=split(/\&/,$rep);
 5384:    my %returnhash=();
 5385:    my $i=0;
 5386:    foreach my $item (@$storearr) {
 5387:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 5388:       $i++;
 5389:    }
 5390:    return %returnhash;
 5391: }
 5392: 
 5393: # ------------------------------------------------------------ tmpput interface
 5394: sub tmpput {
 5395:     my ($storehash,$server,$context)=@_;
 5396:     my $items='';
 5397:     foreach my $item (keys(%$storehash)) {
 5398: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5399:     }
 5400:     $items=~s/\&$//;
 5401:     if (defined($context)) {
 5402:         $items .= ':'.&escape($context);
 5403:     }
 5404:     return &reply("tmpput:$items",$server);
 5405: }
 5406: 
 5407: # ------------------------------------------------------------ tmpget interface
 5408: sub tmpget {
 5409:     my ($token,$server)=@_;
 5410:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 5411:     my $rep=&reply("tmpget:$token",$server);
 5412:     my %returnhash;
 5413:     foreach my $item (split(/\&/,$rep)) {
 5414: 	my ($key,$value)=split(/=/,$item);
 5415:         next if ($key =~ /^error: 2 /);
 5416: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 5417:     }
 5418:     return %returnhash;
 5419: }
 5420: 
 5421: # ------------------------------------------------------------ tmpdel interface
 5422: sub tmpdel {
 5423:     my ($token,$server)=@_;
 5424:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 5425:     return &reply("tmpdel:$token",$server);
 5426: }
 5427: 
 5428: # -------------------------------------------------- portfolio access checking
 5429: 
 5430: sub portfolio_access {
 5431:     my ($requrl) = @_;
 5432:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 5433:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 5434:     if ($result) {
 5435:         my %setters;
 5436:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 5437:             my ($startblock,$endblock) =
 5438:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 5439:             if ($startblock && $endblock) {
 5440:                 return 'B';
 5441:             }
 5442:         } else {
 5443:             my ($startblock,$endblock) =
 5444:                 &Apache::loncommon::blockcheck(\%setters,'port');
 5445:             if ($startblock && $endblock) {
 5446:                 return 'B';
 5447:             }
 5448:         }
 5449:     }
 5450:     if ($result eq 'ok') {
 5451:        return 'F';
 5452:     } elsif ($result =~ /^[^:]+:guest_/) {
 5453:        return 'A';
 5454:     }
 5455:     return '';
 5456: }
 5457: 
 5458: sub get_portfolio_access {
 5459:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 5460: 
 5461:     if (!ref($access_hash)) {
 5462: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 5463: 	my %access_controls = &get_access_controls($current_perms,$group,
 5464: 						   $file_name);
 5465: 	$access_hash = $access_controls{$file_name};
 5466:     }
 5467: 
 5468:     my ($public,$guest,@domains,@users,@courses,@groups);
 5469:     my $now = time;
 5470:     if (ref($access_hash) eq 'HASH') {
 5471:         foreach my $key (keys(%{$access_hash})) {
 5472:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 5473:             if ($start > $now) {
 5474:                 next;
 5475:             }
 5476:             if ($end && $end<$now) {
 5477:                 next;
 5478:             }
 5479:             if ($scope eq 'public') {
 5480:                 $public = $key;
 5481:                 last;
 5482:             } elsif ($scope eq 'guest') {
 5483:                 $guest = $key;
 5484:             } elsif ($scope eq 'domains') {
 5485:                 push(@domains,$key);
 5486:             } elsif ($scope eq 'users') {
 5487:                 push(@users,$key);
 5488:             } elsif ($scope eq 'course') {
 5489:                 push(@courses,$key);
 5490:             } elsif ($scope eq 'group') {
 5491:                 push(@groups,$key);
 5492:             }
 5493:         }
 5494:         if ($public) {
 5495:             return 'ok';
 5496:         }
 5497:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 5498:             if ($guest) {
 5499:                 return $guest;
 5500:             }
 5501:         } else {
 5502:             if (@domains > 0) {
 5503:                 foreach my $domkey (@domains) {
 5504:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 5505:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 5506:                             return 'ok';
 5507:                         }
 5508:                     }
 5509:                 }
 5510:             }
 5511:             if (@users > 0) {
 5512:                 foreach my $userkey (@users) {
 5513:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 5514:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 5515:                             if (ref($item) eq 'HASH') {
 5516:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 5517:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 5518:                                     return 'ok';
 5519:                                 }
 5520:                             }
 5521:                         }
 5522:                     } 
 5523:                 }
 5524:             }
 5525:             my %roleshash;
 5526:             my @courses_and_groups = @courses;
 5527:             push(@courses_and_groups,@groups); 
 5528:             if (@courses_and_groups > 0) {
 5529:                 my (%allgroups,%allroles); 
 5530:                 my ($start,$end,$role,$sec,$group);
 5531:                 foreach my $envkey (%env) {
 5532:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 5533:                         my $cid = $2.'_'.$3; 
 5534:                         if ($1 eq 'gr') {
 5535:                             $group = $4;
 5536:                             $allgroups{$cid}{$group} = $env{$envkey};
 5537:                         } else {
 5538:                             if ($4 eq '') {
 5539:                                 $sec = 'none';
 5540:                             } else {
 5541:                                 $sec = $4;
 5542:                             }
 5543:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 5544:                         }
 5545:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 5546:                         my $cid = $2.'_'.$3;
 5547:                         if ($4 eq '') {
 5548:                             $sec = 'none';
 5549:                         } else {
 5550:                             $sec = $4;
 5551:                         }
 5552:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 5553:                     }
 5554:                 }
 5555:                 if (keys(%allroles) == 0) {
 5556:                     return;
 5557:                 }
 5558:                 foreach my $key (@courses_and_groups) {
 5559:                     my %content = %{$$access_hash{$key}};
 5560:                     my $cnum = $content{'number'};
 5561:                     my $cdom = $content{'domain'};
 5562:                     my $cid = $cdom.'_'.$cnum;
 5563:                     if (!exists($allroles{$cid})) {
 5564:                         next;
 5565:                     }    
 5566:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 5567:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 5568:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 5569:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 5570:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 5571:                         foreach my $role (keys(%{$allroles{$cid}})) {
 5572:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 5573:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 5574:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 5575:                                         if (grep/^all$/,@sections) {
 5576:                                             return 'ok';
 5577:                                         } else {
 5578:                                             if (grep/^$sec$/,@sections) {
 5579:                                                 return 'ok';
 5580:                                             }
 5581:                                         }
 5582:                                     }
 5583:                                 }
 5584:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 5585:                                     if (grep/^none$/,@groups) {
 5586:                                         return 'ok';
 5587:                                     }
 5588:                                 } else {
 5589:                                     if (grep/^all$/,@groups) {
 5590:                                         return 'ok';
 5591:                                     } 
 5592:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 5593:                                         if (grep/^$group$/,@groups) {
 5594:                                             return 'ok';
 5595:                                         }
 5596:                                     }
 5597:                                 } 
 5598:                             }
 5599:                         }
 5600:                     }
 5601:                 }
 5602:             }
 5603:             if ($guest) {
 5604:                 return $guest;
 5605:             }
 5606:         }
 5607:     }
 5608:     return;
 5609: }
 5610: 
 5611: sub course_group_datechecker {
 5612:     my ($dates,$now,$status) = @_;
 5613:     my ($start,$end) = split(/\./,$dates);
 5614:     if (!$start && !$end) {
 5615:         return 'ok';
 5616:     }
 5617:     if (grep/^active$/,@{$status}) {
 5618:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 5619:             return 'ok';
 5620:         }
 5621:     }
 5622:     if (grep/^previous$/,@{$status}) {
 5623:         if ($end > $now ) {
 5624:             return 'ok';
 5625:         }
 5626:     }
 5627:     if (grep/^future$/,@{$status}) {
 5628:         if ($start > $now) {
 5629:             return 'ok';
 5630:         }
 5631:     }
 5632:     return; 
 5633: }
 5634: 
 5635: sub parse_portfolio_url {
 5636:     my ($url) = @_;
 5637: 
 5638:     my ($type,$udom,$unum,$group,$file_name);
 5639:     
 5640:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 5641: 	$type = 1;
 5642:         $udom = $1;
 5643:         $unum = $2;
 5644:         $file_name = $3;
 5645:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 5646: 	$type = 2;
 5647:         $udom = $1;
 5648:         $unum = $2;
 5649:         $group = $3;
 5650:         $file_name = $3.'/'.$4;
 5651:     }
 5652:     if (wantarray) {
 5653: 	return ($type,$udom,$unum,$file_name,$group);
 5654:     }
 5655:     return $type;
 5656: }
 5657: 
 5658: sub is_portfolio_url {
 5659:     my ($url) = @_;
 5660:     return scalar(&parse_portfolio_url($url));
 5661: }
 5662: 
 5663: sub is_portfolio_file {
 5664:     my ($file) = @_;
 5665:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 5666:         return 1;
 5667:     }
 5668:     return;
 5669: }
 5670: 
 5671: sub usertools_access {
 5672:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 5673:     my ($access,%tools);
 5674:     if ($context eq '') {
 5675:         $context = 'tools';
 5676:     }
 5677:     if ($context eq 'requestcourses') {
 5678:         %tools = (
 5679:                       official   => 1,
 5680:                       unofficial => 1,
 5681:                       community  => 1,
 5682:                  );
 5683:     } else {
 5684:         %tools = (
 5685:                       aboutme   => 1,
 5686:                       blog      => 1,
 5687:                       webdav    => 1,
 5688:                       portfolio => 1,
 5689:                  );
 5690:     }
 5691:     return if (!defined($tools{$tool}));
 5692: 
 5693:     if ((!defined($udom)) || (!defined($uname))) {
 5694:         $udom = $env{'user.domain'};
 5695:         $uname = $env{'user.name'};
 5696:     }
 5697: 
 5698:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 5699:         if ($action ne 'reload') {
 5700:             if ($context eq 'requestcourses') {
 5701:                 return $env{'environment.canrequest.'.$tool};
 5702:             } else {
 5703:                 return $env{'environment.availabletools.'.$tool};
 5704:             }
 5705:         }
 5706:     }
 5707: 
 5708:     my ($toolstatus,$inststatus);
 5709: 
 5710:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 5711:          ($action ne 'reload')) {
 5712:         $toolstatus = $env{'environment.'.$context.'.'.$tool};
 5713:         $inststatus = $env{'environment.inststatus'};
 5714:     } else {
 5715:         if (ref($userenvref) eq 'HASH') {
 5716:             $toolstatus = $userenvref->{$context.'.'.$tool};
 5717:             $inststatus = $userenvref->{'inststatus'};
 5718:         } else {
 5719:             my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
 5720:             $toolstatus = $userenv{$context.'.'.$tool};
 5721:             $inststatus = $userenv{'inststatus'};
 5722:         }
 5723:     }
 5724: 
 5725:     if ($toolstatus ne '') {
 5726:         if ($toolstatus) {
 5727:             $access = 1;
 5728:         } else {
 5729:             $access = 0;
 5730:         }
 5731:         return $access;
 5732:     }
 5733: 
 5734:     my ($is_adv,%domdef);
 5735:     if (ref($is_advref) eq 'HASH') {
 5736:         $is_adv = $is_advref->{'is_adv'};
 5737:     } else {
 5738:         $is_adv = &is_advanced_user($udom,$uname);
 5739:     }
 5740:     if (ref($domdefref) eq 'HASH') {
 5741:         %domdef = %{$domdefref};
 5742:     } else {
 5743:         %domdef = &get_domain_defaults($udom);
 5744:     }
 5745:     if (ref($domdef{$tool}) eq 'HASH') {
 5746:         if ($is_adv) {
 5747:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 5748:                 if ($domdef{$tool}{'_LC_adv'}) { 
 5749:                     $access = 1;
 5750:                 } else {
 5751:                     $access = 0;
 5752:                 }
 5753:                 return $access;
 5754:             }
 5755:         }
 5756:         if ($inststatus ne '') {
 5757:             my ($hasaccess,$hasnoaccess);
 5758:             foreach my $affiliation (split(/:/,$inststatus)) {
 5759:                 if ($domdef{$tool}{$affiliation} ne '') { 
 5760:                     if ($domdef{$tool}{$affiliation}) {
 5761:                         $hasaccess = 1;
 5762:                     } else {
 5763:                         $hasnoaccess = 1;
 5764:                     }
 5765:                 }
 5766:             }
 5767:             if ($hasaccess || $hasnoaccess) {
 5768:                 if ($hasaccess) {
 5769:                     $access = 1;
 5770:                 } elsif ($hasnoaccess) {
 5771:                     $access = 0; 
 5772:                 }
 5773:                 return $access;
 5774:             }
 5775:         } else {
 5776:             if ($domdef{$tool}{'default'} ne '') {
 5777:                 if ($domdef{$tool}{'default'}) {
 5778:                     $access = 1;
 5779:                 } elsif ($domdef{$tool}{'default'} == 0) {
 5780:                     $access = 0;
 5781:                 }
 5782:                 return $access;
 5783:             }
 5784:         }
 5785:     } else {
 5786:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 5787:             $access = 1;
 5788:         } else {
 5789:             $access = 0;
 5790:         }
 5791:         return $access;
 5792:     }
 5793: }
 5794: 
 5795: sub is_course_owner {
 5796:     my ($cdom,$cnum,$udom,$uname) = @_;
 5797:     if (($udom eq '') || ($uname eq '')) {
 5798:         $udom = $env{'user.domain'};
 5799:         $uname = $env{'user.name'};
 5800:     }
 5801:     unless (($udom eq '') || ($uname eq '')) {
 5802:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 5803:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 5804:                 return 1;
 5805:             } else {
 5806:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 5807:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 5808:                     return 1;
 5809:                 }
 5810:             }
 5811:         }
 5812:     }
 5813:     return;
 5814: }
 5815: 
 5816: sub is_advanced_user {
 5817:     my ($udom,$uname) = @_;
 5818:     if ($udom ne '' && $uname ne '') {
 5819:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 5820:             if (wantarray) {
 5821:                 return ($env{'user.adv'},$env{'user.author'});
 5822:             } else {
 5823:                 return $env{'user.adv'};
 5824:             }
 5825:         }
 5826:     }
 5827:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 5828:     my %allroles;
 5829:     my ($is_adv,$is_author);
 5830:     foreach my $role (keys(%roleshash)) {
 5831:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 5832:         my $area = '/'.$tdomain.'/'.$trest;
 5833:         if ($sec ne '') {
 5834:             $area .= '/'.$sec;
 5835:         }
 5836:         if (($area ne '') && ($trole ne '')) {
 5837:             my $spec=$trole.'.'.$area;
 5838:             if ($trole =~ /^cr\//) {
 5839:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 5840:             } elsif ($trole ne 'gr') {
 5841:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 5842:             }
 5843:             if ($trole eq 'au') {
 5844:                 $is_author = 1;
 5845:             }
 5846:         }
 5847:     }
 5848:     foreach my $role (keys(%allroles)) {
 5849:         last if ($is_adv);
 5850:         foreach my $item (split(/:/,$allroles{$role})) {
 5851:             if ($item ne '') {
 5852:                 my ($privilege,$restrictions)=split(/&/,$item);
 5853:                 if ($privilege eq 'adv') {
 5854:                     $is_adv = 1;
 5855:                     last;
 5856:                 }
 5857:             }
 5858:         }
 5859:     }
 5860:     if (wantarray) {
 5861:         return ($is_adv,$is_author);
 5862:     }
 5863:     return $is_adv;
 5864: }
 5865: 
 5866: sub check_can_request {
 5867:     my ($dom,$can_request,$request_domains) = @_;
 5868:     my $canreq = 0;
 5869:     my ($types,$typename) = &Apache::loncommon::course_types();
 5870:     my @options = ('approval','validate','autolimit');
 5871:     my $optregex = join('|',@options);
 5872:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 5873:         foreach my $type (@{$types}) {
 5874:             if (&usertools_access($env{'user.name'},
 5875:                                   $env{'user.domain'},
 5876:                                   $type,undef,'requestcourses')) {
 5877:                 $canreq ++;
 5878:                 if (ref($request_domains) eq 'HASH') {
 5879:                     push(@{$request_domains->{$type}},$env{'user.domain'});
 5880:                 }
 5881:                 if ($dom eq $env{'user.domain'}) {
 5882:                     $can_request->{$type} = 1;
 5883:                 }
 5884:             }
 5885:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
 5886:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 5887:                 if (@curr > 0) {
 5888:                     foreach my $item (@curr) {
 5889:                         if (ref($request_domains) eq 'HASH') {
 5890:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 5891:                             if ($otherdom ne '') {
 5892:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 5893:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 5894:                                         push(@{$request_domains->{$type}},$otherdom);
 5895:                                     }
 5896:                                 } else {
 5897:                                     push(@{$request_domains->{$type}},$otherdom);
 5898:                                 }
 5899:                             }
 5900:                         }
 5901:                     }
 5902:                     unless($dom eq $env{'user.domain'}) {
 5903:                         $canreq ++;
 5904:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 5905:                             $can_request->{$type} = 1;
 5906:                         }
 5907:                     }
 5908:                 }
 5909:             }
 5910:         }
 5911:     }
 5912:     return $canreq;
 5913: }
 5914: 
 5915: # ---------------------------------------------- Custom access rule evaluation
 5916: 
 5917: sub customaccess {
 5918:     my ($priv,$uri)=@_;
 5919:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 5920:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 5921:     $udom = &LONCAPA::clean_domain($udom);
 5922:     $ucrs = &LONCAPA::clean_username($ucrs);
 5923:     my $access=0;
 5924:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 5925: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 5926: 	if ($type eq 'user') {
 5927: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 5928: 		my ($tdom,$tuname)=split(m{/},$scope);
 5929: 		if ($tdom) {
 5930: 		    if ($tdom ne $env{'user.domain'}) { next; }
 5931: 		}
 5932: 		if ($tuname) {
 5933: 		    if ($tuname ne $env{'user.name'}) { next; }
 5934: 		}
 5935: 		$access=($effect eq 'allow');
 5936: 		last;
 5937: 	    }
 5938: 	} else {
 5939: 	    if ($role) {
 5940: 		if ($role ne $urole) { next; }
 5941: 	    }
 5942: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 5943: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 5944: 		if ($tdom) {
 5945: 		    if ($tdom ne $udom) { next; }
 5946: 		}
 5947: 		if ($tcrs) {
 5948: 		    if ($tcrs ne $ucrs) { next; }
 5949: 		}
 5950: 		if ($tsec) {
 5951: 		    if ($tsec ne $usec) { next; }
 5952: 		}
 5953: 		$access=($effect eq 'allow');
 5954: 		last;
 5955: 	    }
 5956: 	    if ($realm eq '' && $role eq '') {
 5957: 		$access=($effect eq 'allow');
 5958: 	    }
 5959: 	}
 5960:     }
 5961:     return $access;
 5962: }
 5963: 
 5964: # ------------------------------------------------- Check for a user privilege
 5965: 
 5966: sub allowed {
 5967:     my ($priv,$uri,$symb,$role)=@_;
 5968:     my $ver_orguri=$uri;
 5969:     $uri=&deversion($uri);
 5970:     my $orguri=$uri;
 5971:     $uri=&declutter($uri);
 5972: 
 5973:     if ($priv eq 'evb') {
 5974: # Evade communication block restrictions for specified role in a course
 5975:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 5976:             return $1;
 5977:         } else {
 5978:             return;
 5979:         }
 5980:     }
 5981: 
 5982:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 5983: # Free bre access to adm and meta resources
 5984:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 5985: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 5986: 	&& ($priv eq 'bre')) {
 5987: 	return 'F';
 5988:     }
 5989: 
 5990: # Free bre access to user's own portfolio contents
 5991:     my ($space,$domain,$name,@dir)=split('/',$uri);
 5992:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 5993: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 5994:         my %setters;
 5995:         my ($startblock,$endblock) = 
 5996:             &Apache::loncommon::blockcheck(\%setters,'port');
 5997:         if ($startblock && $endblock) {
 5998:             return 'B';
 5999:         } else {
 6000:             return 'F';
 6001:         }
 6002:     }
 6003: 
 6004: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 6005:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 6006:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 6007:         if (exists($env{'request.course.id'})) {
 6008:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6009:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6010:             if (($domain eq $cdom) && ($name eq $cnum)) {
 6011:                 my $courseprivid=$env{'request.course.id'};
 6012:                 $courseprivid=~s/\_/\//;
 6013:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 6014:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 6015:                     return $1; 
 6016:                 } else {
 6017:                     if ($env{'request.course.sec'}) {
 6018:                         $courseprivid.='/'.$env{'request.course.sec'};
 6019:                     }
 6020:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 6021:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 6022:                         return $2;
 6023:                     }
 6024:                 }
 6025:             }
 6026:         }
 6027:     }
 6028: 
 6029: # Free bre to public access
 6030: 
 6031:     if ($priv eq 'bre') {
 6032:         my $copyright=&metadata($uri,'copyright');
 6033: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 6034:            return 'F'; 
 6035:         }
 6036:         if ($copyright eq 'priv') {
 6037:             $uri=~/([^\/]+)\/([^\/]+)\//;
 6038: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 6039: 		return '';
 6040:             }
 6041:         }
 6042:         if ($copyright eq 'domain') {
 6043:             $uri=~/([^\/]+)\/([^\/]+)\//;
 6044: 	    unless (($env{'user.domain'} eq $1) ||
 6045:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 6046: 		return '';
 6047:             }
 6048:         }
 6049:         if ($env{'request.role'}=~ /li\.\//) {
 6050:             # Library role, so allow browsing of resources in this domain.
 6051:             return 'F';
 6052:         }
 6053:         if ($copyright eq 'custom') {
 6054: 	    unless (&customaccess($priv,$uri)) { return ''; }
 6055:         }
 6056:     }
 6057:     # Domain coordinator is trying to create a course
 6058:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 6059:         # uri is the requested domain in this case.
 6060:         # comparison to 'request.role.domain' shows if the user has selected
 6061:         # a role of dc for the domain in question.
 6062:         return 'F' if ($uri eq $env{'request.role.domain'});
 6063:     }
 6064: 
 6065:     my $thisallowed='';
 6066:     my $statecond=0;
 6067:     my $courseprivid='';
 6068: 
 6069:     my $ownaccess;
 6070:     # Community Coordinator or Assistant Co-author browsing resource space.
 6071:     if (($priv eq 'bro') && ($env{'user.author'})) {
 6072:         if ($uri eq '') {
 6073:             $ownaccess = 1;
 6074:         } else {
 6075:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 6076:                 my $udom = $env{'user.domain'};
 6077:                 my $uname = $env{'user.name'};
 6078:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 6079:                     $ownaccess = 1;
 6080:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 6081:                     unless ($uri =~ m{\.\./}) {
 6082:                         $ownaccess = 1;
 6083:                     }
 6084:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 6085:                     my $now = time;
 6086:                     if ($uri =~ m{^([^/]+)/?$}) {
 6087:                         my $adom = $1;
 6088:                         foreach my $key (keys(%env)) {
 6089:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 6090:                                 my ($start,$end) = split('.',$env{$key});
 6091:                                 if (($now >= $start) && (!$end || $end < $now)) {
 6092:                                     $ownaccess = 1;
 6093:                                     last;
 6094:                                 }
 6095:                             }
 6096:                         }
 6097:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 6098:                         my $adom = $1;
 6099:                         my $aname = $2;
 6100:                         foreach my $role ('ca','aa') { 
 6101:                             if ($env{"user.role.$role./$adom/$aname"}) {
 6102:                                 my ($start,$end) =
 6103:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 6104:                                 if (($now >= $start) && (!$end || $end < $now)) {
 6105:                                     $ownaccess = 1;
 6106:                                     last;
 6107:                                 }
 6108:                             }
 6109:                         }
 6110:                     }
 6111:                 }
 6112:             }
 6113:         }
 6114:     }
 6115: 
 6116: # Course
 6117: 
 6118:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 6119:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6120:             $thisallowed.=$1;
 6121:         }
 6122:     }
 6123: 
 6124: # Domain
 6125: 
 6126:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 6127:        =~/\Q$priv\E\&([^\:]*)/) {
 6128:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6129:             $thisallowed.=$1;
 6130:         }
 6131:     }
 6132: 
 6133: # User who is not author or co-author might still be able to edit
 6134: # resource of an author in the domain (e.g., if Domain Coordinator).
 6135:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 6136:         (&allowed('mdc',$env{'request.course.id'}))) {
 6137:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 6138:             $thisallowed.=$1;
 6139:         }
 6140:     }
 6141: 
 6142: # Course: uri itself is a course
 6143:     my $courseuri=$uri;
 6144:     $courseuri=~s/\_(\d)/\/$1/;
 6145:     $courseuri=~s/^([^\/])/\/$1/;
 6146: 
 6147:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 6148:        =~/\Q$priv\E\&([^\:]*)/) {
 6149:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6150:             $thisallowed.=$1;
 6151:         }
 6152:     }
 6153: 
 6154: # URI is an uploaded document for this course, default permissions don't matter
 6155: # not allowing 'edit' access (editupload) to uploaded course docs
 6156:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 6157: 	$thisallowed='';
 6158:         my ($match)=&is_on_map($uri);
 6159:         if ($match) {
 6160:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 6161:                   =~/\Q$priv\E\&([^\:]*)/) {
 6162:                 my @blockers = &has_comm_blocking($priv,$symb,$uri);
 6163:                 if (@blockers > 0) {
 6164:                     $thisallowed = 'B';
 6165:                 } else {
 6166:                     $thisallowed.=$1;
 6167:                 }
 6168:             }
 6169:         } else {
 6170:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 6171:             if ($refuri) {
 6172:                 if ($refuri =~ m|^/adm/|) {
 6173:                     $thisallowed='F';
 6174:                 } else {
 6175:                     $refuri=&declutter($refuri);
 6176:                     my ($match) = &is_on_map($refuri);
 6177:                     if ($match) {
 6178:                         my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 6179:                         if (@blockers > 0) {
 6180:                             $thisallowed = 'B';
 6181:                         } else {
 6182:                             $thisallowed='F';
 6183:                         }
 6184:                     }
 6185:                 }
 6186:             }
 6187:         }
 6188:     }
 6189: 
 6190:     if ($priv eq 'bre'
 6191: 	&& $thisallowed ne 'F' 
 6192: 	&& $thisallowed ne '2'
 6193: 	&& &is_portfolio_url($uri)) {
 6194: 	$thisallowed = &portfolio_access($uri);
 6195:     }
 6196:     
 6197: # Full access at system, domain or course-wide level? Exit.
 6198:     if ($thisallowed=~/F/) {
 6199: 	return 'F';
 6200:     }
 6201: 
 6202: # If this is generating or modifying users, exit with special codes
 6203: 
 6204:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 6205: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 6206: 	    my ($audom,$auname)=split('/',$uri);
 6207: # no author name given, so this just checks on the general right to make a co-author in this domain
 6208: 	    unless ($auname) { return $thisallowed; }
 6209: # an author name is given, so we are about to actually make a co-author for a certain account
 6210: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 6211: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 6212: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 6213: 	}
 6214: 	return $thisallowed;
 6215:     }
 6216: #
 6217: # Gathered so far: system, domain and course wide privileges
 6218: #
 6219: # Course: See if uri or referer is an individual resource that is part of 
 6220: # the course
 6221: 
 6222:     if ($env{'request.course.id'}) {
 6223: 
 6224:        $courseprivid=$env{'request.course.id'};
 6225:        if ($env{'request.course.sec'}) {
 6226:           $courseprivid.='/'.$env{'request.course.sec'};
 6227:        }
 6228:        $courseprivid=~s/\_/\//;
 6229:        my $checkreferer=1;
 6230:        my ($match,$cond)=&is_on_map($uri);
 6231:        if ($match) {
 6232:            $statecond=$cond;
 6233:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 6234:                =~/\Q$priv\E\&([^\:]*)/) {
 6235:                my $value = $1;
 6236:                if ($priv eq 'bre') {
 6237:                    my @blockers = &has_comm_blocking($priv,$symb,$uri);
 6238:                    if (@blockers > 0) {
 6239:                        $thisallowed = 'B';
 6240:                    } else {
 6241:                        $thisallowed.=$value;
 6242:                    }
 6243:                } else {
 6244:                    $thisallowed.=$value;
 6245:                }
 6246:                $checkreferer=0;
 6247:            }
 6248:        }
 6249:        
 6250:        if ($checkreferer) {
 6251: 	  my $refuri=$env{'httpref.'.$orguri};
 6252:             unless ($refuri) {
 6253:                 foreach my $key (keys(%env)) {
 6254: 		    if ($key=~/^httpref\..*\*/) {
 6255: 			my $pattern=$key;
 6256:                         $pattern=~s/^httpref\.\/res\///;
 6257:                         $pattern=~s/\*/\[\^\/\]\+/g;
 6258:                         $pattern=~s/\//\\\//g;
 6259:                         if ($orguri=~/$pattern/) {
 6260: 			    $refuri=$env{$key};
 6261:                         }
 6262:                     }
 6263:                 }
 6264:             }
 6265: 
 6266:          if ($refuri) { 
 6267: 	  $refuri=&declutter($refuri);
 6268:           my ($match,$cond)=&is_on_map($refuri);
 6269:             if ($match) {
 6270:               my $refstatecond=$cond;
 6271:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 6272:                   =~/\Q$priv\E\&([^\:]*)/) {
 6273:                   my $value = $1;
 6274:                   if ($priv eq 'bre') {
 6275:                       my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 6276:                       if (@blockers > 0) {
 6277:                           $thisallowed = 'B';
 6278:                       } else {
 6279:                           $thisallowed.=$value;
 6280:                       }
 6281:                   } else {
 6282:                       $thisallowed.=$value;
 6283:                   }
 6284:                   $uri=$refuri;
 6285:                   $statecond=$refstatecond;
 6286:               }
 6287:           }
 6288:         }
 6289:        }
 6290:    }
 6291: 
 6292: #
 6293: # Gathered now: all privileges that could apply, and condition number
 6294: # 
 6295: #
 6296: # Full or no access?
 6297: #
 6298: 
 6299:     if ($thisallowed=~/F/) {
 6300: 	return 'F';
 6301:     }
 6302: 
 6303:     unless ($thisallowed) {
 6304:         return '';
 6305:     }
 6306: 
 6307: # Restrictions exist, deal with them
 6308: #
 6309: #   C:according to course preferences
 6310: #   R:according to resource settings
 6311: #   L:unless locked
 6312: #   X:according to user session state
 6313: #
 6314: 
 6315: # Possibly locked functionality, check all courses
 6316: # Locks might take effect only after 10 minutes cache expiration for other
 6317: # courses, and 2 minutes for current course
 6318: 
 6319:     my $envkey;
 6320:     if ($thisallowed=~/L/) {
 6321:         foreach $envkey (keys(%env)) {
 6322:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 6323:                my $courseid=$2;
 6324:                my $roleid=$1.'.'.$2;
 6325:                $courseid=~s/^\///;
 6326:                my $expiretime=600;
 6327:                if ($env{'request.role'} eq $roleid) {
 6328: 		  $expiretime=120;
 6329:                }
 6330: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 6331:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 6332:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 6333: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 6334:                }
 6335:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 6336:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 6337: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 6338:                        &log($env{'user.domain'},$env{'user.name'},
 6339:                             $env{'user.home'},
 6340:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 6341:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 6342:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 6343: 		       return '';
 6344:                    }
 6345:                }
 6346:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 6347:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 6348: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 6349:                        &log($env{'user.domain'},$env{'user.name'},
 6350:                             $env{'user.home'},
 6351:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 6352:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 6353:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 6354: 		       return '';
 6355:                    }
 6356:                }
 6357: 	   }
 6358:        }
 6359:     }
 6360:    
 6361: #
 6362: # Rest of the restrictions depend on selected course
 6363: #
 6364: 
 6365:     unless ($env{'request.course.id'}) {
 6366: 	if ($thisallowed eq 'A') {
 6367: 	    return 'A';
 6368:         } elsif ($thisallowed eq 'B') {
 6369:             return 'B';
 6370: 	} else {
 6371: 	    return '1';
 6372: 	}
 6373:     }
 6374: 
 6375: #
 6376: # Now user is definitely in a course
 6377: #
 6378: 
 6379: 
 6380: # Course preferences
 6381: 
 6382:    if ($thisallowed=~/C/) {
 6383:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 6384:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 6385:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 6386: 	   =~/\Q$rolecode\E/) {
 6387: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6388: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 6389: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 6390: 			$env{'request.course.id'});
 6391: 	   }
 6392:            return '';
 6393:        }
 6394: 
 6395:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 6396: 	   =~/\Q$unamedom\E/) {
 6397: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6398: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 6399: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 6400: 			$env{'request.course.id'});
 6401: 	   }
 6402:            return '';
 6403:        }
 6404:    }
 6405: 
 6406: # Resource preferences
 6407: 
 6408:    if ($thisallowed=~/R/) {
 6409:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 6410:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 6411: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6412: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 6413: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 6414: 	   }
 6415: 	   return '';
 6416:        }
 6417:    }
 6418: 
 6419: # Restricted by state or randomout?
 6420: 
 6421:    if ($thisallowed=~/X/) {
 6422:       if ($env{'acc.randomout'}) {
 6423: 	 if (!$symb) { $symb=&symbread($uri,1); }
 6424:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 6425:             return ''; 
 6426:          }
 6427:       }
 6428:       if (&condval($statecond)) {
 6429: 	 return '2';
 6430:       } else {
 6431:          return '';
 6432:       }
 6433:    }
 6434: 
 6435:     if ($thisallowed eq 'A') {
 6436: 	return 'A';
 6437:     } elsif ($thisallowed eq 'B') {
 6438:         return 'B';
 6439:     }
 6440:    return 'F';
 6441: }
 6442: 
 6443: sub get_comm_blocks {
 6444:     my ($cdom,$cnum) = @_;
 6445:     if ($cdom eq '' || $cnum eq '') {
 6446:         return unless ($env{'request.course.id'});
 6447:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6448:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6449:     }
 6450:     my %commblocks;
 6451:     my $hashid=$cdom.'_'.$cnum;
 6452:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 6453:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 6454:         %commblocks = %{$blocksref};
 6455:     } else {
 6456:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 6457:         my $cachetime = 600;
 6458:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 6459:     }
 6460:     return %commblocks;
 6461: }
 6462: 
 6463: sub has_comm_blocking {
 6464:     my ($priv,$symb,$uri,$blocks) = @_;
 6465:     return unless ($env{'request.course.id'});
 6466:     return unless ($priv eq 'bre');
 6467:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 6468:     my %commblocks;
 6469:     if (ref($blocks) eq 'HASH') {
 6470:         %commblocks = %{$blocks};
 6471:     } else {
 6472:         %commblocks = &get_comm_blocks();
 6473:     }
 6474:     return unless (keys(%commblocks) > 0);
 6475:     if (!$symb) { $symb=&symbread($uri,1); }
 6476:     my ($map,$resid,undef)=&decode_symb($symb);
 6477:     my %tocheck = (
 6478:                     maps      => $map,
 6479:                     resources => $symb,
 6480:                   );
 6481:     my @blockers;
 6482:     my $now = time;
 6483:     my $navmap = Apache::lonnavmaps::navmap->new();
 6484:     foreach my $block (keys(%commblocks)) {
 6485:         if ($block =~ /^(\d+)____(\d+)$/) {
 6486:             my ($start,$end) = ($1,$2);
 6487:             if ($start <= $now && $end >= $now) {
 6488:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 6489:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 6490:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 6491:                             if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
 6492:                                 unless (grep(/^\Q$block\E$/,@blockers)) {
 6493:                                     push(@blockers,$block);
 6494:                                 }
 6495:                             }
 6496:                         }
 6497:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 6498:                             if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
 6499:                                 unless (grep(/^\Q$block\E$/,@blockers)) {  
 6500:                                     push(@blockers,$block);
 6501:                                 }
 6502:                             }
 6503:                         }
 6504:                     }
 6505:                 }
 6506:             }
 6507:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 6508:             my $item = $1;
 6509:             my @to_test;
 6510:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 6511:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 6512:                     my $check_interval;
 6513:                     if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
 6514:                         my @interval;
 6515:                         my $type = 'map';
 6516:                         if ($item eq 'course') {
 6517:                             $type = 'course';
 6518:                             @interval=&EXT("resource.0.interval");
 6519:                         } else {
 6520:                             if ($item =~ /___\d+___/) {
 6521:                                 $type = 'resource';
 6522:                                 @interval=&EXT("resource.0.interval",$item);
 6523:                                 if (ref($navmap)) {                        
 6524:                                     my $res = $navmap->getBySymb($item); 
 6525:                                     push(@to_test,$res);
 6526:                                 }
 6527:                             } else {
 6528:                                 my $mapsymb = &symbread($item,1);
 6529:                                 if ($mapsymb) {
 6530:                                     if (ref($navmap)) {
 6531:                                         my $mapres = $navmap->getBySymb($mapsymb);
 6532:                                         @to_test = $mapres->retrieveResources($mapres,undef,0,1);
 6533:                                         foreach my $res (@to_test) {
 6534:                                             my $symb = $res->symb();
 6535:                                             next if ($symb eq $mapsymb);
 6536:                                             if ($symb ne '') {
 6537:                                                 @interval=&EXT("resource.0.interval",$symb);
 6538:                                                 last;
 6539:                                             }
 6540:                                         }
 6541:                                     }
 6542:                                 }
 6543:                             }
 6544:                         }
 6545:                         if ($interval[0] =~ /\d+/) {
 6546:                             my $first_access;
 6547:                             if ($type eq 'resource') {
 6548:                                 $first_access=&get_first_access($interval[1],$item);
 6549:                             } elsif ($type eq 'map') {
 6550:                                 $first_access=&get_first_access($interval[1],undef,$item);
 6551:                             } else {
 6552:                                 $first_access=&get_first_access($interval[1]);
 6553:                             }
 6554:                             if ($first_access) {
 6555:                                 my $timesup = $first_access+$interval[0];
 6556:                                 if ($timesup > $now) {
 6557:                                     foreach my $res (@to_test) {
 6558:                                         if ($res->is_problem()) {
 6559:                                             if ($res->completable()) {
 6560:                                                 unless (grep(/^\Q$block\E$/,@blockers)) {
 6561:                                                     push(@blockers,$block);
 6562:                                                 }
 6563:                                                 last;
 6564:                                             }
 6565:                                         }
 6566:                                     }
 6567:                                 }
 6568:                             }
 6569:                         }
 6570:                     }
 6571:                 }
 6572:             }
 6573:         }
 6574:     }
 6575:     return @blockers;
 6576: }
 6577: 
 6578: sub check_docs_block {
 6579:     my ($docsblock,$tocheck) =@_;
 6580:     if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
 6581:         return;
 6582:     }
 6583:     if (ref($docsblock->{'maps'}) eq 'HASH') {
 6584:         if ($tocheck->{'maps'}) {
 6585:             if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
 6586:                 return 1;
 6587:             }
 6588:         }
 6589:     }
 6590:     if (ref($docsblock->{'resources'}) eq 'HASH') {
 6591:         if ($tocheck->{'resources'}) {
 6592:             if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
 6593:                 return 1;
 6594:             }
 6595:         }
 6596:     }
 6597:     return;
 6598: }
 6599: 
 6600: #
 6601: #   Removes the versino from a URI and
 6602: #   splits it in to its filename and path to the filename.
 6603: #   Seems like File::Basename could have done this more clearly.
 6604: #   Parameters:
 6605: #      $uri   - input URI
 6606: #   Returns:
 6607: #     Two element list consisting of 
 6608: #     $pathname  - the URI up to and excluding the trailing /
 6609: #     $filename  - The part of the URI following the last /
 6610: #  NOTE:
 6611: #    Another realization of this is simply:
 6612: #    use File::Basename;
 6613: #    ...
 6614: #    $uri = shift;
 6615: #    $filename = basename($uri);
 6616: #    $path     = dirname($uri);
 6617: #    return ($filename, $path);
 6618: #
 6619: #     The implementation below is probably faster however.
 6620: #
 6621: sub split_uri_for_cond {
 6622:     my $uri=&deversion(&declutter(shift));
 6623:     my @uriparts=split(/\//,$uri);
 6624:     my $filename=pop(@uriparts);
 6625:     my $pathname=join('/',@uriparts);
 6626:     return ($pathname,$filename);
 6627: }
 6628: # --------------------------------------------------- Is a resource on the map?
 6629: 
 6630: sub is_on_map {
 6631:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 6632:     #Trying to find the conditional for the file
 6633:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 6634: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 6635:     if ($match) {
 6636: 	return (1,$1);
 6637:     } else {
 6638: 	return (0,0);
 6639:     }
 6640: }
 6641: 
 6642: # --------------------------------------------------------- Get symb from alias
 6643: 
 6644: sub get_symb_from_alias {
 6645:     my $symb=shift;
 6646:     my ($map,$resid,$url)=&decode_symb($symb);
 6647: # Already is a symb
 6648:     if ($url) { return $symb; }
 6649: # Must be an alias
 6650:     my $aliassymb='';
 6651:     my %bighash;
 6652:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6653:                             &GDBM_READER(),0640)) {
 6654:         my $rid=$bighash{'mapalias_'.$symb};
 6655: 	if ($rid) {
 6656: 	    my ($mapid,$resid)=split(/\./,$rid);
 6657: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 6658: 				    $resid,$bighash{'src_'.$rid});
 6659: 	}
 6660:         untie %bighash;
 6661:     }
 6662:     return $aliassymb;
 6663: }
 6664: 
 6665: # ----------------------------------------------------------------- Define Role
 6666: 
 6667: sub definerole {
 6668:   if (allowed('mcr','/')) {
 6669:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 6670:     foreach my $role (split(':',$sysrole)) {
 6671: 	my ($crole,$cqual)=split(/\&/,$role);
 6672:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 6673:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 6674: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 6675:                return "refused:s:$crole&$cqual"; 
 6676:             }
 6677:         }
 6678:     }
 6679:     foreach my $role (split(':',$domrole)) {
 6680: 	my ($crole,$cqual)=split(/\&/,$role);
 6681:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 6682:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 6683: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 6684:                return "refused:d:$crole&$cqual"; 
 6685:             }
 6686:         }
 6687:     }
 6688:     foreach my $role (split(':',$courole)) {
 6689: 	my ($crole,$cqual)=split(/\&/,$role);
 6690:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 6691:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 6692: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 6693:                return "refused:c:$crole&$cqual"; 
 6694:             }
 6695:         }
 6696:     }
 6697:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 6698:                 "$env{'user.domain'}:$env{'user.name'}:".
 6699: 	        "rolesdef_$rolename=".
 6700:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 6701:     return reply($command,$env{'user.home'});
 6702:   } else {
 6703:     return 'refused';
 6704:   }
 6705: }
 6706: 
 6707: # ---------------- Make a metadata query against the network of library servers
 6708: 
 6709: sub metadata_query {
 6710:     my ($query,$custom,$customshow,$server_array)=@_;
 6711:     my %rhash;
 6712:     my %libserv = &all_library();
 6713:     my @server_list = (defined($server_array) ? @$server_array
 6714:                                               : keys(%libserv) );
 6715:     for my $server (@server_list) {
 6716: 	unless ($custom or $customshow) {
 6717: 	    my $reply=&reply("querysend:".&escape($query),$server);
 6718: 	    $rhash{$server}=$reply;
 6719: 	}
 6720: 	else {
 6721: 	    my $reply=&reply("querysend:".&escape($query).':'.
 6722: 			     &escape($custom).':'.&escape($customshow),
 6723: 			     $server);
 6724: 	    $rhash{$server}=$reply;
 6725: 	}
 6726:     }
 6727:     return \%rhash;
 6728: }
 6729: 
 6730: # ----------------------------------------- Send log queries and wait for reply
 6731: 
 6732: sub log_query {
 6733:     my ($uname,$udom,$query,%filters)=@_;
 6734:     my $uhome=&homeserver($uname,$udom);
 6735:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 6736:     my $uhost=&hostname($uhome);
 6737:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 6738:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 6739:                        $uhome);
 6740:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 6741:     return get_query_reply($queryid);
 6742: }
 6743: 
 6744: # -------------------------- Update MySQL table for portfolio file
 6745: 
 6746: sub update_portfolio_table {
 6747:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 6748:     if ($group ne '') {
 6749:         $file_name =~s /^\Q$group\E//;
 6750:     }
 6751:     my $homeserver = &homeserver($uname,$udom);
 6752:     my $queryid=
 6753:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 6754:                ':'.&escape($file_name).':'.$action,$homeserver);
 6755:     my $reply = &get_query_reply($queryid);
 6756:     return $reply;
 6757: }
 6758: 
 6759: # -------------------------- Update MySQL allusers table
 6760: 
 6761: sub update_allusers_table {
 6762:     my ($uname,$udom,$names) = @_;
 6763:     my $homeserver = &homeserver($uname,$udom);
 6764:     my $queryid=
 6765:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 6766:                'lastname='.&escape($names->{'lastname'}).'%%'.
 6767:                'firstname='.&escape($names->{'firstname'}).'%%'.
 6768:                'middlename='.&escape($names->{'middlename'}).'%%'.
 6769:                'generation='.&escape($names->{'generation'}).'%%'.
 6770:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 6771:                'id='.&escape($names->{'id'}),$homeserver);
 6772:     return;
 6773: }
 6774: 
 6775: # ------- Request retrieval of institutional classlists for course(s)
 6776: 
 6777: sub fetch_enrollment_query {
 6778:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 6779:     my $homeserver;
 6780:     my $maxtries = 1;
 6781:     if ($context eq 'automated') {
 6782:         $homeserver = $perlvar{'lonHostID'};
 6783:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 6784:     } else {
 6785:         $homeserver = &homeserver($cnum,$dom);
 6786:     }
 6787:     my $host=&hostname($homeserver);
 6788:     my $cmd = '';
 6789:     foreach my $affiliate (keys(%{$affiliatesref})) {
 6790:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 6791:     }
 6792:     $cmd =~ s/%%$//;
 6793:     $cmd = &escape($cmd);
 6794:     my $query = 'fetchenrollment';
 6795:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 6796:     unless ($queryid=~/^\Q$host\E\_/) { 
 6797:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 6798:         return 'error: '.$queryid;
 6799:     }
 6800:     my $reply = &get_query_reply($queryid);
 6801:     my $tries = 1;
 6802:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 6803:         $reply = &get_query_reply($queryid);
 6804:         $tries ++;
 6805:     }
 6806:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 6807:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 6808:     } else {
 6809:         my @responses = split(/:/,$reply);
 6810:         if ($homeserver eq $perlvar{'lonHostID'}) {
 6811:             foreach my $line (@responses) {
 6812:                 my ($key,$value) = split(/=/,$line,2);
 6813:                 $$replyref{$key} = $value;
 6814:             }
 6815:         } else {
 6816:             my $pathname = LONCAPA::tempdir();
 6817:             foreach my $line (@responses) {
 6818:                 my ($key,$value) = split(/=/,$line);
 6819:                 $$replyref{$key} = $value;
 6820:                 if ($value > 0) {
 6821:                     foreach my $item (@{$$affiliatesref{$key}}) {
 6822:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 6823:                         my $destname = $pathname.'/'.$filename;
 6824:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 6825:                         if ($xml_classlist =~ /^error/) {
 6826:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 6827:                         } else {
 6828:                             if ( open(FILE,">$destname") ) {
 6829:                                 print FILE &unescape($xml_classlist);
 6830:                                 close(FILE);
 6831:                             } else {
 6832:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 6833:                             }
 6834:                         }
 6835:                     }
 6836:                 }
 6837:             }
 6838:         }
 6839:         return 'ok';
 6840:     }
 6841:     return 'error';
 6842: }
 6843: 
 6844: sub get_query_reply {
 6845:     my $queryid=shift;
 6846:     my $replyfile=LONCAPA::tempdir().$queryid;
 6847:     my $reply='';
 6848:     for (1..100) {
 6849: 	sleep 2;
 6850:         if (-e $replyfile.'.end') {
 6851: 	    if (open(my $fh,$replyfile)) {
 6852: 		$reply = join('',<$fh>);
 6853: 		close($fh);
 6854: 	   } else { return 'error: reply_file_error'; }
 6855:            return &unescape($reply);
 6856: 	}
 6857:     }
 6858:     return 'timeout:'.$queryid;
 6859: }
 6860: 
 6861: sub courselog_query {
 6862: #
 6863: # possible filters:
 6864: # url: url or symb
 6865: # username
 6866: # domain
 6867: # action: view, submit, grade
 6868: # start: timestamp
 6869: # end: timestamp
 6870: #
 6871:     my (%filters)=@_;
 6872:     unless ($env{'request.course.id'}) { return 'no_course'; }
 6873:     if ($filters{'url'}) {
 6874: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 6875:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 6876:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 6877:     }
 6878:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6879:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6880:     return &log_query($cname,$cdom,'courselog',%filters);
 6881: }
 6882: 
 6883: sub userlog_query {
 6884: #
 6885: # possible filters:
 6886: # action: log check role
 6887: # start: timestamp
 6888: # end: timestamp
 6889: #
 6890:     my ($uname,$udom,%filters)=@_;
 6891:     return &log_query($uname,$udom,'userlog',%filters);
 6892: }
 6893: 
 6894: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 6895: 
 6896: sub auto_run {
 6897:     my ($cnum,$cdom) = @_;
 6898:     my $response = 0;
 6899:     my $settings;
 6900:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 6901:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 6902:         $settings = $domconfig{'autoenroll'};
 6903:         if ($settings->{'run'} eq '1') {
 6904:             $response = 1;
 6905:         }
 6906:     } else {
 6907:         my $homeserver;
 6908:         if (&is_course($cdom,$cnum)) {
 6909:             $homeserver = &homeserver($cnum,$cdom);
 6910:         } else {
 6911:             $homeserver = &domain($cdom,'primary');
 6912:         }
 6913:         if ($homeserver ne 'no_host') {
 6914:             $response = &reply('autorun:'.$cdom,$homeserver);
 6915:         }
 6916:     }
 6917:     return $response;
 6918: }
 6919: 
 6920: sub auto_get_sections {
 6921:     my ($cnum,$cdom,$inst_coursecode) = @_;
 6922:     my $homeserver;
 6923:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 6924:         $homeserver = &homeserver($cnum,$cdom);
 6925:     }
 6926:     if (!defined($homeserver)) { 
 6927:         if ($cdom =~ /^$match_domain$/) {
 6928:             $homeserver = &domain($cdom,'primary');
 6929:         }
 6930:     }
 6931:     my @secs;
 6932:     if (defined($homeserver)) {
 6933:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 6934:         unless ($response eq 'refused') {
 6935:             @secs = split(/:/,$response);
 6936:         }
 6937:     }
 6938:     return @secs;
 6939: }
 6940: 
 6941: sub auto_new_course {
 6942:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 6943:     my $homeserver = &homeserver($cnum,$cdom);
 6944:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 6945:     return $response;
 6946: }
 6947: 
 6948: sub auto_validate_courseID {
 6949:     my ($cnum,$cdom,$inst_course_id) = @_;
 6950:     my $homeserver = &homeserver($cnum,$cdom);
 6951:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 6952:     return $response;
 6953: }
 6954: 
 6955: sub auto_validate_instcode {
 6956:     my ($cnum,$cdom,$instcode,$owner) = @_;
 6957:     my ($homeserver,$response);
 6958:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 6959:         $homeserver = &homeserver($cnum,$cdom);
 6960:     }
 6961:     if (!defined($homeserver)) {
 6962:         if ($cdom =~ /^$match_domain$/) {
 6963:             $homeserver = &domain($cdom,'primary');
 6964:         }
 6965:     }
 6966:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 6967:                         &escape($instcode).':'.&escape($owner),$homeserver));
 6968:     my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
 6969:     return ($outcome,$description);
 6970: }
 6971: 
 6972: sub auto_create_password {
 6973:     my ($cnum,$cdom,$authparam,$udom) = @_;
 6974:     my ($homeserver,$response);
 6975:     my $create_passwd = 0;
 6976:     my $authchk = '';
 6977:     if ($udom =~ /^$match_domain$/) {
 6978:         $homeserver = &domain($udom,'primary');
 6979:     }
 6980:     if ($homeserver eq '') {
 6981:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 6982:             $homeserver = &homeserver($cnum,$cdom);
 6983:         }
 6984:     }
 6985:     if ($homeserver eq '') {
 6986:         $authchk = 'nodomain';
 6987:     } else {
 6988:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 6989:         if ($response eq 'refused') {
 6990:             $authchk = 'refused';
 6991:         } else {
 6992:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 6993:         }
 6994:     }
 6995:     return ($authparam,$create_passwd,$authchk);
 6996: }
 6997: 
 6998: sub auto_photo_permission {
 6999:     my ($cnum,$cdom,$students) = @_;
 7000:     my $homeserver = &homeserver($cnum,$cdom);
 7001:     my ($outcome,$perm_reqd,$conditions) = 
 7002: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 7003:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7004: 	return (undef,undef);
 7005:     }
 7006:     return ($outcome,$perm_reqd,$conditions);
 7007: }
 7008: 
 7009: sub auto_checkphotos {
 7010:     my ($uname,$udom,$pid) = @_;
 7011:     my $homeserver = &homeserver($uname,$udom);
 7012:     my ($result,$resulttype);
 7013:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 7014: 				   &escape($uname).':'.&escape($pid),
 7015: 				   $homeserver));
 7016:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7017: 	return (undef,undef);
 7018:     }
 7019:     if ($outcome) {
 7020:         ($result,$resulttype) = split(/:/,$outcome);
 7021:     } 
 7022:     return ($result,$resulttype);
 7023: }
 7024: 
 7025: sub auto_photochoice {
 7026:     my ($cnum,$cdom) = @_;
 7027:     my $homeserver = &homeserver($cnum,$cdom);
 7028:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 7029: 						       &escape($cdom),
 7030: 						       $homeserver)));
 7031:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7032: 	return (undef,undef);
 7033:     }
 7034:     return ($update,$comment);
 7035: }
 7036: 
 7037: sub auto_photoupdate {
 7038:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 7039:     my $homeserver = &homeserver($cnum,$dom);
 7040:     my $host=&hostname($homeserver);
 7041:     my $cmd = '';
 7042:     my $maxtries = 1;
 7043:     foreach my $affiliate (keys(%{$affiliatesref})) {
 7044:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 7045:     }
 7046:     $cmd =~ s/%%$//;
 7047:     $cmd = &escape($cmd);
 7048:     my $query = 'institutionalphotos';
 7049:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 7050:     unless ($queryid=~/^\Q$host\E\_/) {
 7051:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 7052:         return 'error: '.$queryid;
 7053:     }
 7054:     my $reply = &get_query_reply($queryid);
 7055:     my $tries = 1;
 7056:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 7057:         $reply = &get_query_reply($queryid);
 7058:         $tries ++;
 7059:     }
 7060:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 7061:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 7062:     } else {
 7063:         my @responses = split(/:/,$reply);
 7064:         my $outcome = shift(@responses); 
 7065:         foreach my $item (@responses) {
 7066:             my ($key,$value) = split(/=/,$item);
 7067:             $$photo{$key} = $value;
 7068:         }
 7069:         return $outcome;
 7070:     }
 7071:     return 'error';
 7072: }
 7073: 
 7074: sub auto_instcode_format {
 7075:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 7076: 	$cat_order) = @_;
 7077:     my $courses = '';
 7078:     my @homeservers;
 7079:     if ($caller eq 'global') {
 7080: 	my %servers = &get_servers($codedom,'library');
 7081: 	foreach my $tryserver (keys(%servers)) {
 7082: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7083: 		push(@homeservers,$tryserver);
 7084: 	    }
 7085:         }
 7086:     } elsif ($caller eq 'requests') {
 7087:         if ($codedom =~ /^$match_domain$/) {
 7088:             my $chome = &domain($codedom,'primary');
 7089:             unless ($chome eq 'no_host') {
 7090:                 push(@homeservers,$chome);
 7091:             }
 7092:         }
 7093:     } else {
 7094:         push(@homeservers,&homeserver($caller,$codedom));
 7095:     }
 7096:     foreach my $code (keys(%{$instcodes})) {
 7097:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 7098:     }
 7099:     chop($courses);
 7100:     my $ok_response = 0;
 7101:     my $response;
 7102:     while (@homeservers > 0 && $ok_response == 0) {
 7103:         my $server = shift(@homeservers); 
 7104:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 7105:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 7106:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 7107: 		split(/:/,$response);
 7108:             %{$codes} = (%{$codes},&str2hash($codes_str));
 7109:             push(@{$codetitles},&str2array($codetitles_str));
 7110:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 7111:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 7112:             $ok_response = 1;
 7113:         }
 7114:     }
 7115:     if ($ok_response) {
 7116:         return 'ok';
 7117:     } else {
 7118:         return $response;
 7119:     }
 7120: }
 7121: 
 7122: sub auto_instcode_defaults {
 7123:     my ($domain,$returnhash,$code_order) = @_;
 7124:     my @homeservers;
 7125: 
 7126:     my %servers = &get_servers($domain,'library');
 7127:     foreach my $tryserver (keys(%servers)) {
 7128: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7129: 	    push(@homeservers,$tryserver);
 7130: 	}
 7131:     }
 7132: 
 7133:     my $response;
 7134:     foreach my $server (@homeservers) {
 7135:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 7136:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 7137: 	
 7138: 	foreach my $pair (split(/\&/,$response)) {
 7139: 	    my ($name,$value)=split(/\=/,$pair);
 7140: 	    if ($name eq 'code_order') {
 7141: 		@{$code_order} = split(/\&/,&unescape($value));
 7142: 	    } else {
 7143: 		$returnhash->{&unescape($name)}=&unescape($value);
 7144: 	    }
 7145: 	}
 7146: 	return 'ok';
 7147:     }
 7148: 
 7149:     return $response;
 7150: }
 7151: 
 7152: sub auto_possible_instcodes {
 7153:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 7154:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 7155:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 7156:         return;
 7157:     }
 7158:     my (@homeservers,$uhome);
 7159:     if (defined(&domain($domain,'primary'))) {
 7160:         $uhome=&domain($domain,'primary');
 7161:         push(@homeservers,&domain($domain,'primary'));
 7162:     } else {
 7163:         my %servers = &get_servers($domain,'library');
 7164:         foreach my $tryserver (keys(%servers)) {
 7165:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7166:                 push(@homeservers,$tryserver);
 7167:             }
 7168:         }
 7169:     }
 7170:     my $response;
 7171:     foreach my $server (@homeservers) {
 7172:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 7173:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 7174:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 7175:             split(':',$response);
 7176:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 7177:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 7178:         foreach my $item (split('&',$cat_title)) {   
 7179:             my ($name,$value)=split('=',$item);
 7180:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 7181:         }
 7182:         foreach my $item (split('&',$cat_order)) {
 7183:             my ($name,$value)=split('=',$item);
 7184:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 7185:         }
 7186:         return 'ok';
 7187:     }
 7188:     return $response;
 7189: }
 7190: 
 7191: sub auto_courserequest_checks {
 7192:     my ($dom) = @_;
 7193:     my ($homeserver,%validations);
 7194:     if ($dom =~ /^$match_domain$/) {
 7195:         $homeserver = &domain($dom,'primary');
 7196:     }
 7197:     unless ($homeserver eq 'no_host') {
 7198:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 7199:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 7200:             my @items = split(/&/,$response);
 7201:             foreach my $item (@items) {
 7202:                 my ($key,$value) = split('=',$item);
 7203:                 $validations{&unescape($key)} = &thaw_unescape($value);
 7204:             }
 7205:         }
 7206:     }
 7207:     return %validations; 
 7208: }
 7209: 
 7210: sub auto_courserequest_validation {
 7211:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
 7212:     my ($homeserver,$response);
 7213:     if ($dom =~ /^$match_domain$/) {
 7214:         $homeserver = &domain($dom,'primary');
 7215:     }
 7216:     unless ($homeserver eq 'no_host') {  
 7217:           
 7218:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 7219:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 7220:                                     ':'.&escape($instcode).':'.&escape($instseclist),
 7221:                                     $homeserver));
 7222:     }
 7223:     return $response;
 7224: }
 7225: 
 7226: sub auto_validate_class_sec {
 7227:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 7228:     my $homeserver = &homeserver($cnum,$cdom);
 7229:     my $ownerlist;
 7230:     if (ref($owners) eq 'ARRAY') {
 7231:         $ownerlist = join(',',@{$owners});
 7232:     } else {
 7233:         $ownerlist = $owners;
 7234:     }
 7235:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 7236:                         &escape($ownerlist).':'.$cdom,$homeserver);
 7237:     return $response;
 7238: }
 7239: 
 7240: # ------------------------------------------------------- Course Group routines
 7241: 
 7242: sub get_coursegroups {
 7243:     my ($cdom,$cnum,$group,$namespace) = @_;
 7244:     return(&dump($namespace,$cdom,$cnum,$group));
 7245: }
 7246: 
 7247: sub modify_coursegroup {
 7248:     my ($cdom,$cnum,$groupsettings) = @_;
 7249:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 7250: }
 7251: 
 7252: sub toggle_coursegroup_status {
 7253:     my ($cdom,$cnum,$group,$action) = @_;
 7254:     my ($from_namespace,$to_namespace);
 7255:     if ($action eq 'delete') {
 7256:         $from_namespace = 'coursegroups';
 7257:         $to_namespace = 'deleted_groups';
 7258:     } else {
 7259:         $from_namespace = 'deleted_groups';
 7260:         $to_namespace = 'coursegroups';
 7261:     }
 7262:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 7263:     if (my $tmp = &error(%curr_group)) {
 7264:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 7265:         return ('read error',$tmp);
 7266:     } else {
 7267:         my %savedsettings = %curr_group; 
 7268:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 7269:         my $deloutcome;
 7270:         if ($result eq 'ok') {
 7271:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 7272:         } else {
 7273:             return ('write error',$result);
 7274:         }
 7275:         if ($deloutcome eq 'ok') {
 7276:             return 'ok';
 7277:         } else {
 7278:             return ('delete error',$deloutcome);
 7279:         }
 7280:     }
 7281: }
 7282: 
 7283: sub modify_group_roles {
 7284:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 7285:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 7286:     my $role = 'gr/'.&escape($userprivs);
 7287:     my ($uname,$udom) = split(/:/,$user);
 7288:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 7289:     if ($result eq 'ok') {
 7290:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 7291:     }
 7292:     return $result;
 7293: }
 7294: 
 7295: sub modify_coursegroup_membership {
 7296:     my ($cdom,$cnum,$membership) = @_;
 7297:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 7298:     return $result;
 7299: }
 7300: 
 7301: sub get_active_groups {
 7302:     my ($udom,$uname,$cdom,$cnum) = @_;
 7303:     my $now = time;
 7304:     my %groups = ();
 7305:     foreach my $key (keys(%env)) {
 7306:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 7307:             my ($start,$end) = split(/\./,$env{$key});
 7308:             if (($end!=0) && ($end<$now)) { next; }
 7309:             if (($start!=0) && ($start>$now)) { next; }
 7310:             if ($1 eq $cdom && $2 eq $cnum) {
 7311:                 $groups{$3} = $env{$key} ;
 7312:             }
 7313:         }
 7314:     }
 7315:     return %groups;
 7316: }
 7317: 
 7318: sub get_group_membership {
 7319:     my ($cdom,$cnum,$group) = @_;
 7320:     return(&dump('groupmembership',$cdom,$cnum,$group));
 7321: }
 7322: 
 7323: sub get_users_groups {
 7324:     my ($udom,$uname,$courseid) = @_;
 7325:     my @usersgroups;
 7326:     my $cachetime=1800;
 7327: 
 7328:     my $hashid="$udom:$uname:$courseid";
 7329:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 7330:     if (defined($cached)) {
 7331:         @usersgroups = split(/:/,$grouplist);
 7332:     } else {  
 7333:         $grouplist = '';
 7334:         my $courseurl = &courseid_to_courseurl($courseid);
 7335:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 7336:         my $access_end = $env{'course.'.$courseid.
 7337:                               '.default_enrollment_end_date'};
 7338:         my $now = time;
 7339:         foreach my $key (keys(%roleshash)) {
 7340:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 7341:                 my $group = $1;
 7342:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 7343:                     my $start = $2;
 7344:                     my $end = $1;
 7345:                     if ($start == -1) { next; } # deleted from group
 7346:                     if (($start!=0) && ($start>$now)) { next; }
 7347:                     if (($end!=0) && ($end<$now)) {
 7348:                         if ($access_end && $access_end < $now) {
 7349:                             if ($access_end - $end < 86400) {
 7350:                                 push(@usersgroups,$group);
 7351:                             }
 7352:                         }
 7353:                         next;
 7354:                     }
 7355:                     push(@usersgroups,$group);
 7356:                 }
 7357:             }
 7358:         }
 7359:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 7360:         $grouplist = join(':',@usersgroups);
 7361:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 7362:     }
 7363:     return @usersgroups;
 7364: }
 7365: 
 7366: sub devalidate_getgroups_cache {
 7367:     my ($udom,$uname,$cdom,$cnum)=@_;
 7368:     my $courseid = $cdom.'_'.$cnum;
 7369: 
 7370:     my $hashid="$udom:$uname:$courseid";
 7371:     &devalidate_cache_new('getgroups',$hashid);
 7372: }
 7373: 
 7374: # ------------------------------------------------------------------ Plain Text
 7375: 
 7376: sub plaintext {
 7377:     my ($short,$type,$cid,$forcedefault) = @_;
 7378:     if ($short =~ m{^cr/}) {
 7379: 	return (split('/',$short))[-1];
 7380:     }
 7381:     if (!defined($cid)) {
 7382:         $cid = $env{'request.course.id'};
 7383:     }
 7384:     my %rolenames = (
 7385:                       Course    => 'std',
 7386:                       Community => 'alt1',
 7387:                     );
 7388:     if ($cid ne '') {
 7389:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 7390:             unless ($forcedefault) {
 7391:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 7392:                 &Apache::lonlocal::mt_escape(\$roletext);
 7393:                 return &Apache::lonlocal::mt($roletext);
 7394:             }
 7395:         }
 7396:     }
 7397:     if ((defined($type)) && (defined($rolenames{$type})) &&
 7398:         (defined($rolenames{$type})) && 
 7399:         (defined($prp{$short}{$rolenames{$type}}))) {
 7400:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 7401:     } elsif ($cid ne '') {
 7402:         my $crstype = $env{'course.'.$cid.'.type'};
 7403:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
 7404:             (defined($prp{$short}{$rolenames{$crstype}}))) {
 7405:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
 7406:         }
 7407:     }
 7408:     return &Apache::lonlocal::mt($prp{$short}{'std'});
 7409: }
 7410: 
 7411: # ----------------------------------------------------------------- Assign Role
 7412: 
 7413: sub assignrole {
 7414:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 7415:         $context)=@_;
 7416:     my $mrole;
 7417:     if ($role =~ /^cr\//) {
 7418:         my $cwosec=$url;
 7419:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 7420: 	unless (&allowed('ccr',$cwosec)) {
 7421:            my $refused = 1;
 7422:            if ($context eq 'requestcourses') {
 7423:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 7424:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
 7425:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
 7426:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 7427:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 7428:                            if ($crsenv{'internal.courseowner'} eq
 7429:                                $env{'user.name'}.':'.$env{'user.domain'}) {
 7430:                                $refused = '';
 7431:                            }
 7432:                        }
 7433:                    }
 7434:                }
 7435:            }
 7436:            if ($refused) {
 7437:                &logthis('Refused custom assignrole: '.
 7438:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
 7439:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
 7440:                return 'refused';
 7441:            }
 7442:         }
 7443:         $mrole='cr';
 7444:     } elsif ($role =~ /^gr\//) {
 7445:         my $cwogrp=$url;
 7446:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 7447:         unless (&allowed('mdg',$cwogrp)) {
 7448:             &logthis('Refused group assignrole: '.
 7449:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 7450:                     $env{'user.name'}.' at '.$env{'user.domain'});
 7451:             return 'refused';
 7452:         }
 7453:         $mrole='gr';
 7454:     } else {
 7455:         my $cwosec=$url;
 7456:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 7457:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 7458:             my $refused;
 7459:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 7460:                 if (!(&allowed('c'.$role,$url))) {
 7461:                     $refused = 1;
 7462:                 }
 7463:             } else {
 7464:                 $refused = 1;
 7465:             }
 7466:             if ($refused) {
 7467:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 7468:                 if (!$selfenroll && $context eq 'course') {
 7469:                     my %crsenv;
 7470:                     if ($role eq 'cc' || $role eq 'co') {
 7471:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 7472:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
 7473:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
 7474:                                 if ($crsenv{'internal.courseowner'} eq 
 7475:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 7476:                                     $refused = '';
 7477:                                 }
 7478:                             }
 7479:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
 7480:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
 7481:                                 if ($crsenv{'internal.courseowner'} eq 
 7482:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 7483:                                     $refused = '';
 7484:                                 }
 7485:                             }
 7486:                         }
 7487:                     }
 7488:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7489:                     $refused = '';
 7490:                 } elsif ($context eq 'requestcourses') {
 7491:                     my @possroles = ('st','ta','ep','in','cc','co');
 7492:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
 7493:                         my $wrongcc;
 7494:                         if ($cnum =~ /^$match_community$/) {
 7495:                             $wrongcc = 1 if ($role eq 'cc');
 7496:                         } else {
 7497:                             $wrongcc = 1 if ($role eq 'co');
 7498:                         }
 7499:                         unless ($wrongcc) {
 7500:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 7501:                             if ($crsenv{'internal.courseowner'} eq 
 7502:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
 7503:                                 $refused = '';
 7504:                             }
 7505:                         }
 7506:                     }
 7507:                 }
 7508:                 if ($refused) {
 7509:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 7510:                              ' '.$role.' '.$end.' '.$start.' by '.
 7511: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 7512:                     return 'refused';
 7513:                 }
 7514:             }
 7515:         } elsif ($role eq 'au') {
 7516:             if ($url ne '/'.$udom.'/') {
 7517:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
 7518:                          ' to assign author role for '.$uname.':'.$udom.
 7519:                          ' in domain: '.$url.' refused (wrong domain).');
 7520:                 return 'refused';
 7521:             }
 7522:         }
 7523:         $mrole=$role;
 7524:     }
 7525:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 7526:                 "$udom:$uname:$url".'_'."$mrole=$role";
 7527:     if ($end) { $command.='_'.$end; }
 7528:     if ($start) {
 7529: 	if ($end) { 
 7530:            $command.='_'.$start; 
 7531:         } else {
 7532:            $command.='_0_'.$start;
 7533:         }
 7534:     }
 7535:     my $origstart = $start;
 7536:     my $origend = $end;
 7537:     my $delflag;
 7538: # actually delete
 7539:     if ($deleteflag) {
 7540: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 7541: # modify command to delete the role
 7542:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 7543:                 "$udom:$uname:$url".'_'."$mrole";
 7544: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 7545: # set start and finish to negative values for userrolelog
 7546:            $start=-1;
 7547:            $end=-1;
 7548:            $delflag = 1;
 7549:         }
 7550:     }
 7551: # send command
 7552:     my $answer=&reply($command,&homeserver($uname,$udom));
 7553: # log new user role if status is ok
 7554:     if ($answer eq 'ok') {
 7555: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 7556: # for course roles, perform group memberships changes triggered by role change.
 7557:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
 7558:         unless ($role =~ /^gr/) {
 7559:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 7560:                                              $origstart,$selfenroll,$context);
 7561:         }
 7562:         if ($role eq 'cc') {
 7563:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
 7564:         }
 7565:     }
 7566:     return $answer;
 7567: }
 7568: 
 7569: sub autoupdate_coowners {
 7570:     my ($url,$end,$start,$uname,$udom) = @_;
 7571:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
 7572:     if (($cdom ne '') && ($cnum ne '')) {
 7573:         my $now = time;
 7574:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
 7575:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
 7576:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
 7577:             my $instcode = $coursehash{'internal.coursecode'};
 7578:             if ($instcode ne '') {
 7579:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
 7580:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
 7581:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
 7582:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
 7583:                         if ($result eq 'valid') {
 7584:                             if ($coursehash{'internal.co-owners'}) {
 7585:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 7586:                                     push(@newcoowners,$coowner);
 7587:                                 }
 7588:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
 7589:                                     push(@newcoowners,$uname.':'.$udom);
 7590:                                 }
 7591:                                 @newcoowners = sort(@newcoowners);
 7592:                             } else {
 7593:                                 push(@newcoowners,$uname.':'.$udom);
 7594:                             }
 7595:                         } else {
 7596:                             if ($coursehash{'internal.co-owners'}) {
 7597:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 7598:                                     unless ($coowner eq $uname.':'.$udom) {
 7599:                                         push(@newcoowners,$coowner);
 7600:                                     }
 7601:                                 }
 7602:                                 unless (@newcoowners > 0) {
 7603:                                     $delcoowners = 1;
 7604:                                     $coowners = '';
 7605:                                 }
 7606:                             }
 7607:                         }
 7608:                         if (@newcoowners || $delcoowners) {
 7609:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
 7610:                                             $delcoowners,@newcoowners);
 7611:                         }
 7612:                     }
 7613:                 }
 7614:             }
 7615:         }
 7616:     }
 7617: }
 7618: 
 7619: sub store_coowners {
 7620:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
 7621:     my $cid = $cdom.'_'.$cnum;
 7622:     my ($coowners,$delresult,$putresult);
 7623:     if (@newcoowners) {
 7624:         $coowners = join(',',@newcoowners);
 7625:         my %coownershash = (
 7626:                             'internal.co-owners' => $coowners,
 7627:                            );
 7628:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
 7629:         if ($putresult eq 'ok') {
 7630:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
 7631:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
 7632:             }
 7633:         }
 7634:     }
 7635:     if ($delcoowners) {
 7636:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
 7637:         if ($delresult eq 'ok') {
 7638:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
 7639:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
 7640:             }
 7641:         }
 7642:     }
 7643:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
 7644:         my %crsinfo =
 7645:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 7646:         if (ref($crsinfo{$cid}) eq 'HASH') {
 7647:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
 7648:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
 7649:         }
 7650:     }
 7651: }
 7652: 
 7653: # -------------------------------------------------- Modify user authentication
 7654: # Overrides without validation
 7655: 
 7656: sub modifyuserauth {
 7657:     my ($udom,$uname,$umode,$upass)=@_;
 7658:     my $uhome=&homeserver($uname,$udom);
 7659:     unless (&allowed('mau',$udom)) { return 'refused'; }
 7660:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 7661:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 7662:              ' in domain '.$env{'request.role.domain'});  
 7663:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 7664: 		     &escape($upass),$uhome);
 7665:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 7666:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 7667:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 7668:     &log($udom,,$uname,$uhome,
 7669:         'Authentication changed by '.$env{'user.domain'}.', '.
 7670:                                      $env{'user.name'}.', '.$umode.
 7671:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 7672:     unless ($reply eq 'ok') {
 7673:         &logthis('Authentication mode error: '.$reply);
 7674: 	return 'error: '.$reply;
 7675:     }   
 7676:     return 'ok';
 7677: }
 7678: 
 7679: # --------------------------------------------------------------- Modify a user
 7680: 
 7681: sub modifyuser {
 7682:     my ($udom,    $uname, $uid,
 7683:         $umode,   $upass, $first,
 7684:         $middle,  $last,  $gene,
 7685:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
 7686:     $udom= &LONCAPA::clean_domain($udom);
 7687:     $uname=&LONCAPA::clean_username($uname);
 7688:     my $showcandelete = 'none';
 7689:     if (ref($candelete) eq 'ARRAY') {
 7690:         if (@{$candelete} > 0) {
 7691:             $showcandelete = join(', ',@{$candelete});
 7692:         }
 7693:     }
 7694:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 7695:              $umode.', '.$first.', '.$middle.', '.
 7696: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
 7697:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 7698:                                      ' desiredhome not specified'). 
 7699:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 7700:              ' in domain '.$env{'request.role.domain'});
 7701:     my $uhome=&homeserver($uname,$udom,'true');
 7702:     my $newuser;
 7703:     if ($uhome eq 'no_host') {
 7704:         $newuser = 1;
 7705:     }
 7706: # ----------------------------------------------------------------- Create User
 7707:     if (($uhome eq 'no_host') && 
 7708: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 7709:         my $unhome='';
 7710:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 7711:             $unhome = $desiredhome;
 7712: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 7713: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 7714:         } else { # load balancing routine for determining $unhome
 7715:             my $loadm=10000000;
 7716: 	    my %servers = &get_servers($udom,'library');
 7717: 	    foreach my $tryserver (keys(%servers)) {
 7718: 		my $answer=reply('load',$tryserver);
 7719: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 7720: 		    $loadm=$answer;
 7721: 		    $unhome=$tryserver;
 7722: 		}
 7723: 	    }
 7724:         }
 7725:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 7726: 	    return 'error: unable to find a home server for '.$uname.
 7727:                    ' in domain '.$udom;
 7728:         }
 7729:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 7730:                          &escape($upass),$unhome);
 7731: 	unless ($reply eq 'ok') {
 7732:             return 'error: '.$reply;
 7733:         }   
 7734:         $uhome=&homeserver($uname,$udom,'true');
 7735:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 7736: 	    return 'error: unable verify users home machine.';
 7737:         }
 7738:     }   # End of creation of new user
 7739: # ---------------------------------------------------------------------- Add ID
 7740:     if ($uid) {
 7741:        $uid=~tr/A-Z/a-z/;
 7742:        my %uidhash=&idrget($udom,$uname);
 7743:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 7744:          && (!$forceid)) {
 7745: 	  unless ($uid eq $uidhash{$uname}) {
 7746: 	      return 'error: user id "'.$uid.'" does not match '.
 7747:                   'current user id "'.$uidhash{$uname}.'".';
 7748:           }
 7749:        } else {
 7750: 	  &idput($udom,($uname => $uid));
 7751:        }
 7752:     }
 7753: # -------------------------------------------------------------- Add names, etc
 7754:     my @tmp=&get('environment',
 7755: 		   ['firstname','middlename','lastname','generation','id',
 7756:                     'permanentemail','inststatus'],
 7757: 		   $udom,$uname);
 7758:     my (%names,%oldnames);
 7759:     if ($tmp[0] =~ m/^error:.*/) { 
 7760:         %names=(); 
 7761:     } else {
 7762:         %names = @tmp;
 7763:         %oldnames = %names;
 7764:     }
 7765: #
 7766: # If name, email and/or uid are blank (e.g., because an uploaded file
 7767: # of users did not contain them), do not overwrite existing values
 7768: # unless field is in $candelete array ref.  
 7769: #
 7770: 
 7771:     my @fields = ('firstname','middlename','lastname','generation',
 7772:                   'permanentemail','id');
 7773:     my %newvalues;
 7774:     if (ref($candelete) eq 'ARRAY') {
 7775:         foreach my $field (@fields) {
 7776:             if (grep(/^\Q$field\E$/,@{$candelete})) {
 7777:                 if ($field eq 'firstname') {
 7778:                     $names{$field} = $first;
 7779:                 } elsif ($field eq 'middlename') {
 7780:                     $names{$field} = $middle;
 7781:                 } elsif ($field eq 'lastname') {
 7782:                     $names{$field} = $last;
 7783:                 } elsif ($field eq 'generation') { 
 7784:                     $names{$field} = $gene;
 7785:                 } elsif ($field eq 'permanentemail') {
 7786:                     $names{$field} = $email;
 7787:                 } elsif ($field eq 'id') {
 7788:                     $names{$field}  = $uid;
 7789:                 }
 7790:             }
 7791:         }
 7792:     }
 7793:     if ($first)  { $names{'firstname'}  = $first; }
 7794:     if (defined($middle)) { $names{'middlename'} = $middle; }
 7795:     if ($last)   { $names{'lastname'}   = $last; }
 7796:     if (defined($gene))   { $names{'generation'} = $gene; }
 7797:     if ($email) {
 7798:        $email=~s/[^\w\@\.\-\,]//gs;
 7799:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 7800:     }
 7801:     if ($uid) { $names{'id'}  = $uid; }
 7802:     if (defined($inststatus)) {
 7803:         $names{'inststatus'} = '';
 7804:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
 7805:         if (ref($usertypes) eq 'HASH') {
 7806:             my @okstatuses; 
 7807:             foreach my $item (split(/:/,$inststatus)) {
 7808:                 if (defined($usertypes->{$item})) {
 7809:                     push(@okstatuses,$item);  
 7810:                 }
 7811:             }
 7812:             if (@okstatuses) {
 7813:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
 7814:             }
 7815:         }
 7816:     }
 7817:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
 7818:                  $umode.', '.$first.', '.$middle.', '.
 7819:                  $last.', '.$gene.', '.$email.', '.$inststatus;
 7820:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 7821:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 7822:     } else {
 7823:         $logmsg .= ' during self creation';
 7824:     }
 7825:     my $changed;
 7826:     if ($newuser) {
 7827:         $changed = 1;
 7828:     } else {
 7829:         foreach my $field (@fields) {
 7830:             if ($names{$field} ne $oldnames{$field}) {
 7831:                 $changed = 1;
 7832:                 last;
 7833:             }
 7834:         }
 7835:     }
 7836:     unless ($changed) {
 7837:         $logmsg = 'No changes in user information needed for: '.$logmsg;
 7838:         &logthis($logmsg);
 7839:         return 'ok';
 7840:     }
 7841:     my $reply = &put('environment', \%names, $udom,$uname);
 7842:     if ($reply ne 'ok') { 
 7843:         return 'error: '.$reply;
 7844:     }
 7845:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
 7846:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
 7847:     }
 7848:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 7849:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 7850:     $logmsg = 'Success modifying user '.$logmsg;
 7851:     &logthis($logmsg);
 7852:     return 'ok';
 7853: }
 7854: 
 7855: # -------------------------------------------------------------- Modify student
 7856: 
 7857: sub modifystudent {
 7858:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 7859:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 7860:         $selfenroll,$context,$inststatus)=@_;
 7861:     if (!$cid) {
 7862: 	unless ($cid=$env{'request.course.id'}) {
 7863: 	    return 'not_in_class';
 7864: 	}
 7865:     }
 7866: # --------------------------------------------------------------- Make the user
 7867:     my $reply=&modifyuser
 7868: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 7869:          $desiredhome,$email,$inststatus);
 7870:     unless ($reply eq 'ok') { return $reply; }
 7871:     # This will cause &modify_student_enrollment to get the uid from the
 7872:     # students environment
 7873:     $uid = undef if (!$forceid);
 7874:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 7875: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
 7876:     return $reply;
 7877: }
 7878: 
 7879: sub modify_student_enrollment {
 7880:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
 7881:     my ($cdom,$cnum,$chome);
 7882:     if (!$cid) {
 7883: 	unless ($cid=$env{'request.course.id'}) {
 7884: 	    return 'not_in_class';
 7885: 	}
 7886: 	$cdom=$env{'course.'.$cid.'.domain'};
 7887: 	$cnum=$env{'course.'.$cid.'.num'};
 7888:     } else {
 7889: 	($cdom,$cnum)=split(/_/,$cid);
 7890:     }
 7891:     $chome=$env{'course.'.$cid.'.home'};
 7892:     if (!$chome) {
 7893: 	$chome=&homeserver($cnum,$cdom);
 7894:     }
 7895:     if (!$chome) { return 'unknown_course'; }
 7896:     # Make sure the user exists
 7897:     my $uhome=&homeserver($uname,$udom);
 7898:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 7899: 	return 'error: no such user';
 7900:     }
 7901:     # Get student data if we were not given enough information
 7902:     if (!defined($first)  || $first  eq '' || 
 7903:         !defined($last)   || $last   eq '' || 
 7904:         !defined($uid)    || $uid    eq '' || 
 7905:         !defined($middle) || $middle eq '' || 
 7906:         !defined($gene)   || $gene   eq '') {
 7907:         # They did not supply us with enough data to enroll the student, so
 7908:         # we need to pick up more information.
 7909:         my %tmp = &get('environment',
 7910:                        ['firstname','middlename','lastname', 'generation','id']
 7911:                        ,$udom,$uname);
 7912: 
 7913:         #foreach my $key (keys(%tmp)) {
 7914:         #    &logthis("key $key = ".$tmp{$key});
 7915:         #}
 7916:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 7917:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 7918:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 7919:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 7920:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 7921:     }
 7922:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 7923:     my $user = "$uname:$udom";
 7924:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
 7925:     my $reply=cput('classlist',
 7926: 		   {$user => 
 7927: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
 7928: 		   $cdom,$cnum);
 7929:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
 7930:         &devalidate_getsection_cache($udom,$uname,$cid);
 7931:     } else { 
 7932: 	return 'error: '.$reply;
 7933:     }
 7934:     # Add student role to user
 7935:     my $uurl='/'.$cid;
 7936:     $uurl=~s/\_/\//g;
 7937:     if ($usec) {
 7938: 	$uurl.='/'.$usec;
 7939:     }
 7940:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
 7941:                              $selfenroll,$context);
 7942:     if ($result ne 'ok') {
 7943:         if ($old_entry{$user} ne '') {
 7944:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
 7945:         } else {
 7946:             $reply = &del('classlist',[$user],$cdom,$cnum);
 7947:         }
 7948:     }
 7949:     return $result; 
 7950: }
 7951: 
 7952: sub format_name {
 7953:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 7954:     my $name;
 7955:     if ($first ne 'lastname') {
 7956: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 7957:     } else {
 7958: 	if ($lastname=~/\S/) {
 7959: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 7960: 	    $name=~s/\s+,/,/;
 7961: 	} else {
 7962: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 7963: 	}
 7964:     }
 7965:     $name=~s/^\s+//;
 7966:     $name=~s/\s+$//;
 7967:     $name=~s/\s+/ /g;
 7968:     return $name;
 7969: }
 7970: 
 7971: # ------------------------------------------------- Write to course preferences
 7972: 
 7973: sub writecoursepref {
 7974:     my ($courseid,%prefs)=@_;
 7975:     $courseid=~s/^\///;
 7976:     $courseid=~s/\_/\//g;
 7977:     my ($cdomain,$cnum)=split(/\//,$courseid);
 7978:     my $chome=homeserver($cnum,$cdomain);
 7979:     if (($chome eq '') || ($chome eq 'no_host')) { 
 7980: 	return 'error: no such course';
 7981:     }
 7982:     my $cstring='';
 7983:     foreach my $pref (keys(%prefs)) {
 7984: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 7985:     }
 7986:     $cstring=~s/\&$//;
 7987:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 7988: }
 7989: 
 7990: # ---------------------------------------------------------- Make/modify course
 7991: 
 7992: sub createcourse {
 7993:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 7994:         $course_owner,$crstype,$cnum,$context,$category)=@_;
 7995:     $url=&declutter($url);
 7996:     my $cid='';
 7997:     if ($context eq 'requestcourses') {
 7998:         my $can_create = 0;
 7999:         my ($ownername,$ownerdom) = split(':',$course_owner);
 8000:         if ($udom eq $ownerdom) {
 8001:             if (&usertools_access($ownername,$ownerdom,$category,undef,
 8002:                                   $context)) {
 8003:                 $can_create = 1;
 8004:             }
 8005:         } else {
 8006:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
 8007:                                            $category);
 8008:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
 8009:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
 8010:                 if (@curr > 0) {
 8011:                     my @options = qw(approval validate autolimit);
 8012:                     my $optregex = join('|',@options);
 8013:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
 8014:                         $can_create = 1;
 8015:                     }
 8016:                 }
 8017:             }
 8018:         }
 8019:         if ($can_create) {
 8020:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
 8021:                 unless (&allowed('ccc',$udom)) {
 8022:                     return 'refused'; 
 8023:                 }
 8024:             }
 8025:         } else {
 8026:             return 'refused';
 8027:         }
 8028:     } elsif (!&allowed('ccc',$udom)) {
 8029:         return 'refused';
 8030:     }
 8031: # --------------------------------------------------------------- Get Unique ID
 8032:     my $uname;
 8033:     if ($cnum =~ /^$match_courseid$/) {
 8034:         my $chome=&homeserver($cnum,$udom,'true');
 8035:         if (($chome eq '') || ($chome eq 'no_host')) {
 8036:             $uname = $cnum;
 8037:         } else {
 8038:             $uname = &generate_coursenum($udom,$crstype);
 8039:         }
 8040:     } else {
 8041:         $uname = &generate_coursenum($udom,$crstype);
 8042:     }
 8043:     return $uname if ($uname =~ /^error/);
 8044: # -------------------------------------------------- Check supplied server name
 8045:     if (!defined($course_server)) {
 8046:         if (defined(&domain($udom,'primary'))) {
 8047:             $course_server = &domain($udom,'primary');
 8048:         } else {
 8049:             $course_server = $env{'user.home'}; 
 8050:         }
 8051:     }
 8052:     my %host_servers =
 8053:         &Apache::lonnet::get_servers($udom,'library');
 8054:     unless ($host_servers{$course_server}) {
 8055:         return 'error: invalid home server for course: '.$course_server;
 8056:     }
 8057: # ------------------------------------------------------------- Make the course
 8058:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 8059:                       $course_server);
 8060:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 8061:     my $uhome=&homeserver($uname,$udom,'true');
 8062:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 8063: 	return 'error: no such course';
 8064:     }
 8065: # ----------------------------------------------------------------- Course made
 8066: # log existence
 8067:     my $now = time;
 8068:     my $newcourse = {
 8069:                     $udom.'_'.$uname => {
 8070:                                      description => $description,
 8071:                                      inst_code   => $inst_code,
 8072:                                      owner       => $course_owner,
 8073:                                      type        => $crstype,
 8074:                                      creator     => $env{'user.name'}.':'.
 8075:                                                     $env{'user.domain'},
 8076:                                      created     => $now,
 8077:                                      context     => $context,
 8078:                                                 },
 8079:                     };
 8080:     &courseidput($udom,$newcourse,$uhome,'notime');
 8081: # set toplevel url
 8082:     my $topurl=$url;
 8083:     unless ($nonstandard) {
 8084: # ------------------------------------------ For standard courses, make top url
 8085:         my $mapurl=&clutter($url);
 8086:         if ($mapurl eq '/res/') { $mapurl=''; }
 8087:         $env{'form.initmap'}=(<<ENDINITMAP);
 8088: <map>
 8089: <resource id="1" type="start"></resource>
 8090: <resource id="2" src="$mapurl"></resource>
 8091: <resource id="3" type="finish"></resource>
 8092: <link index="1" from="1" to="2"></link>
 8093: <link index="2" from="2" to="3"></link>
 8094: </map>
 8095: ENDINITMAP
 8096:         $topurl=&declutter(
 8097:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 8098:                           );
 8099:     }
 8100: # ----------------------------------------------------------- Write preferences
 8101:     &writecoursepref($udom.'_'.$uname,
 8102:                      ('description'              => $description,
 8103:                       'url'                      => $topurl,
 8104:                       'internal.creator'         => $env{'user.name'}.':'.
 8105:                                                     $env{'user.domain'},
 8106:                       'internal.created'         => $now,
 8107:                       'internal.creationcontext' => $context)
 8108:                     );
 8109:     return '/'.$udom.'/'.$uname;
 8110: }
 8111: 
 8112: # ------------------------------------------------------------------- Create ID
 8113: sub generate_coursenum {
 8114:     my ($udom,$crstype) = @_;
 8115:     my $domdesc = &domain($udom);
 8116:     return 'error: invalid domain' if ($domdesc eq '');
 8117:     my $first;
 8118:     if ($crstype eq 'Community') {
 8119:         $first = '0';
 8120:     } else {
 8121:         $first = int(1+rand(9)); 
 8122:     } 
 8123:     my $uname=$first.
 8124:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 8125:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
 8126:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 8127: # ----------------------------------------------- Make sure that does not exist
 8128:     my $uhome=&homeserver($uname,$udom,'true');
 8129:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
 8130:         if ($crstype eq 'Community') {
 8131:             $first = '0';
 8132:         } else {
 8133:             $first = int(1+rand(9));
 8134:         }
 8135:         $uname=$first.
 8136:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 8137:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
 8138:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 8139:         $uhome=&homeserver($uname,$udom,'true');
 8140:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
 8141:             return 'error: unable to generate unique course-ID';
 8142:         }
 8143:     }
 8144:     return $uname;
 8145: }
 8146: 
 8147: sub is_course {
 8148:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
 8149:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
 8150: 
 8151:     return unless $cdom and $cnum;
 8152: 
 8153:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
 8154:         '.');
 8155: 
 8156:     return unless exists($courses{$cdom.'_'.$cnum});
 8157:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
 8158: }
 8159: 
 8160: sub store_userdata {
 8161:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
 8162:     my $result;
 8163:     if ($datakey ne '') {
 8164:         if (ref($storehash) eq 'HASH') {
 8165:             if ($udom eq '' || $uname eq '') {
 8166:                 $udom = $env{'user.domain'};
 8167:                 $uname = $env{'user.name'};
 8168:             }
 8169:             my $uhome=&homeserver($uname,$udom);
 8170:             if (($uhome eq '') || ($uhome eq 'no_host')) {
 8171:                 $result = 'error: no_host';
 8172:             } else {
 8173:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
 8174:                 $storehash->{'host'} = $perlvar{'lonHostID'};
 8175: 
 8176:                 my $namevalue='';
 8177:                 foreach my $key (keys(%{$storehash})) {
 8178:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 8179:                 }
 8180:                 $namevalue=~s/\&$//;
 8181:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
 8182:                                   $namevalue,$uhome);
 8183:             }
 8184:         } else {
 8185:             $result = 'error: data to store was not a hash reference'; 
 8186:         }
 8187:     } else {
 8188:         $result= 'error: invalid requestkey'; 
 8189:     }
 8190:     return $result;
 8191: }
 8192: 
 8193: # ---------------------------------------------------------- Assign Custom Role
 8194: 
 8195: sub assigncustomrole {
 8196:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
 8197:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 8198:                        $end,$start,$deleteflag,$selfenroll,$context);
 8199: }
 8200: 
 8201: # ----------------------------------------------------------------- Revoke Role
 8202: 
 8203: sub revokerole {
 8204:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
 8205:     my $now=time;
 8206:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
 8207: }
 8208: 
 8209: # ---------------------------------------------------------- Revoke Custom Role
 8210: 
 8211: sub revokecustomrole {
 8212:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
 8213:     my $now=time;
 8214:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 8215:            $deleteflag,$selfenroll,$context);
 8216: }
 8217: 
 8218: # ------------------------------------------------------------ Disk usage
 8219: sub diskusage {
 8220:     my ($udom,$uname,$directorypath,$getpropath)=@_;
 8221:     $directorypath =~ s/\/$//;
 8222:     my $listing=&reply('du2:'.&escape($directorypath).':'
 8223:                        .&escape($getpropath).':'.&escape($uname).':'
 8224:                        .&escape($udom),homeserver($uname,$udom));
 8225:     if ($listing eq 'unknown_cmd') {
 8226:         if ($getpropath) {
 8227:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
 8228:         }
 8229:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
 8230:     }
 8231:     return $listing;
 8232: }
 8233: 
 8234: sub is_locked {
 8235:     my ($file_name, $domain, $user, $which) = @_;
 8236:     my @check;
 8237:     my $is_locked;
 8238:     push (@check,$file_name);
 8239:     my %locked = &get('file_permissions',\@check,
 8240: 		      $env{'user.domain'},$env{'user.name'});
 8241:     my ($tmp)=keys(%locked);
 8242:     if ($tmp=~/^error:/) { undef(%locked); }
 8243:     
 8244:     if (ref($locked{$file_name}) eq 'ARRAY') {
 8245:         $is_locked = 'false';
 8246:         foreach my $entry (@{$locked{$file_name}}) {
 8247:            if (ref($entry) eq 'ARRAY') {
 8248:                $is_locked = 'true';
 8249:                if (ref($which) eq 'ARRAY') {
 8250:                    push(@{$which},$entry);
 8251:                } else {
 8252:                    last;
 8253:                }
 8254:            }
 8255:        }
 8256:     } else {
 8257:         $is_locked = 'false';
 8258:     }
 8259:     return $is_locked;
 8260: }
 8261: 
 8262: sub declutter_portfile {
 8263:     my ($file) = @_;
 8264:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 8265:     return $file;
 8266: }
 8267: 
 8268: # ------------------------------------------------------------- Mark as Read Only
 8269: 
 8270: sub mark_as_readonly {
 8271:     my ($domain,$user,$files,$what) = @_;
 8272:     my %current_permissions = &dump('file_permissions',$domain,$user);
 8273:     my ($tmp)=keys(%current_permissions);
 8274:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 8275:     foreach my $file (@{$files}) {
 8276: 	$file = &declutter_portfile($file);
 8277:         push(@{$current_permissions{$file}},$what);
 8278:     }
 8279:     &put('file_permissions',\%current_permissions,$domain,$user);
 8280:     return;
 8281: }
 8282: 
 8283: # ------------------------------------------------------------Save Selected Files
 8284: 
 8285: sub save_selected_files {
 8286:     my ($user, $path, @files) = @_;
 8287:     my $filename = $user."savedfiles";
 8288:     my @other_files = &files_not_in_path($user, $path);
 8289:     open (OUT, '>'.$tmpdir.$filename);
 8290:     foreach my $file (@files) {
 8291:         print (OUT $env{'form.currentpath'}.$file."\n");
 8292:     }
 8293:     foreach my $file (@other_files) {
 8294:         print (OUT $file."\n");
 8295:     }
 8296:     close (OUT);
 8297:     return 'ok';
 8298: }
 8299: 
 8300: sub clear_selected_files {
 8301:     my ($user) = @_;
 8302:     my $filename = $user."savedfiles";
 8303:     open (OUT, '>'.LONCAPA::tempdir().$filename);
 8304:     print (OUT undef);
 8305:     close (OUT);
 8306:     return ("ok");    
 8307: }
 8308: 
 8309: sub files_in_path {
 8310:     my ($user, $path) = @_;
 8311:     my $filename = $user."savedfiles";
 8312:     my %return_files;
 8313:     open (IN, '<'.LONCAPA::tempdir().$filename);
 8314:     while (my $line_in = <IN>) {
 8315:         chomp ($line_in);
 8316:         my @paths_and_file = split (m!/!, $line_in);
 8317:         my $file_part = pop (@paths_and_file);
 8318:         my $path_part = join ('/', @paths_and_file);
 8319:         $path_part.='/';
 8320:         my $path_and_file = $path_part.$file_part;
 8321:         if ($path_part eq $path) {
 8322:             $return_files{$file_part}= 'selected';
 8323:         }
 8324:     }
 8325:     close (IN);
 8326:     return (\%return_files);
 8327: }
 8328: 
 8329: # called in portfolio select mode, to show files selected NOT in current directory
 8330: sub files_not_in_path {
 8331:     my ($user, $path) = @_;
 8332:     my $filename = $user."savedfiles";
 8333:     my @return_files;
 8334:     my $path_part;
 8335:     open(IN, '<'.LONCAPA::.$filename);
 8336:     while (my $line = <IN>) {
 8337:         #ok, I know it's clunky, but I want it to work
 8338:         my @paths_and_file = split(m|/|, $line);
 8339:         my $file_part = pop(@paths_and_file);
 8340:         chomp($file_part);
 8341:         my $path_part = join('/', @paths_and_file);
 8342:         $path_part .= '/';
 8343:         my $path_and_file = $path_part.$file_part;
 8344:         if ($path_part ne $path) {
 8345:             push(@return_files, ($path_and_file));
 8346:         }
 8347:     }
 8348:     close(OUT);
 8349:     return (@return_files);
 8350: }
 8351: 
 8352: #----------------------------------------------Get portfolio file permissions
 8353: 
 8354: sub get_portfile_permissions {
 8355:     my ($domain,$user) = @_;
 8356:     my %current_permissions = &dump('file_permissions',$domain,$user);
 8357:     my ($tmp)=keys(%current_permissions);
 8358:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 8359:     return \%current_permissions;
 8360: }
 8361: 
 8362: #---------------------------------------------Get portfolio file access controls
 8363: 
 8364: sub get_access_controls {
 8365:     my ($current_permissions,$group,$file) = @_;
 8366:     my %access;
 8367:     my $real_file = $file;
 8368:     $file =~ s/\.meta$//;
 8369:     if (defined($file)) {
 8370:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 8371:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 8372:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 8373:             }
 8374:         }
 8375:     } else {
 8376:         foreach my $key (keys(%{$current_permissions})) {
 8377:             if ($key =~ /\0accesscontrol$/) {
 8378:                 if (defined($group)) {
 8379:                     if ($key !~ m-^\Q$group\E/-) {
 8380:                         next;
 8381:                     }
 8382:                 }
 8383:                 my ($fullpath) = split(/\0/,$key);
 8384:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 8385:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 8386:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 8387:                     }
 8388:                 }
 8389:             }
 8390:         }
 8391:     }
 8392:     return %access;
 8393: }
 8394: 
 8395: sub modify_access_controls {
 8396:     my ($file_name,$changes,$domain,$user)=@_;
 8397:     my ($outcome,$deloutcome);
 8398:     my %store_permissions;
 8399:     my %new_values;
 8400:     my %new_control;
 8401:     my %translation;
 8402:     my @deletions = ();
 8403:     my $now = time;
 8404:     if (exists($$changes{'activate'})) {
 8405:         if (ref($$changes{'activate'}) eq 'HASH') {
 8406:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 8407:             my $numnew = scalar(@newitems);
 8408:             for (my $i=0; $i<$numnew; $i++) {
 8409:                 my $newkey = $newitems[$i];
 8410:                 my $newid = &Apache::loncommon::get_cgi_id();
 8411:                 if ($newkey =~ /^\d+:/) { 
 8412:                     $newkey =~ s/^(\d+)/$newid/;
 8413:                     $translation{$1} = $newid;
 8414:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 8415:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 8416:                     $translation{$1} = $newid;
 8417:                 }
 8418:                 $new_values{$file_name."\0".$newkey} = 
 8419:                                           $$changes{'activate'}{$newitems[$i]};
 8420:                 $new_control{$newkey} = $now;
 8421:             }
 8422:         }
 8423:     }
 8424:     my %todelete;
 8425:     my %changed_items;
 8426:     foreach my $action ('delete','update') {
 8427:         if (exists($$changes{$action})) {
 8428:             if (ref($$changes{$action}) eq 'HASH') {
 8429:                 foreach my $key (keys(%{$$changes{$action}})) {
 8430:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 8431:                     if ($action eq 'delete') { 
 8432:                         $todelete{$itemnum} = 1;
 8433:                     } else {
 8434:                         $changed_items{$itemnum} = $key;
 8435:                     }
 8436:                 }
 8437:             }
 8438:         }
 8439:     }
 8440:     # get lock on access controls for file.
 8441:     my $lockhash = {
 8442:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 8443:                                                        ':'.$env{'user.domain'},
 8444:                    }; 
 8445:     my $tries = 0;
 8446:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 8447:    
 8448:     while (($gotlock ne 'ok') && $tries <3) {
 8449:         $tries ++;
 8450:         sleep 1;
 8451:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 8452:     }
 8453:     if ($gotlock eq 'ok') {
 8454:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 8455:         my ($tmp)=keys(%curr_permissions);
 8456:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 8457:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 8458:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 8459:             if (ref($curr_controls) eq 'HASH') {
 8460:                 foreach my $control_item (keys(%{$curr_controls})) {
 8461:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 8462:                     if (defined($todelete{$itemnum})) {
 8463:                         push(@deletions,$file_name."\0".$control_item);
 8464:                     } else {
 8465:                         if (defined($changed_items{$itemnum})) {
 8466:                             $new_control{$changed_items{$itemnum}} = $now;
 8467:                             push(@deletions,$file_name."\0".$control_item);
 8468:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 8469:                         } else {
 8470:                             $new_control{$control_item} = $$curr_controls{$control_item};
 8471:                         }
 8472:                     }
 8473:                 }
 8474:             }
 8475:         }
 8476:         my ($group);
 8477:         if (&is_course($domain,$user)) {
 8478:             ($group,my $file) = split(/\//,$file_name,2);
 8479:         }
 8480:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 8481:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 8482:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 8483:         #  remove lock
 8484:         my @del_lock = ($file_name."\0".'locked_access_records');
 8485:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 8486:         my $sqlresult =
 8487:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
 8488:                                     $group);
 8489:     } else {
 8490:         $outcome = "error: could not obtain lockfile\n";  
 8491:     }
 8492:     return ($outcome,$deloutcome,\%new_values,\%translation);
 8493: }
 8494: 
 8495: sub make_public_indefinitely {
 8496:     my ($requrl) = @_;
 8497:     my $now = time;
 8498:     my $action = 'activate';
 8499:     my $aclnum = 0;
 8500:     if (&is_portfolio_url($requrl)) {
 8501:         my (undef,$udom,$unum,$file_name,$group) =
 8502:             &parse_portfolio_url($requrl);
 8503:         my $current_perms = &get_portfile_permissions($udom,$unum);
 8504:         my %access_controls = &get_access_controls($current_perms,
 8505:                                                    $group,$file_name);
 8506:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 8507:             my ($num,$scope,$end,$start) = 
 8508:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 8509:             if ($scope eq 'public') {
 8510:                 if ($start <= $now && $end == 0) {
 8511:                     $action = 'none';
 8512:                 } else {
 8513:                     $action = 'update';
 8514:                     $aclnum = $num;
 8515:                 }
 8516:                 last;
 8517:             }
 8518:         }
 8519:         if ($action eq 'none') {
 8520:              return 'ok';
 8521:         } else {
 8522:             my %changes;
 8523:             my $newend = 0;
 8524:             my $newstart = $now;
 8525:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 8526:             $changes{$action}{$newkey} = {
 8527:                 type => 'public',
 8528:                 time => {
 8529:                     start => $newstart,
 8530:                     end   => $newend,
 8531:                 },
 8532:             };
 8533:             my ($outcome,$deloutcome,$new_values,$translation) =
 8534:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 8535:             return $outcome;
 8536:         }
 8537:     } else {
 8538:         return 'invalid';
 8539:     }
 8540: }
 8541: 
 8542: #------------------------------------------------------Get Marked as Read Only
 8543: 
 8544: sub get_marked_as_readonly {
 8545:     my ($domain,$user,$what,$group) = @_;
 8546:     my $current_permissions = &get_portfile_permissions($domain,$user);
 8547:     my @readonly_files;
 8548:     my $cmp1=$what;
 8549:     if (ref($what)) { $cmp1=join('',@{$what}) };
 8550:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 8551:         if (defined($group)) {
 8552:             if ($file_name !~ m-^\Q$group\E/-) {
 8553:                 next;
 8554:             }
 8555:         }
 8556:         if (ref($value) eq "ARRAY"){
 8557:             foreach my $stored_what (@{$value}) {
 8558:                 my $cmp2=$stored_what;
 8559:                 if (ref($stored_what) eq 'ARRAY') {
 8560:                     $cmp2=join('',@{$stored_what});
 8561:                 }
 8562:                 if ($cmp1 eq $cmp2) {
 8563:                     push(@readonly_files, $file_name);
 8564:                     last;
 8565:                 } elsif (!defined($what)) {
 8566:                     push(@readonly_files, $file_name);
 8567:                     last;
 8568:                 }
 8569:             }
 8570:         }
 8571:     }
 8572:     return @readonly_files;
 8573: }
 8574: #-----------------------------------------------------------Get Marked as Read Only Hash
 8575: 
 8576: sub get_marked_as_readonly_hash {
 8577:     my ($current_permissions,$group,$what) = @_;
 8578:     my %readonly_files;
 8579:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 8580:         if (defined($group)) {
 8581:             if ($file_name !~ m-^\Q$group\E/-) {
 8582:                 next;
 8583:             }
 8584:         }
 8585:         if (ref($value) eq "ARRAY"){
 8586:             foreach my $stored_what (@{$value}) {
 8587:                 if (ref($stored_what) eq 'ARRAY') {
 8588:                     foreach my $lock_descriptor(@{$stored_what}) {
 8589:                         if ($lock_descriptor eq 'graded') {
 8590:                             $readonly_files{$file_name} = 'graded';
 8591:                         } elsif ($lock_descriptor eq 'handback') {
 8592:                             $readonly_files{$file_name} = 'handback';
 8593:                         } else {
 8594:                             if (!exists($readonly_files{$file_name})) {
 8595:                                 $readonly_files{$file_name} = 'locked';
 8596:                             }
 8597:                         }
 8598:                     }
 8599:                 } 
 8600:             }
 8601:         } 
 8602:     }
 8603:     return %readonly_files;
 8604: }
 8605: # ------------------------------------------------------------ Unmark as Read Only
 8606: 
 8607: sub unmark_as_readonly {
 8608:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 8609:     # for portfolio submissions, $what contains [$symb,$crsid] 
 8610:     my ($domain,$user,$what,$file_name,$group) = @_;
 8611:     $file_name = &declutter_portfile($file_name);
 8612:     my $symb_crs = $what;
 8613:     if (ref($what)) { $symb_crs=join('',@$what); }
 8614:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 8615:     my ($tmp)=keys(%current_permissions);
 8616:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 8617:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 8618:     foreach my $file (@readonly_files) {
 8619: 	my $clean_file = &declutter_portfile($file);
 8620: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 8621: 	my $current_locks = $current_permissions{$file};
 8622:         my @new_locks;
 8623:         my @del_keys;
 8624:         if (ref($current_locks) eq "ARRAY"){
 8625:             foreach my $locker (@{$current_locks}) {
 8626:                 my $compare=$locker;
 8627:                 if (ref($locker) eq 'ARRAY') {
 8628:                     $compare=join('',@{$locker});
 8629:                     if ($compare ne $symb_crs) {
 8630:                         push(@new_locks, $locker);
 8631:                     }
 8632:                 }
 8633:             }
 8634:             if (scalar(@new_locks) > 0) {
 8635:                 $current_permissions{$file} = \@new_locks;
 8636:             } else {
 8637:                 push(@del_keys, $file);
 8638:                 &del('file_permissions',\@del_keys, $domain, $user);
 8639:                 delete($current_permissions{$file});
 8640:             }
 8641:         }
 8642:     }
 8643:     &put('file_permissions',\%current_permissions,$domain,$user);
 8644:     return;
 8645: }
 8646: 
 8647: # ------------------------------------------------------------ Directory lister
 8648: 
 8649: sub dirlist {
 8650:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
 8651:     $uri=~s/^\///;
 8652:     $uri=~s/\/$//;
 8653:     my ($udom, $uname);
 8654:     if ($getuserdir) {
 8655:         $udom = $userdomain;
 8656:         $uname = $username;
 8657:     } else {
 8658:         (undef,$udom,$uname)=split(/\//,$uri);
 8659:         if(defined($userdomain)) {
 8660:             $udom = $userdomain;
 8661:         }
 8662:         if(defined($username)) {
 8663:             $uname = $username;
 8664:         }
 8665:     }
 8666:     my ($dirRoot,$listing,@listing_results);
 8667: 
 8668:     $dirRoot = $perlvar{'lonDocRoot'};
 8669:     if (defined($getpropath)) {
 8670:         $dirRoot = &propath($udom,$uname);
 8671:         $dirRoot =~ s/\/$//;
 8672:     } elsif (defined($getuserdir)) {
 8673:         my $subdir=$uname.'__';
 8674:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 8675:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
 8676:                    ."/$udom/$subdir/$uname";
 8677:     } elsif (defined($alternateRoot)) {
 8678:         $dirRoot = $alternateRoot;
 8679:     }
 8680: 
 8681:     if($udom) {
 8682:         if($uname) {
 8683:             my $uhome = &homeserver($uname,$udom);
 8684:             if ($uhome eq 'no_host') {
 8685:                 return ([],'no_host');
 8686:             }
 8687:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
 8688:                               .$getuserdir.':'.&escape($dirRoot)
 8689:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
 8690:             if ($listing eq 'unknown_cmd') {
 8691:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
 8692:             } else {
 8693:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 8694:             }
 8695:             if ($listing eq 'unknown_cmd') {
 8696:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
 8697:                 @listing_results = split(/:/,$listing);
 8698:             } else {
 8699:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 8700:             }
 8701:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
 8702:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
 8703:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 8704:                 return ([],$listing);
 8705:             } else {
 8706:                 return (\@listing_results);
 8707:             }
 8708:         } elsif(!$alternateRoot) {
 8709:             my (%allusers,%listerror);
 8710: 	    my %servers = &get_servers($udom,'library');
 8711:  	    foreach my $tryserver (keys(%servers)) {
 8712:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
 8713:                                   &escape($udom),$tryserver);
 8714:                 if ($listing eq 'unknown_cmd') {
 8715: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 8716: 				      $udom, $tryserver);
 8717:                 } else {
 8718:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
 8719:                 }
 8720: 		if ($listing eq 'unknown_cmd') {
 8721: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 8722: 				      $udom, $tryserver);
 8723: 		    @listing_results = split(/:/,$listing);
 8724: 		} else {
 8725: 		    @listing_results =
 8726: 			map { &unescape($_); } split(/:/,$listing);
 8727: 		}
 8728:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
 8729:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
 8730:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 8731:                     $listerror{$tryserver} = $listing;
 8732:                 } else {
 8733: 		    foreach my $line (@listing_results) {
 8734: 			my ($entry) = split(/&/,$line,2);
 8735: 			$allusers{$entry} = 1;
 8736: 		    }
 8737: 		}
 8738:             }
 8739:             my @alluserslist=();
 8740:             foreach my $user (sort(keys(%allusers))) {
 8741:                 push(@alluserslist,$user.'&user');
 8742:             }
 8743:             return (\@alluserslist);
 8744:         } else {
 8745:             return ([],'missing username');
 8746:         }
 8747:     } elsif(!defined($getpropath)) {
 8748:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
 8749:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
 8750:         return (\@all_domains);
 8751:     } else {
 8752:         return ([],'missing domain');
 8753:     }
 8754: }
 8755: 
 8756: # --------------------------------------------- GetFileTimestamp
 8757: # This function utilizes dirlist and returns the date stamp for
 8758: # when it was last modified.  It will also return an error of -1
 8759: # if an error occurs
 8760: 
 8761: sub GetFileTimestamp {
 8762:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
 8763:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 8764:     $studentName   = &LONCAPA::clean_username($studentName);
 8765:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
 8766:                                     undef,$getuserdir);
 8767:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 8768:         return -1;
 8769:     }
 8770:     if (ref($fileref) eq 'ARRAY') {
 8771:         my @stats = split('&',$fileref->[0]);
 8772:         # @stats contains first the filename, then the stat output
 8773:         return $stats[10]; # so this is 10 instead of 9.
 8774:     } else {
 8775:         return -1;
 8776:     }
 8777: }
 8778: 
 8779: sub stat_file {
 8780:     my ($uri) = @_;
 8781:     $uri = &clutter_with_no_wrapper($uri);
 8782: 
 8783:     my ($udom,$uname,$file);
 8784:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 8785: 	($udom,$uname,$file) =
 8786: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 8787: 	$file = 'userfiles/'.$file;
 8788:     }
 8789:     if ($uri =~ m-^/res/-) {
 8790: 	($udom,$uname) = 
 8791: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 8792: 	$file = $uri;
 8793:     }
 8794: 
 8795:     if (!$udom || !$uname || !$file) {
 8796: 	# unable to handle the uri
 8797: 	return ();
 8798:     }
 8799:     my $getpropath;
 8800:     if ($file =~ /^userfiles\//) {
 8801:         $getpropath = 1;
 8802:     }
 8803:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
 8804:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 8805:         return ();
 8806:     } else {
 8807:         if (ref($listref) eq 'ARRAY') {
 8808:             my @stats = split('&',$listref->[0]);
 8809: 	    shift(@stats); #filename is first
 8810: 	    return @stats;
 8811:         }
 8812:     }
 8813:     return ();
 8814: }
 8815: 
 8816: # -------------------------------------------------------- Value of a Condition
 8817: 
 8818: # gets the value of a specific preevaluated condition
 8819: #    stored in the string  $env{user.state.<cid>}
 8820: # or looks up a condition reference in the bighash and if if hasn't
 8821: # already been evaluated recurses into docondval to get the value of
 8822: # the condition, then memoizing it to 
 8823: #   $env{user.state.<cid>.<condition>}
 8824: sub directcondval {
 8825:     my $number=shift;
 8826:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 8827: 	&Apache::lonuserstate::evalstate();
 8828:     }
 8829:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 8830: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 8831:     } elsif ($number =~ /^_/) {
 8832: 	my $sub_condition;
 8833: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8834: 		&GDBM_READER(),0640)) {
 8835: 	    $sub_condition=$bighash{'conditions'.$number};
 8836: 	    untie(%bighash);
 8837: 	}
 8838: 	my $value = &docondval($sub_condition);
 8839: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
 8840: 	return $value;
 8841:     }
 8842:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 8843:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 8844:     } else {
 8845:        return 2;
 8846:     }
 8847: }
 8848: 
 8849: # get the collection of conditions for this resource
 8850: sub condval {
 8851:     my $condidx=shift;
 8852:     my $allpathcond='';
 8853:     foreach my $cond (split(/\|/,$condidx)) {
 8854: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 8855: 	    $allpathcond.=
 8856: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 8857: 	}
 8858:     }
 8859:     $allpathcond=~s/\|$//;
 8860:     return &docondval($allpathcond);
 8861: }
 8862: 
 8863: #evaluates an expression of conditions
 8864: sub docondval {
 8865:     my ($allpathcond) = @_;
 8866:     my $result=0;
 8867:     if ($env{'request.course.id'}
 8868: 	&& defined($allpathcond)) {
 8869: 	my $operand='|';
 8870: 	my @stack;
 8871: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 8872: 	    if ($chunk eq '(') {
 8873: 		push @stack,($operand,$result);
 8874: 	    } elsif ($chunk eq ')') {
 8875: 		my $before=pop @stack;
 8876: 		if (pop @stack eq '&') {
 8877: 		    $result=$result>$before?$before:$result;
 8878: 		} else {
 8879: 		    $result=$result>$before?$result:$before;
 8880: 		}
 8881: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 8882: 		$operand=$chunk;
 8883: 	    } else {
 8884: 		my $new=directcondval($chunk);
 8885: 		if ($operand eq '&') {
 8886: 		    $result=$result>$new?$new:$result;
 8887: 		} else {
 8888: 		    $result=$result>$new?$result:$new;
 8889: 		}
 8890: 	    }
 8891: 	}
 8892:     }
 8893:     return $result;
 8894: }
 8895: 
 8896: # ---------------------------------------------------- Devalidate courseresdata
 8897: 
 8898: sub devalidatecourseresdata {
 8899:     my ($coursenum,$coursedomain)=@_;
 8900:     my $hashid=$coursenum.':'.$coursedomain;
 8901:     &devalidate_cache_new('courseres',$hashid);
 8902: }
 8903: 
 8904: 
 8905: # --------------------------------------------------- Course Resourcedata Query
 8906: #
 8907: #  Parameters:
 8908: #      $coursenum    - Number of the course.
 8909: #      $coursedomain - Domain at which the course was created.
 8910: #  Returns:
 8911: #     A hash of the course parameters along (I think) with timestamps
 8912: #     and version info.
 8913: 
 8914: sub get_courseresdata {
 8915:     my ($coursenum,$coursedomain)=@_;
 8916:     my $coursehom=&homeserver($coursenum,$coursedomain);
 8917:     my $hashid=$coursenum.':'.$coursedomain;
 8918:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 8919:     my %dumpreply;
 8920:     unless (defined($cached)) {
 8921: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 8922: 	$result=\%dumpreply;
 8923: 	my ($tmp) = keys(%dumpreply);
 8924: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 8925: 	    &do_cache_new('courseres',$hashid,$result,600);
 8926: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 8927: 	    return $tmp;
 8928: 	} elsif ($tmp =~ /^(error)/) {
 8929: 	    $result=undef;
 8930: 	    &do_cache_new('courseres',$hashid,$result,600);
 8931: 	}
 8932:     }
 8933:     return $result;
 8934: }
 8935: 
 8936: sub devalidateuserresdata {
 8937:     my ($uname,$udom)=@_;
 8938:     my $hashid="$udom:$uname";
 8939:     &devalidate_cache_new('userres',$hashid);
 8940: }
 8941: 
 8942: sub get_userresdata {
 8943:     my ($uname,$udom)=@_;
 8944:     #most student don\'t have any data set, check if there is some data
 8945:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 8946: 
 8947:     my $hashid="$udom:$uname";
 8948:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 8949:     if (!defined($cached)) {
 8950: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 8951: 	$result=\%resourcedata;
 8952: 	&do_cache_new('userres',$hashid,$result,600);
 8953:     }
 8954:     my ($tmp)=keys(%$result);
 8955:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 8956: 	return $result;
 8957:     }
 8958:     #error 2 occurs when the .db doesn't exist
 8959:     if ($tmp!~/error: 2 /) {
 8960: 	&logthis("<font color=\"blue\">WARNING:".
 8961: 		 " Trying to get resource data for ".
 8962: 		 $uname." at ".$udom.": ".
 8963: 		 $tmp."</font>");
 8964:     } elsif ($tmp=~/error: 2 /) {
 8965: 	#&EXT_cache_set($udom,$uname);
 8966: 	&do_cache_new('userres',$hashid,undef,600);
 8967: 	undef($tmp); # not really an error so don't send it back
 8968:     }
 8969:     return $tmp;
 8970: }
 8971: #----------------------------------------------- resdata - return resource data
 8972: #  Purpose:
 8973: #    Return resource data for either users or for a course.
 8974: #  Parameters:
 8975: #     $name      - Course/user name.
 8976: #     $domain    - Name of the domain the user/course is registered on.
 8977: #     $type      - Type of thing $name is (must be 'course' or 'user'
 8978: #     @which     - Array of names of resources desired.
 8979: #  Returns:
 8980: #     The value of the first reasource in @which that is found in the
 8981: #     resource hash.
 8982: #  Exceptional Conditions:
 8983: #     If the $type passed in is not valid (not the string 'course' or 
 8984: #     'user', an undefined  reference is returned.
 8985: #     If none of the resources are found, an undef is returned
 8986: sub resdata {
 8987:     my ($name,$domain,$type,@which)=@_;
 8988:     my $result;
 8989:     if ($type eq 'course') {
 8990: 	$result=&get_courseresdata($name,$domain);
 8991:     } elsif ($type eq 'user') {
 8992: 	$result=&get_userresdata($name,$domain);
 8993:     }
 8994:     if (!ref($result)) { return $result; }    
 8995:     foreach my $item (@which) {
 8996: 	if (defined($result->{$item->[0]})) {
 8997: 	    return [$result->{$item->[0]},$item->[1]];
 8998: 	}
 8999:     }
 9000:     return undef;
 9001: }
 9002: 
 9003: #
 9004: # EXT resource caching routines
 9005: #
 9006: 
 9007: sub clear_EXT_cache_status {
 9008:     &delenv('cache.EXT.');
 9009: }
 9010: 
 9011: sub EXT_cache_status {
 9012:     my ($target_domain,$target_user) = @_;
 9013:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 9014:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 9015:         # We know already the user has no data
 9016:         return 1;
 9017:     } else {
 9018:         return 0;
 9019:     }
 9020: }
 9021: 
 9022: sub EXT_cache_set {
 9023:     my ($target_domain,$target_user) = @_;
 9024:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 9025:     #&appenv({$cachename => time});
 9026: }
 9027: 
 9028: # --------------------------------------------------------- Value of a Variable
 9029: sub EXT {
 9030: 
 9031:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
 9032:     unless ($varname) { return ''; }
 9033:     #get real user name/domain, courseid and symb
 9034:     my $courseid;
 9035:     my $publicuser;
 9036:     if ($symbparm) {
 9037: 	$symbparm=&get_symb_from_alias($symbparm);
 9038:     }
 9039:     if (!($uname && $udom)) {
 9040:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 9041:       if (!$symbparm) {	$symbparm=$cursymb; }
 9042:     } else {
 9043: 	$courseid=$env{'request.course.id'};
 9044:     }
 9045:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 9046:     my $rest;
 9047:     if (defined($therest[0])) {
 9048:        $rest=join('.',@therest);
 9049:     } else {
 9050:        $rest='';
 9051:     }
 9052: 
 9053:     my $qualifierrest=$qualifier;
 9054:     if ($rest) { $qualifierrest.='.'.$rest; }
 9055:     my $spacequalifierrest=$space;
 9056:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 9057:     if ($realm eq 'user') {
 9058: # --------------------------------------------------------------- user.resource
 9059: 	if ($space eq 'resource') {
 9060: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 9061: 		  || defined($Apache::lonhomework::parsing_a_task))
 9062: 		 &&
 9063: 		 ($symbparm eq &symbread()) ) {	
 9064: 		# if we are in the middle of processing the resource the
 9065: 		# get the value we are planning on committing
 9066:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 9067:                     return $Apache::lonhomework::results{$qualifierrest};
 9068:                 } else {
 9069:                     return $Apache::lonhomework::history{$qualifierrest};
 9070:                 }
 9071: 	    } else {
 9072: 		my %restored;
 9073: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 9074: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 9075: 		} else {
 9076: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 9077: 		}
 9078: 		return $restored{$qualifierrest};
 9079: 	    }
 9080: # ----------------------------------------------------------------- user.access
 9081:         } elsif ($space eq 'access') {
 9082: 	    # FIXME - not supporting calls for a specific user
 9083:             return &allowed($qualifier,$rest);
 9084: # ------------------------------------------ user.preferences, user.environment
 9085:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 9086: 	    if (($uname eq $env{'user.name'}) &&
 9087: 		($udom eq $env{'user.domain'})) {
 9088: 		return $env{join('.',('environment',$qualifierrest))};
 9089: 	    } else {
 9090: 		my %returnhash;
 9091: 		if (!$publicuser) {
 9092: 		    %returnhash=&userenvironment($udom,$uname,
 9093: 						 $qualifierrest);
 9094: 		}
 9095: 		return $returnhash{$qualifierrest};
 9096: 	    }
 9097: # ----------------------------------------------------------------- user.course
 9098:         } elsif ($space eq 'course') {
 9099: 	    # FIXME - not supporting calls for a specific user
 9100:             return $env{join('.',('request.course',$qualifier))};
 9101: # ------------------------------------------------------------------- user.role
 9102:         } elsif ($space eq 'role') {
 9103: 	    # FIXME - not supporting calls for a specific user
 9104:             my ($role,$where)=split(/\./,$env{'request.role'});
 9105:             if ($qualifier eq 'value') {
 9106: 		return $role;
 9107:             } elsif ($qualifier eq 'extent') {
 9108:                 return $where;
 9109:             }
 9110: # ----------------------------------------------------------------- user.domain
 9111:         } elsif ($space eq 'domain') {
 9112:             return $udom;
 9113: # ------------------------------------------------------------------- user.name
 9114:         } elsif ($space eq 'name') {
 9115:             return $uname;
 9116: # ---------------------------------------------------- Any other user namespace
 9117:         } else {
 9118: 	    my %reply;
 9119: 	    if (!$publicuser) {
 9120: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 9121: 	    }
 9122: 	    return $reply{$qualifierrest};
 9123:         }
 9124:     } elsif ($realm eq 'query') {
 9125: # ---------------------------------------------- pull stuff out of query string
 9126:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 9127: 						[$spacequalifierrest]);
 9128: 	return $env{'form.'.$spacequalifierrest}; 
 9129:    } elsif ($realm eq 'request') {
 9130: # ------------------------------------------------------------- request.browser
 9131:         if ($space eq 'browser') {
 9132:             return $env{'browser.'.$qualifier};
 9133: # ------------------------------------------------------------ request.filename
 9134:         } else {
 9135:             return $env{'request.'.$spacequalifierrest};
 9136:         }
 9137:     } elsif ($realm eq 'course') {
 9138: # ---------------------------------------------------------- course.description
 9139:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 9140:     } elsif ($realm eq 'resource') {
 9141: 
 9142: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 9143: 	    if (!$symbparm) { $symbparm=&symbread(); }
 9144: 	}
 9145: 
 9146: 	if ($space eq 'title') {
 9147: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 9148: 	    return &gettitle($symbparm);
 9149: 	}
 9150: 	
 9151: 	if ($space eq 'map') {
 9152: 	    my ($map) = &decode_symb($symbparm);
 9153: 	    return &symbread($map);
 9154: 	}
 9155: 	if ($space eq 'filename') {
 9156: 	    if ($symbparm) {
 9157: 		return &clutter((&decode_symb($symbparm))[2]);
 9158: 	    }
 9159: 	    return &hreflocation('',$env{'request.filename'});
 9160: 	}
 9161: 
 9162: 	my ($section, $group, @groups);
 9163: 	my ($courselevelm,$courselevel);
 9164: 	if ($symbparm && defined($courseid) && 
 9165: 	    $courseid eq $env{'request.course.id'}) {
 9166: 
 9167: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 9168: 
 9169: # ----------------------------------------------------- Cascading lookup scheme
 9170: 	    my $symbp=$symbparm;
 9171: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 9172: 
 9173: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 9174: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 9175: 
 9176: 	    if (($env{'user.name'} eq $uname) &&
 9177: 		($env{'user.domain'} eq $udom)) {
 9178: 		$section=$env{'request.course.sec'};
 9179:                 @groups = split(/:/,$env{'request.course.groups'});  
 9180:                 @groups=&sort_course_groups($courseid,@groups); 
 9181: 	    } else {
 9182: 		if (! defined($usection)) {
 9183: 		    $section=&getsection($udom,$uname,$courseid);
 9184: 		} else {
 9185: 		    $section = $usection;
 9186: 		}
 9187:                 @groups = &get_users_groups($udom,$uname,$courseid);
 9188: 	    }
 9189: 
 9190: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 9191: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 9192: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 9193: 
 9194: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 9195: 	    my $courselevelr=$courseid.'.'.$symbparm;
 9196: 	    $courselevelm=$courseid.'.'.$mapparm;
 9197: 
 9198: # ----------------------------------------------------------- first, check user
 9199: 
 9200: 	    my $userreply=&resdata($uname,$udom,'user',
 9201: 				       ([$courselevelr,'resource'],
 9202: 					[$courselevelm,'map'     ],
 9203: 					[$courselevel, 'course'  ]));
 9204: 	    if (defined($userreply)) { return &get_reply($userreply); }
 9205: 
 9206: # ------------------------------------------------ second, check some of course
 9207:             my $coursereply;
 9208:             if (@groups > 0) {
 9209:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 9210:                                        $mapparm,$spacequalifierrest);
 9211:                 if (defined($coursereply)) { return &get_reply($coursereply); }
 9212:             }
 9213: 
 9214: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 9215: 				  $env{'course.'.$courseid.'.domain'},
 9216: 				  'course',
 9217: 				  ([$seclevelr,   'resource'],
 9218: 				   [$seclevelm,   'map'     ],
 9219: 				   [$seclevel,    'course'  ],
 9220: 				   [$courselevelr,'resource']));
 9221: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 9222: 
 9223: # ------------------------------------------------------ third, check map parms
 9224: 	    my %parmhash=();
 9225: 	    my $thisparm='';
 9226: 	    if (tie(%parmhash,'GDBM_File',
 9227: 		    $env{'request.course.fn'}.'_parms.db',
 9228: 		    &GDBM_READER(),0640)) {
 9229: 		$thisparm=$parmhash{$symbparm};
 9230: 		untie(%parmhash);
 9231: 	    }
 9232: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
 9233: 	}
 9234: # ------------------------------------------ fourth, look in resource metadata
 9235: 
 9236: 	$spacequalifierrest=~s/\./\_/;
 9237: 	my $filename;
 9238: 	if (!$symbparm) { $symbparm=&symbread(); }
 9239: 	if ($symbparm) {
 9240: 	    $filename=(&decode_symb($symbparm))[2];
 9241: 	} else {
 9242: 	    $filename=$env{'request.filename'};
 9243: 	}
 9244: 	my $metadata=&metadata($filename,$spacequalifierrest);
 9245: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 9246: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 9247: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 9248: 
 9249: # ---------------------------------------------- fourth, look in rest of course
 9250: 	if ($symbparm && defined($courseid) && 
 9251: 	    $courseid eq $env{'request.course.id'}) {
 9252: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 9253: 				     $env{'course.'.$courseid.'.domain'},
 9254: 				     'course',
 9255: 				     ([$courselevelm,'map'   ],
 9256: 				      [$courselevel, 'course']));
 9257: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 9258: 	}
 9259: # ------------------------------------------------------------------ Cascade up
 9260: 	unless ($space eq '0') {
 9261: 	    my @parts=split(/_/,$space);
 9262: 	    my $id=pop(@parts);
 9263: 	    my $part=join('_',@parts);
 9264: 	    if ($part eq '') { $part='0'; }
 9265: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 9266: 				 $symbparm,$udom,$uname,$section,1);
 9267: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
 9268: 	}
 9269: 	if ($recurse) { return undef; }
 9270: 	my $pack_def=&packages_tab_default($filename,$varname);
 9271: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
 9272: # ---------------------------------------------------- Any other user namespace
 9273:     } elsif ($realm eq 'environment') {
 9274: # ----------------------------------------------------------------- environment
 9275: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 9276: 	    return $env{'environment.'.$spacequalifierrest};
 9277: 	} else {
 9278: 	    if ($uname eq 'anonymous' && $udom eq '') {
 9279: 		return '';
 9280: 	    }
 9281: 	    my %returnhash=&userenvironment($udom,$uname,
 9282: 					    $spacequalifierrest);
 9283: 	    return $returnhash{$spacequalifierrest};
 9284: 	}
 9285:     } elsif ($realm eq 'system') {
 9286: # ----------------------------------------------------------------- system.time
 9287: 	if ($space eq 'time') {
 9288: 	    return time;
 9289:         }
 9290:     } elsif ($realm eq 'server') {
 9291: # ----------------------------------------------------------------- system.time
 9292: 	if ($space eq 'name') {
 9293: 	    return $ENV{'SERVER_NAME'};
 9294:         }
 9295:     }
 9296:     return '';
 9297: }
 9298: 
 9299: sub get_reply {
 9300:     my ($reply_value) = @_;
 9301:     if (ref($reply_value) eq 'ARRAY') {
 9302:         if (wantarray) {
 9303: 	    return @$reply_value;
 9304:         }
 9305:         return $reply_value->[0];
 9306:     } else {
 9307:         return $reply_value;
 9308:     }
 9309: }
 9310: 
 9311: sub check_group_parms {
 9312:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
 9313:     my @groupitems = ();
 9314:     my $resultitem;
 9315:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
 9316:     foreach my $group (@{$groups}) {
 9317:         foreach my $level (@levels) {
 9318:              my $item = $courseid.'.['.$group.'].'.$level->[0];
 9319:              push(@groupitems,[$item,$level->[1]]);
 9320:         }
 9321:     }
 9322:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
 9323:                             $env{'course.'.$courseid.'.domain'},
 9324:                                      'course',@groupitems);
 9325:     return $coursereply;
 9326: }
 9327: 
 9328: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
 9329:     my ($courseid,@groups) = @_;
 9330:     @groups = sort(@groups);
 9331:     return @groups;
 9332: }
 9333: 
 9334: sub packages_tab_default {
 9335:     my ($uri,$varname)=@_;
 9336:     my (undef,$part,$name)=split(/\./,$varname);
 9337: 
 9338:     my (@extension,@specifics,$do_default);
 9339:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
 9340: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 9341: 	if ($pack_type eq 'default') {
 9342: 	    $do_default=1;
 9343: 	} elsif ($pack_type eq 'extension') {
 9344: 	    push(@extension,[$package,$pack_type,$pack_part]);
 9345: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
 9346: 	    # only look at packages defaults for packages that this id is
 9347: 	    push(@specifics,[$package,$pack_type,$pack_part]);
 9348: 	}
 9349:     }
 9350:     # first look for a package that matches the requested part id
 9351:     foreach my $package (@specifics) {
 9352: 	my (undef,$pack_type,$pack_part)=@{$package};
 9353: 	next if ($pack_part ne $part);
 9354: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 9355: 	    return $packagetab{"$pack_type&$name&default"};
 9356: 	}
 9357:     }
 9358:     # look for any possible matching non extension_ package
 9359:     foreach my $package (@specifics) {
 9360: 	my (undef,$pack_type,$pack_part)=@{$package};
 9361: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 9362: 	    return $packagetab{"$pack_type&$name&default"};
 9363: 	}
 9364: 	if ($pack_type eq 'part') { $pack_part='0'; }
 9365: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
 9366: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
 9367: 	}
 9368:     }
 9369:     # look for any posible extension_ match
 9370:     foreach my $package (@extension) {
 9371: 	my ($package,$pack_type)=@{$package};
 9372: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 9373: 	    return $packagetab{"$pack_type&$name&default"};
 9374: 	}
 9375: 	if (defined($packagetab{$package."&$name&default"})) {
 9376: 	    return $packagetab{$package."&$name&default"};
 9377: 	}
 9378:     }
 9379:     # look for a global default setting
 9380:     if ($do_default && defined($packagetab{"default&$name&default"})) {
 9381: 	return $packagetab{"default&$name&default"};
 9382:     }
 9383:     return undef;
 9384: }
 9385: 
 9386: sub add_prefix_and_part {
 9387:     my ($prefix,$part)=@_;
 9388:     my $keyroot;
 9389:     if (defined($prefix) && $prefix !~ /^__/) {
 9390: 	# prefix that has a part already
 9391: 	$keyroot=$prefix;
 9392:     } elsif (defined($prefix)) {
 9393: 	# prefix that is missing a part
 9394: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 9395:     } else {
 9396: 	# no prefix at all
 9397: 	if (defined($part)) { $keyroot='_'.$part; }
 9398:     }
 9399:     return $keyroot;
 9400: }
 9401: 
 9402: # ---------------------------------------------------------------- Get metadata
 9403: 
 9404: my %metaentry;
 9405: my %importedpartids;
 9406: sub metadata {
 9407:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 9408:     $uri=&declutter($uri);
 9409:     # if it is a non metadata possible uri return quickly
 9410:     if (($uri eq '') || 
 9411: 	(($uri =~ m|^/*adm/|) && 
 9412: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
 9413:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
 9414: 	return undef;
 9415:     }
 9416:     if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) 
 9417: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
 9418: 	return undef;
 9419:     }
 9420:     my $filename=$uri;
 9421:     $uri=~s/\.meta$//;
 9422: #
 9423: # Is the metadata already cached?
 9424: # Look at timestamp of caching
 9425: # Everything is cached by the main uri, libraries are never directly cached
 9426: #
 9427:     if (!defined($liburi)) {
 9428: 	my ($result,$cached)=&is_cached_new('meta',$uri);
 9429: 	if (defined($cached)) { return $result->{':'.$what}; }
 9430:     }
 9431:     {
 9432: # Imported parts would go here
 9433:         my %importedids=();
 9434:         my @origfileimportpartids=();
 9435:         my $importedparts=0;
 9436: #
 9437: # Is this a recursive call for a library?
 9438: #
 9439: #	if (! exists($metacache{$uri})) {
 9440: #	    $metacache{$uri}={};
 9441: #	}
 9442: 	my $cachetime = 60*60;
 9443:         if ($liburi) {
 9444: 	    $liburi=&declutter($liburi);
 9445:             $filename=$liburi;
 9446:         } else {
 9447: 	    &devalidate_cache_new('meta',$uri);
 9448: 	    undef(%metaentry);
 9449: 	}
 9450:         my %metathesekeys=();
 9451:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 9452: 	my $metastring;
 9453: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
 9454: 	    my $which = &hreflocation('','/'.($liburi || $uri));
 9455: 	    $metastring = 
 9456: 		&Apache::lonnet::ssi_body($which,
 9457: 					  ('grade_target' => 'meta'));
 9458: 	    $cachetime = 1; # only want this cached in the child not long term
 9459: 	} elsif (($uri !~ m -^(editupload)/-) && 
 9460:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
 9461: 	    my $file=&filelocation('',&clutter($filename));
 9462: 	    #push(@{$metaentry{$uri.'.file'}},$file);
 9463: 	    $metastring=&getfile($file);
 9464: 	}
 9465:         my $parser=HTML::LCParser->new(\$metastring);
 9466:         my $token;
 9467:         undef %metathesekeys;
 9468:         while ($token=$parser->get_token) {
 9469: 	    if ($token->[0] eq 'S') {
 9470: 		if (defined($token->[2]->{'package'})) {
 9471: #
 9472: # This is a package - get package info
 9473: #
 9474: 		    my $package=$token->[2]->{'package'};
 9475: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 9476: 		    if (defined($token->[2]->{'id'})) { 
 9477: 			$keyroot.='_'.$token->[2]->{'id'}; 
 9478: 		    }
 9479: 		    if ($metaentry{':packages'}) {
 9480: 			$metaentry{':packages'}.=','.$package.$keyroot;
 9481: 		    } else {
 9482: 			$metaentry{':packages'}=$package.$keyroot;
 9483: 		    }
 9484: 		    foreach my $pack_entry (keys(%packagetab)) {
 9485: 			my $part=$keyroot;
 9486: 			$part=~s/^\_//;
 9487: 			if ($pack_entry=~/^\Q$package\E\&/ || 
 9488: 			    $pack_entry=~/^\Q$package\E_0\&/) {
 9489: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
 9490: 			    # ignore package.tab specified default values
 9491:                             # here &package_tab_default() will fetch those
 9492: 			    if ($subp eq 'default') { next; }
 9493: 			    my $value=$packagetab{$pack_entry};
 9494: 			    my $unikey;
 9495: 			    if ($pack =~ /_0$/) {
 9496: 				$unikey='parameter_0_'.$name;
 9497: 				$part=0;
 9498: 			    } else {
 9499: 				$unikey='parameter'.$keyroot.'_'.$name;
 9500: 			    }
 9501: 			    if ($subp eq 'display') {
 9502: 				$value.=' [Part: '.$part.']';
 9503: 			    }
 9504: 			    $metaentry{':'.$unikey.'.part'}=$part;
 9505: 			    $metathesekeys{$unikey}=1;
 9506: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 9507: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
 9508: 			    }
 9509: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
 9510: 				$metaentry{':'.$unikey}=
 9511: 				    $metaentry{':'.$unikey.'.default'};
 9512: 			    }
 9513: 			}
 9514: 		    }
 9515: 		} else {
 9516: #
 9517: # This is not a package - some other kind of start tag
 9518: #
 9519: 		    my $entry=$token->[1];
 9520: 		    my $unikey='';
 9521: 
 9522: 		    if ($entry eq 'import') {
 9523: #
 9524: # Importing a library here
 9525: #
 9526:                         my $location=$parser->get_text('/import');
 9527:                         my $dir=$filename;
 9528:                         $dir=~s|[^/]*$||;
 9529:                         $location=&filelocation($dir,$location);
 9530:                        
 9531:                         my $importmode=$token->[2]->{'importmode'};
 9532:                         if ($importmode eq 'problem') {
 9533: # Import as problem/response
 9534:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 9535:                         } elsif ($importmode eq 'part') {
 9536: # Import as part(s)
 9537:                            $importedparts=1;
 9538: # We need to get the original file and the imported file to get the part order correct
 9539: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
 9540: # Load and inspect original file
 9541:                            if ($#origfileimportpartids<0) {
 9542:                               undef(%importedpartids);
 9543:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
 9544:                               my $origfile=&getfile($origfilelocation);
 9545:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
 9546:                            }
 9547: 
 9548: # Load and inspect imported file
 9549:                            my $impfile=&getfile($location);
 9550:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
 9551:                            if ($#impfilepartids>=0) {
 9552: # This problem had parts
 9553:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
 9554:                            } else {
 9555: # Importing by turning a single problem into a problem part
 9556: # It gets the import-tags ID as part-ID
 9557:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
 9558:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
 9559:                            }
 9560:                         } else {
 9561: # Normal import
 9562:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 9563:                            if (defined($token->[2]->{'id'})) {
 9564:                               $unikey.='_'.$token->[2]->{'id'};
 9565:                            }
 9566:                         }
 9567: 
 9568: 			if ($depthcount<20) {
 9569: 			    my $metadata = 
 9570: 				&metadata($uri,'keys', $location,$unikey,
 9571: 					  $depthcount+1);
 9572: 			    foreach my $meta (split(',',$metadata)) {
 9573: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
 9574: 				$metathesekeys{$meta}=1;
 9575: 			    }
 9576: 			
 9577:                         }
 9578: 		    } else {
 9579: #
 9580: # Not importing, some other kind of non-package, non-library start tag
 9581: # 
 9582:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
 9583:                         if (defined($token->[2]->{'id'})) {
 9584:                             $unikey.='_'.$token->[2]->{'id'};
 9585:                         }
 9586: 			if (defined($token->[2]->{'name'})) { 
 9587: 			    $unikey.='_'.$token->[2]->{'name'}; 
 9588: 			}
 9589: 			$metathesekeys{$unikey}=1;
 9590: 			foreach my $param (@{$token->[3]}) {
 9591: 			    $metaentry{':'.$unikey.'.'.$param} =
 9592: 				$token->[2]->{$param};
 9593: 			}
 9594: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
 9595: 			my $default=$metaentry{':'.$unikey.'.default'};
 9596: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
 9597: 		 # only ws inside the tag, and not in default, so use default
 9598: 		 # as value
 9599: 			    $metaentry{':'.$unikey}=$default;
 9600: 			} elsif ( $internaltext =~ /\S/ ) {
 9601: 		  # something interesting inside the tag
 9602: 			    $metaentry{':'.$unikey}=$internaltext;
 9603: 			} else {
 9604: 		  # no interesting values, don't set a default
 9605: 			}
 9606: # end of not-a-package not-a-library import
 9607: 		    }
 9608: # end of not-a-package start tag
 9609: 		}
 9610: # the next is the end of "start tag"
 9611: 	    }
 9612: 	}
 9613: 	my ($extension) = ($uri =~ /\.(\w+)$/);
 9614: 	$extension = lc($extension);
 9615: 	if ($extension eq 'htm') { $extension='html'; }
 9616: 
 9617: 	foreach my $key (keys(%packagetab)) {
 9618: 	    #no specific packages #how's our extension
 9619: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
 9620: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
 9621: 					 \%metathesekeys);
 9622: 	}
 9623: 
 9624: 	if (!exists($metaentry{':packages'})
 9625: 	    || $packagetab{"import_defaults&extension_$extension"}) {
 9626: 	    foreach my $key (keys(%packagetab)) {
 9627: 		#no specific packages well let's get default then
 9628: 		if ($key!~/^default&/) { next; }
 9629: 		&metadata_create_package_def($uri,$key,'default',
 9630: 					     \%metathesekeys);
 9631: 	    }
 9632: 	}
 9633: # are there custom rights to evaluate
 9634: 	if ($metaentry{':copyright'} eq 'custom') {
 9635: 
 9636:     #
 9637:     # Importing a rights file here
 9638:     #
 9639: 	    unless ($depthcount) {
 9640: 		my $location=$metaentry{':customdistributionfile'};
 9641: 		my $dir=$filename;
 9642: 		$dir=~s|[^/]*$||;
 9643: 		$location=&filelocation($dir,$location);
 9644: 		my $rights_metadata =
 9645: 		    &metadata($uri,'keys',$location,'_rights',
 9646: 			      $depthcount+1);
 9647: 		foreach my $rights (split(',',$rights_metadata)) {
 9648: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
 9649: 		    $metathesekeys{$rights}=1;
 9650: 		}
 9651: 	    }
 9652: 	}
 9653: 	# uniqifiy package listing
 9654: 	my %seen;
 9655: 	my @uniq_packages =
 9656: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
 9657: 	$metaentry{':packages'} = join(',',@uniq_packages);
 9658: 
 9659:         if ($importedparts) {
 9660: # We had imported parts and need to rebuild partorder
 9661:            $metaentry{':partorder'}='';
 9662:            $metathesekeys{'partorder'}=1;
 9663:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
 9664:                if ($origfileimportpartids[$index] eq 'part') {
 9665: # original part, part of the problem
 9666:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
 9667:                } else {
 9668: # we have imported parts at this position
 9669:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
 9670:                }
 9671:            }
 9672:            $metaentry{':partorder'}=~s/^\,//;
 9673:         }
 9674: 
 9675: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
 9676: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
 9677: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
 9678: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
 9679: # this is the end of "was not already recently cached
 9680:     }
 9681:     return $metaentry{':'.$what};
 9682: }
 9683: 
 9684: sub metadata_create_package_def {
 9685:     my ($uri,$key,$package,$metathesekeys)=@_;
 9686:     my ($pack,$name,$subp)=split(/\&/,$key);
 9687:     if ($subp eq 'default') { next; }
 9688:     
 9689:     if (defined($metaentry{':packages'})) {
 9690: 	$metaentry{':packages'}.=','.$package;
 9691:     } else {
 9692: 	$metaentry{':packages'}=$package;
 9693:     }
 9694:     my $value=$packagetab{$key};
 9695:     my $unikey;
 9696:     $unikey='parameter_0_'.$name;
 9697:     $metaentry{':'.$unikey.'.part'}=0;
 9698:     $$metathesekeys{$unikey}=1;
 9699:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 9700: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
 9701:     }
 9702:     if (defined($metaentry{':'.$unikey.'.default'})) {
 9703: 	$metaentry{':'.$unikey}=
 9704: 	    $metaentry{':'.$unikey.'.default'};
 9705:     }
 9706: }
 9707: 
 9708: sub metadata_generate_part0 {
 9709:     my ($metadata,$metacache,$uri) = @_;
 9710:     my %allnames;
 9711:     foreach my $metakey (keys(%$metadata)) {
 9712: 	if ($metakey=~/^parameter\_(.*)/) {
 9713: 	  my $part=$$metacache{':'.$metakey.'.part'};
 9714: 	  my $name=$$metacache{':'.$metakey.'.name'};
 9715: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
 9716: 	    $allnames{$name}=$part;
 9717: 	  }
 9718: 	}
 9719:     }
 9720:     foreach my $name (keys(%allnames)) {
 9721:       $$metadata{"parameter_0_$name"}=1;
 9722:       my $key=":parameter_0_$name";
 9723:       $$metacache{"$key.part"}='0';
 9724:       $$metacache{"$key.name"}=$name;
 9725:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
 9726: 					   $allnames{$name}.'_'.$name.
 9727: 					   '.type'};
 9728:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
 9729: 			     '.display'};
 9730:       my $expr='[Part: '.$allnames{$name}.']';
 9731:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
 9732:       $$metacache{"$key.display"}=$olddis;
 9733:     }
 9734: }
 9735: 
 9736: # ------------------------------------------------------ Devalidate title cache
 9737: 
 9738: sub devalidate_title_cache {
 9739:     my ($url)=@_;
 9740:     if (!$env{'request.course.id'}) { return; }
 9741:     my $symb=&symbread($url);
 9742:     if (!$symb) { return; }
 9743:     my $key=$env{'request.course.id'}."\0".$symb;
 9744:     &devalidate_cache_new('title',$key);
 9745: }
 9746: 
 9747: # ------------------------------------------------- Get the title of a course
 9748: 
 9749: sub current_course_title {
 9750:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
 9751: }
 9752: # ------------------------------------------------- Get the title of a resource
 9753: 
 9754: sub gettitle {
 9755:     my $urlsymb=shift;
 9756:     my $symb=&symbread($urlsymb);
 9757:     if ($symb) {
 9758: 	my $key=$env{'request.course.id'}."\0".$symb;
 9759: 	my ($result,$cached)=&is_cached_new('title',$key);
 9760: 	if (defined($cached)) { 
 9761: 	    return $result;
 9762: 	}
 9763: 	my ($map,$resid,$url)=&decode_symb($symb);
 9764: 	my $title='';
 9765: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
 9766: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
 9767: 	} else {
 9768: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9769: 		    &GDBM_READER(),0640)) {
 9770: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
 9771: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
 9772: 		untie(%bighash);
 9773: 	    }
 9774: 	}
 9775: 	$title=~s/\&colon\;/\:/gs;
 9776: 	if ($title) {
 9777: # Remember both $symb and $title for dynamic metadata
 9778:             $accesshash{$symb.'___crstitle'}=$title;
 9779:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
 9780: # Cache this title and then return it
 9781: 	    return &do_cache_new('title',$key,$title,600);
 9782: 	}
 9783: 	$urlsymb=$url;
 9784:     }
 9785:     my $title=&metadata($urlsymb,'title');
 9786:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
 9787:     return $title;
 9788: }
 9789: 
 9790: sub get_slot {
 9791:     my ($which,$cnum,$cdom)=@_;
 9792:     if (!$cnum || !$cdom) {
 9793: 	(undef,my $courseid)=&whichuser();
 9794: 	$cdom=$env{'course.'.$courseid.'.domain'};
 9795: 	$cnum=$env{'course.'.$courseid.'.num'};
 9796:     }
 9797:     my $key=join("\0",'slots',$cdom,$cnum,$which);
 9798:     my %slotinfo;
 9799:     if (exists($remembered{$key})) {
 9800: 	$slotinfo{$which} = $remembered{$key};
 9801:     } else {
 9802: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
 9803: 	&Apache::lonhomework::showhash(%slotinfo);
 9804: 	my ($tmp)=keys(%slotinfo);
 9805: 	if ($tmp=~/^error:/) { return (); }
 9806: 	$remembered{$key} = $slotinfo{$which};
 9807:     }
 9808:     if (ref($slotinfo{$which}) eq 'HASH') {
 9809: 	return %{$slotinfo{$which}};
 9810:     }
 9811:     return $slotinfo{$which};
 9812: }
 9813: 
 9814: sub get_reservable_slots {
 9815:     my ($cnum,$cdom,$uname,$udom) = @_;
 9816:     my $now = time;
 9817:     my $reservable_info;
 9818:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
 9819:     if (exists($remembered{$key})) {
 9820:         $reservable_info = $remembered{$key};
 9821:     } else {
 9822:         my %resv;
 9823:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
 9824:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
 9825:         $reservable_info = \%resv;
 9826:         $remembered{$key} = $reservable_info;
 9827:     }
 9828:     return $reservable_info;
 9829: }
 9830: 
 9831: sub get_course_slots {
 9832:     my ($cnum,$cdom) = @_;
 9833:     my $hashid=$cnum.':'.$cdom;
 9834:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
 9835:     if (defined($cached)) {
 9836:         if (ref($result) eq 'HASH') {
 9837:             return %{$result};
 9838:         }
 9839:     } else {
 9840:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
 9841:         my ($tmp) = keys(%slots);
 9842:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 9843:             &Apache::lonnet::do_cache_new('allslots',$hashid,\%slots,600);
 9844:             return %slots;
 9845:         }
 9846:     }
 9847:     return;
 9848: }
 9849: 
 9850: sub devalidate_slots_cache {
 9851:     my ($cnum,$cdom)=@_;
 9852:     my $hashid=$cnum.':'.$cdom;
 9853:     &devalidate_cache_new('allslots',$hashid);
 9854: }
 9855: 
 9856: sub get_coursechange {
 9857:     my ($cdom,$cnum) = @_;
 9858:     if ($cdom eq '' || $cnum eq '') {
 9859:         return unless ($env{'request.course.id'});
 9860:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9861:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9862:     }
 9863:     my $hashid=$cdom.'_'.$cnum;
 9864:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
 9865:     if ((defined($cached)) && ($change ne '')) {
 9866:         return $change;
 9867:     } else {
 9868:         my %crshash;
 9869:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
 9870:         if ($crshash{'internal.contentchange'} eq '') {
 9871:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
 9872:             if ($change eq '') {
 9873:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
 9874:                 $change = $crshash{'internal.created'};
 9875:             }
 9876:         } else {
 9877:             $change = $crshash{'internal.contentchange'};
 9878:         }
 9879:         my $cachetime = 600;
 9880:         &do_cache_new('crschange',$hashid,$change,$cachetime);
 9881:     }
 9882:     return $change;
 9883: }
 9884: 
 9885: sub devalidate_coursechange_cache {
 9886:     my ($cnum,$cdom)=@_;
 9887:     my $hashid=$cnum.':'.$cdom;
 9888:     &devalidate_cache_new('crschange',$hashid);
 9889: }
 9890: 
 9891: # ------------------------------------------------- Update symbolic store links
 9892: 
 9893: sub symblist {
 9894:     my ($mapname,%newhash)=@_;
 9895:     $mapname=&deversion(&declutter($mapname));
 9896:     my %hash;
 9897:     if (($env{'request.course.fn'}) && (%newhash)) {
 9898:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 9899:                       &GDBM_WRCREAT(),0640)) {
 9900: 	    foreach my $url (keys(%newhash)) {
 9901: 		next if ($url eq 'last_known'
 9902: 			 && $env{'form.no_update_last_known'});
 9903: 		$hash{declutter($url)}=&encode_symb($mapname,
 9904: 						    $newhash{$url}->[1],
 9905: 						    $newhash{$url}->[0]);
 9906:             }
 9907:             if (untie(%hash)) {
 9908: 		return 'ok';
 9909:             }
 9910:         }
 9911:     }
 9912:     return 'error';
 9913: }
 9914: 
 9915: # --------------------------------------------------------------- Verify a symb
 9916: 
 9917: sub symbverify {
 9918:     my ($symb,$thisurl)=@_;
 9919:     my $thisfn=$thisurl;
 9920:     $thisfn=&declutter($thisfn);
 9921: # direct jump to resource in page or to a sequence - will construct own symbs
 9922:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
 9923: # check URL part
 9924:     my ($map,$resid,$url)=&decode_symb($symb);
 9925: 
 9926:     unless ($url eq $thisfn) { return 0; }
 9927: 
 9928:     $symb=&symbclean($symb);
 9929:     $thisurl=&deversion($thisurl);
 9930:     $thisfn=&deversion($thisfn);
 9931: 
 9932:     my %bighash;
 9933:     my $okay=0;
 9934: 
 9935:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9936:                             &GDBM_READER(),0640)) {
 9937:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
 9938:             $thisurl =~ s/\?.+$//;
 9939:         }
 9940:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
 9941:         unless ($ids) {
 9942:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
 9943:             $ids=$bighash{$idkey};
 9944:         }
 9945:         if ($ids) {
 9946: # ------------------------------------------------------------------- Has ID(s)
 9947: 	    foreach my $id (split(/\,/,$ids)) {
 9948: 	       my ($mapid,$resid)=split(/\./,$id);
 9949:                if ($thisfn =~ m{^/adm/wrapper/ext/}) {
 9950:                    $symb =~ s/\?.+$//;
 9951:                }
 9952:                if (
 9953:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
 9954:    eq $symb) { 
 9955: 		   if (($env{'request.role.adv'}) ||
 9956: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
 9957:                        ($thisurl eq '/adm/navmaps')) {
 9958: 		       $okay=1; 
 9959: 		   }
 9960: 	       }
 9961: 	   }
 9962:         }
 9963: 	untie(%bighash);
 9964:     }
 9965:     return $okay;
 9966: }
 9967: 
 9968: # --------------------------------------------------------------- Clean-up symb
 9969: 
 9970: sub symbclean {
 9971:     my $symb=shift;
 9972:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 9973: # remove version from map
 9974:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
 9975: 
 9976: # remove version from URL
 9977:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
 9978: 
 9979: # remove wrapper
 9980: 
 9981:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
 9982:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
 9983:     return $symb;
 9984: }
 9985: 
 9986: # ---------------------------------------------- Split symb to find map and url
 9987: 
 9988: sub encode_symb {
 9989:     my ($map,$resid,$url)=@_;
 9990:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
 9991: }
 9992: 
 9993: sub decode_symb {
 9994:     my $symb=shift;
 9995:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 9996:     my ($map,$resid,$url)=split(/___/,$symb);
 9997:     return (&fixversion($map),$resid,&fixversion($url));
 9998: }
 9999: 
10000: sub fixversion {
10001:     my $fn=shift;
10002:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
10003:     my %bighash;
10004:     my $uri=&clutter($fn);
10005:     my $key=$env{'request.course.id'}.'_'.$uri;
10006: # is this cached?
10007:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
10008:     if (defined($cached)) { return $result; }
10009: # unfortunately not cached, or expired
10010:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10011: 	    &GDBM_READER(),0640)) {
10012:  	if ($bighash{'version_'.$uri}) {
10013:  	    my $version=$bighash{'version_'.$uri};
10014:  	    unless (($version eq 'mostrecent') || 
10015: 		    ($version==&getversion($uri))) {
10016:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
10017:  	    }
10018:  	}
10019:  	untie %bighash;
10020:     }
10021:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
10022: }
10023: 
10024: sub deversion {
10025:     my $url=shift;
10026:     $url=~s/\.\d+\.(\w+)$/\.$1/;
10027:     return $url;
10028: }
10029: 
10030: # ------------------------------------------------------ Return symb list entry
10031: 
10032: sub symbread {
10033:     my ($thisfn,$donotrecurse)=@_;
10034:     my $cache_str='request.symbread.cached.'.$thisfn;
10035:     if (defined($env{$cache_str})) {
10036:         if (($thisfn) || ($env{$cache_str} ne '')) {
10037:             return $env{$cache_str};
10038:         }
10039:     }
10040: # no filename provided? try from environment
10041:     unless ($thisfn) {
10042:         if ($env{'request.symb'}) {
10043: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
10044: 	}
10045: 	$thisfn=$env{'request.filename'};
10046:     }
10047:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
10048: # is that filename actually a symb? Verify, clean, and return
10049:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
10050: 	if (&symbverify($thisfn,$1)) {
10051: 	    return $env{$cache_str}=&symbclean($thisfn);
10052: 	}
10053:     }
10054:     $thisfn=declutter($thisfn);
10055:     my %hash;
10056:     my %bighash;
10057:     my $syval='';
10058:     if (($env{'request.course.fn'}) && ($thisfn)) {
10059:         my $targetfn = $thisfn;
10060:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
10061:             $targetfn = 'adm/wrapper/'.$thisfn;
10062:         }
10063: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
10064: 	    $targetfn=$1;
10065: 	}
10066:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
10067:                       &GDBM_READER(),0640)) {
10068: 	    $syval=$hash{$targetfn};
10069:             untie(%hash);
10070:         }
10071: # ---------------------------------------------------------- There was an entry
10072:         if ($syval) {
10073: 	    #unless ($syval=~/\_\d+$/) {
10074: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
10075: 		    #&appenv({'request.ambiguous' => $thisfn});
10076: 		    #return $env{$cache_str}='';
10077: 		#}    
10078: 		#$syval.=$1;
10079: 	    #}
10080:         } else {
10081: # ------------------------------------------------------- Was not in symb table
10082:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10083:                             &GDBM_READER(),0640)) {
10084: # ---------------------------------------------- Get ID(s) for current resource
10085:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
10086:               unless ($ids) { 
10087:                  $ids=$bighash{'ids_/'.$thisfn};
10088:               }
10089:               unless ($ids) {
10090: # alias?
10091: 		  $ids=$bighash{'mapalias_'.$thisfn};
10092:               }
10093:               if ($ids) {
10094: # ------------------------------------------------------------------- Has ID(s)
10095:                  my @possibilities=split(/\,/,$ids);
10096:                  if ($#possibilities==0) {
10097: # ----------------------------------------------- There is only one possibility
10098: 		     my ($mapid,$resid)=split(/\./,$ids);
10099: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
10100: 						    $resid,$thisfn);
10101:                  } elsif (!$donotrecurse) {
10102: # ------------------------------------------ There is more than one possibility
10103:                      my $realpossible=0;
10104:                      foreach my $id (@possibilities) {
10105: 			 my $file=$bighash{'src_'.$id};
10106:                          if (&allowed('bre',$file)) {
10107:          		    my ($mapid,$resid)=split(/\./,$id);
10108:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
10109: 				$realpossible++;
10110:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
10111: 						    $resid,$thisfn);
10112:                             }
10113: 			 }
10114:                      }
10115: 		     if ($realpossible!=1) { $syval=''; }
10116:                  } else {
10117:                      $syval='';
10118:                  }
10119: 	      }
10120:               untie(%bighash)
10121:            }
10122:         }
10123:         if ($syval) {
10124: 	    return $env{$cache_str}=$syval;
10125:         }
10126:     }
10127:     &appenv({'request.ambiguous' => $thisfn});
10128:     return $env{$cache_str}='';
10129: }
10130: 
10131: # ---------------------------------------------------------- Return random seed
10132: 
10133: sub numval {
10134:     my $txt=shift;
10135:     $txt=~tr/A-J/0-9/;
10136:     $txt=~tr/a-j/0-9/;
10137:     $txt=~tr/K-T/0-9/;
10138:     $txt=~tr/k-t/0-9/;
10139:     $txt=~tr/U-Z/0-5/;
10140:     $txt=~tr/u-z/0-5/;
10141:     $txt=~s/\D//g;
10142:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
10143:     return int($txt);
10144: }
10145: 
10146: sub numval2 {
10147:     my $txt=shift;
10148:     $txt=~tr/A-J/0-9/;
10149:     $txt=~tr/a-j/0-9/;
10150:     $txt=~tr/K-T/0-9/;
10151:     $txt=~tr/k-t/0-9/;
10152:     $txt=~tr/U-Z/0-5/;
10153:     $txt=~tr/u-z/0-5/;
10154:     $txt=~s/\D//g;
10155:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10156:     my $total;
10157:     foreach my $val (@txts) { $total+=$val; }
10158:     if ($_64bit) { if ($total > 2**32) { return -1; } }
10159:     return int($total);
10160: }
10161: 
10162: sub numval3 {
10163:     use integer;
10164:     my $txt=shift;
10165:     $txt=~tr/A-J/0-9/;
10166:     $txt=~tr/a-j/0-9/;
10167:     $txt=~tr/K-T/0-9/;
10168:     $txt=~tr/k-t/0-9/;
10169:     $txt=~tr/U-Z/0-5/;
10170:     $txt=~tr/u-z/0-5/;
10171:     $txt=~s/\D//g;
10172:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10173:     my $total;
10174:     foreach my $val (@txts) { $total+=$val; }
10175:     if ($_64bit) { $total=(($total<<32)>>32); }
10176:     return $total;
10177: }
10178: 
10179: sub digest {
10180:     my ($data)=@_;
10181:     my $digest=&Digest::MD5::md5($data);
10182:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
10183:     my ($e,$f);
10184:     {
10185:         use integer;
10186:         $e=($a+$b);
10187:         $f=($c+$d);
10188:         if ($_64bit) {
10189:             $e=(($e<<32)>>32);
10190:             $f=(($f<<32)>>32);
10191:         }
10192:     }
10193:     if (wantarray) {
10194: 	return ($e,$f);
10195:     } else {
10196: 	my $g;
10197: 	{
10198: 	    use integer;
10199: 	    $g=($e+$f);
10200: 	    if ($_64bit) {
10201: 		$g=(($g<<32)>>32);
10202: 	    }
10203: 	}
10204: 	return $g;
10205:     }
10206: }
10207: 
10208: sub latest_rnd_algorithm_id {
10209:     return '64bit5';
10210: }
10211: 
10212: sub get_rand_alg {
10213:     my ($courseid)=@_;
10214:     if (!$courseid) { $courseid=(&whichuser())[1]; }
10215:     if ($courseid) {
10216: 	return $env{"course.$courseid.rndseed"};
10217:     }
10218:     return &latest_rnd_algorithm_id();
10219: }
10220: 
10221: sub validCODE {
10222:     my ($CODE)=@_;
10223:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
10224:     return 0;
10225: }
10226: 
10227: sub getCODE {
10228:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
10229:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
10230: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
10231: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
10232: 	return $Apache::lonhomework::history{'resource.CODE'};
10233:     }
10234:     return undef;
10235: }
10236: #
10237: #  Determines the random seed for a specific context:
10238: #
10239: # parameters:
10240: #   symb      - in course context the symb for the seed.
10241: #   course_id - The course id of the form domain_coursenum.
10242: #   domain    - Domain for the user.
10243: #   course    - Course for the user.
10244: #   cenv      - environment of the course.
10245: #
10246: # NOTE:
10247: #   All parameters are picked out of the environment if missing
10248: #   or not defined.
10249: #   If a symb cannot be determined the current time is used instead.
10250: #
10251: #  For a given well defined symb, courside, domain, username,
10252: #  and course environment, the seed is reproducible.
10253: #
10254: sub rndseed {
10255:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
10256:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
10257:     if (!defined($symb)) {
10258: 	unless ($symb=$wsymb) { return time; }
10259:     }
10260:     if (!defined $courseid) { 
10261: 	$courseid=$wcourseid; 
10262:     }
10263:     if (!defined $domain) { $domain=$wdomain; }
10264:     if (!defined $username) { $username=$wusername }
10265: 
10266:     my $which;
10267:     if (defined($cenv->{'rndseed'})) {
10268: 	$which = $cenv->{'rndseed'};
10269:     } else {
10270: 	$which =&get_rand_alg($courseid);
10271:     }
10272:     if (defined(&getCODE())) {
10273: 
10274: 	if ($which eq '64bit5') {
10275: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
10276: 	} elsif ($which eq '64bit4') {
10277: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
10278: 	} else {
10279: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
10280: 	}
10281:     } elsif ($which eq '64bit5') {
10282: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
10283:     } elsif ($which eq '64bit4') {
10284: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
10285:     } elsif ($which eq '64bit3') {
10286: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
10287:     } elsif ($which eq '64bit2') {
10288: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
10289:     } elsif ($which eq '64bit') {
10290: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
10291:     }
10292:     return &rndseed_32bit($symb,$courseid,$domain,$username);
10293: }
10294: 
10295: sub rndseed_32bit {
10296:     my ($symb,$courseid,$domain,$username)=@_;
10297:     {
10298: 	use integer;
10299: 	my $symbchck=unpack("%32C*",$symb) << 27;
10300: 	my $symbseed=numval($symb) << 22;
10301: 	my $namechck=unpack("%32C*",$username) << 17;
10302: 	my $nameseed=numval($username) << 12;
10303: 	my $domainseed=unpack("%32C*",$domain) << 7;
10304: 	my $courseseed=unpack("%32C*",$courseid);
10305: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
10306: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10307: 	#&logthis("rndseed :$num:$symb");
10308: 	if ($_64bit) { $num=(($num<<32)>>32); }
10309: 	return $num;
10310:     }
10311: }
10312: 
10313: sub rndseed_64bit {
10314:     my ($symb,$courseid,$domain,$username)=@_;
10315:     {
10316: 	use integer;
10317: 	my $symbchck=unpack("%32S*",$symb) << 21;
10318: 	my $symbseed=numval($symb) << 10;
10319: 	my $namechck=unpack("%32S*",$username);
10320: 	
10321: 	my $nameseed=numval($username) << 21;
10322: 	my $domainseed=unpack("%32S*",$domain) << 10;
10323: 	my $courseseed=unpack("%32S*",$courseid);
10324: 	
10325: 	my $num1=$symbchck+$symbseed+$namechck;
10326: 	my $num2=$nameseed+$domainseed+$courseseed;
10327: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10328: 	#&logthis("rndseed :$num:$symb");
10329: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10330: 	return "$num1,$num2";
10331:     }
10332: }
10333: 
10334: sub rndseed_64bit2 {
10335:     my ($symb,$courseid,$domain,$username)=@_;
10336:     {
10337: 	use integer;
10338: 	# strings need to be an even # of cahracters long, it it is odd the
10339:         # last characters gets thrown away
10340: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
10341: 	my $symbseed=numval($symb) << 10;
10342: 	my $namechck=unpack("%32S*",$username.' ');
10343: 	
10344: 	my $nameseed=numval($username) << 21;
10345: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
10346: 	my $courseseed=unpack("%32S*",$courseid.' ');
10347: 	
10348: 	my $num1=$symbchck+$symbseed+$namechck;
10349: 	my $num2=$nameseed+$domainseed+$courseseed;
10350: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10351: 	#&logthis("rndseed :$num:$symb");
10352: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10353: 	return "$num1,$num2";
10354:     }
10355: }
10356: 
10357: sub rndseed_64bit3 {
10358:     my ($symb,$courseid,$domain,$username)=@_;
10359:     {
10360: 	use integer;
10361: 	# strings need to be an even # of cahracters long, it it is odd the
10362:         # last characters gets thrown away
10363: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
10364: 	my $symbseed=numval2($symb) << 10;
10365: 	my $namechck=unpack("%32S*",$username.' ');
10366: 	
10367: 	my $nameseed=numval2($username) << 21;
10368: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
10369: 	my $courseseed=unpack("%32S*",$courseid.' ');
10370: 	
10371: 	my $num1=$symbchck+$symbseed+$namechck;
10372: 	my $num2=$nameseed+$domainseed+$courseseed;
10373: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10374: 	#&logthis("rndseed :$num1:$num2:$_64bit");
10375: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10376: 	
10377: 	return "$num1:$num2";
10378:     }
10379: }
10380: 
10381: sub rndseed_64bit4 {
10382:     my ($symb,$courseid,$domain,$username)=@_;
10383:     {
10384: 	use integer;
10385: 	# strings need to be an even # of cahracters long, it it is odd the
10386:         # last characters gets thrown away
10387: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
10388: 	my $symbseed=numval3($symb) << 10;
10389: 	my $namechck=unpack("%32S*",$username.' ');
10390: 	
10391: 	my $nameseed=numval3($username) << 21;
10392: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
10393: 	my $courseseed=unpack("%32S*",$courseid.' ');
10394: 	
10395: 	my $num1=$symbchck+$symbseed+$namechck;
10396: 	my $num2=$nameseed+$domainseed+$courseseed;
10397: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10398: 	#&logthis("rndseed :$num1:$num2:$_64bit");
10399: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10400: 	
10401: 	return "$num1:$num2";
10402:     }
10403: }
10404: 
10405: sub rndseed_64bit5 {
10406:     my ($symb,$courseid,$domain,$username)=@_;
10407:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
10408:     return "$num1:$num2";
10409: }
10410: 
10411: sub rndseed_CODE_64bit {
10412:     my ($symb,$courseid,$domain,$username)=@_;
10413:     {
10414: 	use integer;
10415: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
10416: 	my $symbseed=numval2($symb);
10417: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
10418: 	my $CODEseed=numval(&getCODE());
10419: 	my $courseseed=unpack("%32S*",$courseid.' ');
10420: 	my $num1=$symbseed+$CODEchck;
10421: 	my $num2=$CODEseed+$courseseed+$symbchck;
10422: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
10423: 	#&logthis("rndseed :$num1:$num2:$symb");
10424: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
10425: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
10426: 	return "$num1:$num2";
10427:     }
10428: }
10429: 
10430: sub rndseed_CODE_64bit4 {
10431:     my ($symb,$courseid,$domain,$username)=@_;
10432:     {
10433: 	use integer;
10434: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
10435: 	my $symbseed=numval3($symb);
10436: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
10437: 	my $CODEseed=numval3(&getCODE());
10438: 	my $courseseed=unpack("%32S*",$courseid.' ');
10439: 	my $num1=$symbseed+$CODEchck;
10440: 	my $num2=$CODEseed+$courseseed+$symbchck;
10441: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
10442: 	#&logthis("rndseed :$num1:$num2:$symb");
10443: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
10444: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
10445: 	return "$num1:$num2";
10446:     }
10447: }
10448: 
10449: sub rndseed_CODE_64bit5 {
10450:     my ($symb,$courseid,$domain,$username)=@_;
10451:     my $code = &getCODE();
10452:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
10453:     return "$num1:$num2";
10454: }
10455: 
10456: sub setup_random_from_rndseed {
10457:     my ($rndseed)=@_;
10458:     if ($rndseed =~/([,:])/) {
10459: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
10460: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
10461:     } else {
10462: 	&Math::Random::random_set_seed_from_phrase($rndseed);
10463:     }
10464: }
10465: 
10466: sub latest_receipt_algorithm_id {
10467:     return 'receipt3';
10468: }
10469: 
10470: sub recunique {
10471:     my $fucourseid=shift;
10472:     my $unique;
10473:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
10474: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
10475: 	$unique=$env{"course.$fucourseid.internal.encseed"};
10476:     } else {
10477: 	$unique=$perlvar{'lonReceipt'};
10478:     }
10479:     return unpack("%32C*",$unique);
10480: }
10481: 
10482: sub recprefix {
10483:     my $fucourseid=shift;
10484:     my $prefix;
10485:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
10486: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
10487: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
10488:     } else {
10489: 	$prefix=$perlvar{'lonHostID'};
10490:     }
10491:     return unpack("%32C*",$prefix);
10492: }
10493: 
10494: sub ireceipt {
10495:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
10496: 
10497:     my $return =&recprefix($fucourseid).'-';
10498: 
10499:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
10500: 	$env{'request.state'} eq 'construct') {
10501: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
10502: 	return $return;
10503:     }
10504: 
10505:     my $cuname=unpack("%32C*",$funame);
10506:     my $cudom=unpack("%32C*",$fudom);
10507:     my $cucourseid=unpack("%32C*",$fucourseid);
10508:     my $cusymb=unpack("%32C*",$fusymb);
10509:     my $cunique=&recunique($fucourseid);
10510:     my $cpart=unpack("%32S*",$part);
10511:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
10512: 
10513: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
10514: 			       
10515: 	$return.= ($cunique%$cuname+
10516: 		   $cunique%$cudom+
10517: 		   $cusymb%$cuname+
10518: 		   $cusymb%$cudom+
10519: 		   $cucourseid%$cuname+
10520: 		   $cucourseid%$cudom+
10521: 		   $cpart%$cuname+
10522: 		   $cpart%$cudom);
10523:     } else {
10524: 	$return.= ($cunique%$cuname+
10525: 		   $cunique%$cudom+
10526: 		   $cusymb%$cuname+
10527: 		   $cusymb%$cudom+
10528: 		   $cucourseid%$cuname+
10529: 		   $cucourseid%$cudom);
10530:     }
10531:     return $return;
10532: }
10533: 
10534: sub receipt {
10535:     my ($part)=@_;
10536:     my ($symb,$courseid,$domain,$name) = &whichuser();
10537:     return &ireceipt($name,$domain,$courseid,$symb,$part);
10538: }
10539: 
10540: sub whichuser {
10541:     my ($passedsymb)=@_;
10542:     my ($symb,$courseid,$domain,$name,$publicuser);
10543:     if (defined($env{'form.grade_symb'})) {
10544: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
10545: 	my $allowed=&allowed('vgr',$tmp_courseid);
10546: 	if (!$allowed &&
10547: 	    exists($env{'request.course.sec'}) &&
10548: 	    $env{'request.course.sec'} !~ /^\s*$/) {
10549: 	    $allowed=&allowed('vgr',$tmp_courseid.
10550: 			      '/'.$env{'request.course.sec'});
10551: 	}
10552: 	if ($allowed) {
10553: 	    ($symb)=&get_env_multiple('form.grade_symb');
10554: 	    $courseid=$tmp_courseid;
10555: 	    ($domain)=&get_env_multiple('form.grade_domain');
10556: 	    ($name)=&get_env_multiple('form.grade_username');
10557: 	    return ($symb,$courseid,$domain,$name,$publicuser);
10558: 	}
10559:     }
10560:     if (!$passedsymb) {
10561: 	$symb=&symbread();
10562:     } else {
10563: 	$symb=$passedsymb;
10564:     }
10565:     $courseid=$env{'request.course.id'};
10566:     $domain=$env{'user.domain'};
10567:     $name=$env{'user.name'};
10568:     if ($name eq 'public' && $domain eq 'public') {
10569: 	if (!defined($env{'form.username'})) {
10570: 	    $env{'form.username'}.=time.rand(10000000);
10571: 	}
10572: 	$name.=$env{'form.username'};
10573:     }
10574:     return ($symb,$courseid,$domain,$name,$publicuser);
10575: 
10576: }
10577: 
10578: # ------------------------------------------------------------ Serves up a file
10579: # returns either the contents of the file or 
10580: # -1 if the file doesn't exist
10581: #
10582: # if the target is a file that was uploaded via DOCS, 
10583: # a check will be made to see if a current copy exists on the local server,
10584: # if it does this will be served, otherwise a copy will be retrieved from
10585: # the home server for the course and stored in /home/httpd/html/userfiles on
10586: # the local server.   
10587: 
10588: sub getfile {
10589:     my ($file) = @_;
10590:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
10591:     &repcopy($file);
10592:     return &readfile($file);
10593: }
10594: 
10595: sub repcopy_userfile {
10596:     my ($file)=@_;
10597:     my $londocroot = $perlvar{'lonDocRoot'};
10598:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
10599:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
10600:     my ($cdom,$cnum,$filename) = 
10601: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
10602:     my $uri="/uploaded/$cdom/$cnum/$filename";
10603:     if (-e "$file") {
10604: # we already have a local copy, check it out
10605: 	my @fileinfo = stat($file);
10606: 	my $rtncode;
10607: 	my $info;
10608: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
10609: 	if ($lwpresp ne 'ok') {
10610: # there is no such file anymore, even though we had a local copy
10611: 	    if ($rtncode eq '404') {
10612: 		unlink($file);
10613: 	    }
10614: 	    return -1;
10615: 	}
10616: 	if ($info < $fileinfo[9]) {
10617: # nice, the file we have is up-to-date, just say okay
10618: 	    return 'ok';
10619: 	} else {
10620: # the file is outdated, get rid of it
10621: 	    unlink($file);
10622: 	}
10623:     }
10624: # one way or the other, at this point, we don't have the file
10625: # construct the correct path for the file
10626:     my @parts = ($cdom,$cnum); 
10627:     if ($filename =~ m|^(.+)/[^/]+$|) {
10628: 	push @parts, split(/\//,$1);
10629:     }
10630:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
10631:     foreach my $part (@parts) {
10632: 	$path .= '/'.$part;
10633: 	if (!-e $path) {
10634: 	    mkdir($path,0770);
10635: 	}
10636:     }
10637: # now the path exists for sure
10638: # get a user agent
10639:     my $ua=new LWP::UserAgent;
10640:     my $transferfile=$file.'.in.transfer';
10641: # FIXME: this should flock
10642:     if (-e $transferfile) { return 'ok'; }
10643:     my $request;
10644:     $uri=~s/^\///;
10645:     my $homeserver = &homeserver($cnum,$cdom);
10646:     my $protocol = $protocol{$homeserver};
10647:     $protocol = 'http' if ($protocol ne 'https');
10648:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
10649:     my $response=$ua->request($request,$transferfile);
10650: # did it work?
10651:     if ($response->is_error()) {
10652: 	unlink($transferfile);
10653: 	&logthis("Userfile repcopy failed for $uri");
10654: 	return -1;
10655:     }
10656: # worked, rename the transfer file
10657:     rename($transferfile,$file);
10658:     return 'ok';
10659: }
10660: 
10661: sub tokenwrapper {
10662:     my $uri=shift;
10663:     $uri=~s|^https?\://([^/]+)||;
10664:     $uri=~s|^/||;
10665:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
10666:     my $token=$1;
10667:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
10668:     if ($udom && $uname && $file) {
10669: 	$file=~s|(\?\.*)*$||;
10670:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
10671:         my $homeserver = &homeserver($uname,$udom);
10672:         my $protocol = $protocol{$homeserver};
10673:         $protocol = 'http' if ($protocol ne 'https');
10674:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
10675:                (($uri=~/\?/)?'&':'?').'token='.$token.
10676:                                '&tokenissued='.$perlvar{'lonHostID'};
10677:     } else {
10678:         return '/adm/notfound.html';
10679:     }
10680: }
10681: 
10682: # call with reqtype HEAD: get last modification time
10683: # call with reqtype GET: get the file contents
10684: # Do not call this with reqtype GET for large files! It loads everything into memory
10685: #
10686: sub getuploaded {
10687:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
10688:     $uri=~s/^\///;
10689:     my $homeserver = &homeserver($cnum,$cdom);
10690:     my $protocol = $protocol{$homeserver};
10691:     $protocol = 'http' if ($protocol ne 'https');
10692:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
10693:     my $ua=new LWP::UserAgent;
10694:     my $request=new HTTP::Request($reqtype,$uri);
10695:     my $response=$ua->request($request);
10696:     $$rtncode = $response->code;
10697:     if (! $response->is_success()) {
10698: 	return 'failed';
10699:     }      
10700:     if ($reqtype eq 'HEAD') {
10701: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
10702:     } elsif ($reqtype eq 'GET') {
10703: 	$$info = $response->content;
10704:     }
10705:     return 'ok';
10706: }
10707: 
10708: sub readfile {
10709:     my $file = shift;
10710:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
10711:     my $fh;
10712:     open($fh,"<$file");
10713:     my $a='';
10714:     while (my $line = <$fh>) { $a .= $line; }
10715:     return $a;
10716: }
10717: 
10718: sub filelocation {
10719:     my ($dir,$file) = @_;
10720:     my $location;
10721:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
10722: 
10723:     if ($file =~ m-^/adm/-) {
10724: 	$file=~s-^/adm/wrapper/-/-;
10725: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
10726:     }
10727: 
10728:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
10729:         $location = $file;
10730:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
10731:         my ($udom,$uname,$filename)=
10732:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
10733:         my $home=&homeserver($uname,$udom);
10734:         my $is_me=0;
10735:         my @ids=&current_machine_ids();
10736:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
10737:         if ($is_me) {
10738:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
10739:         } else {
10740:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
10741:   	      $udom.'/'.$uname.'/'.$filename;
10742:         }
10743:     } elsif ($file =~ m-^/adm/-) {
10744: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
10745:     } else {
10746:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
10747:         $file=~s:^/(res|priv)/:/:;
10748:         my $space=$1;
10749:         if ( !( $file =~ m:^/:) ) {
10750:             $location = $dir. '/'.$file;
10751:         } else {
10752:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
10753:         }
10754:     }
10755:     $location=~s://+:/:g; # remove duplicate /
10756:     while ($location=~m{/\.\./}) {
10757: 	if ($location =~ m{/[^/]+/\.\./}) {
10758: 	    $location=~ s{/[^/]+/\.\./}{/}g;
10759: 	} else {
10760: 	    $location=~ s{/\.\./}{/}g;
10761: 	}
10762:     } #remove dir/..
10763:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
10764:     return $location;
10765: }
10766: 
10767: sub hreflocation {
10768:     my ($dir,$file)=@_;
10769:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
10770: 	$file=filelocation($dir,$file);
10771:     } elsif ($file=~m-^/adm/-) {
10772: 	$file=~s-^/adm/wrapper/-/-;
10773: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
10774:     }
10775:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
10776: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
10777:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
10778: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
10779: 	        {/uploaded/$1/$2/}x;
10780:     }
10781:     if ($file=~ m{^/userfiles/}) {
10782: 	$file =~ s{^/userfiles/}{/uploaded/};
10783:     }
10784:     return $file;
10785: }
10786: 
10787: 
10788: 
10789: 
10790: 
10791: sub current_machine_domains {
10792:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
10793: }
10794: 
10795: sub machine_domains {
10796:     my ($hostname) = @_;
10797:     my @domains;
10798:     my %hostname = &all_hostnames();
10799:     while( my($id, $name) = each(%hostname)) {
10800: #	&logthis("-$id-$name-$hostname-");
10801: 	if ($hostname eq $name) {
10802: 	    push(@domains,&host_domain($id));
10803: 	}
10804:     }
10805:     return @domains;
10806: }
10807: 
10808: sub current_machine_ids {
10809:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
10810: }
10811: 
10812: sub machine_ids {
10813:     my ($hostname) = @_;
10814:     $hostname ||= &hostname($perlvar{'lonHostID'});
10815:     my @ids;
10816:     my %name_to_host = &all_names();
10817:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
10818: 	return @{ $name_to_host{$hostname} };
10819:     }
10820:     return;
10821: }
10822: 
10823: sub additional_machine_domains {
10824:     my @domains;
10825:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
10826:     while( my $line = <$fh>) {
10827:         $line =~ s/\s//g;
10828:         push(@domains,$line);
10829:     }
10830:     return @domains;
10831: }
10832: 
10833: sub default_login_domain {
10834:     my $domain = $perlvar{'lonDefDomain'};
10835:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
10836:     foreach my $posdom (&current_machine_domains(),
10837:                         &additional_machine_domains()) {
10838:         if (lc($posdom) eq lc($testdomain)) {
10839:             $domain=$posdom;
10840:             last;
10841:         }
10842:     }
10843:     return $domain;
10844: }
10845: 
10846: # ------------------------------------------------------------- Declutters URLs
10847: 
10848: sub declutter {
10849:     my $thisfn=shift;
10850:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
10851:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
10852:     $thisfn=~s/^\///;
10853:     $thisfn=~s|^adm/wrapper/||;
10854:     $thisfn=~s|^adm/coursedocs/showdoc/||;
10855:     $thisfn=~s/^res\///;
10856:     $thisfn=~s/^priv\///;
10857:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
10858:         $thisfn=~s/\?.+$//;
10859:     }
10860:     return $thisfn;
10861: }
10862: 
10863: # ------------------------------------------------------------- Clutter up URLs
10864: 
10865: sub clutter {
10866:     my $thisfn='/'.&declutter(shift);
10867:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
10868: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
10869:        $thisfn='/res'.$thisfn; 
10870:     }
10871:     if ($thisfn !~m|^/adm|) {
10872: 	if ($thisfn =~ m|^/ext/|) {
10873: 	    $thisfn='/adm/wrapper'.$thisfn;
10874: 	} else {
10875: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
10876: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
10877: 	    if ($embstyle eq 'ssi'
10878: 		|| ($embstyle eq 'hdn')
10879: 		|| ($embstyle eq 'rat')
10880: 		|| ($embstyle eq 'prv')
10881: 		|| ($embstyle eq 'ign')) {
10882: 		#do nothing with these
10883: 	    } elsif (($embstyle eq 'img') 
10884: 		|| ($embstyle eq 'emb')
10885: 		|| ($embstyle eq 'wrp')) {
10886: 		$thisfn='/adm/wrapper'.$thisfn;
10887: 	    } elsif ($embstyle eq 'unk'
10888: 		     && $thisfn!~/\.(sequence|page)$/) {
10889: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
10890: 	    } else {
10891: #		&logthis("Got a blank emb style");
10892: 	    }
10893: 	}
10894:     }
10895:     return $thisfn;
10896: }
10897: 
10898: sub clutter_with_no_wrapper {
10899:     my $uri = &clutter(shift);
10900:     if ($uri =~ m-^/adm/-) {
10901: 	$uri =~ s-^/adm/wrapper/-/-;
10902: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
10903:     }
10904:     return $uri;
10905: }
10906: 
10907: sub freeze_escape {
10908:     my ($value)=@_;
10909:     if (ref($value)) {
10910: 	$value=&nfreeze($value);
10911: 	return '__FROZEN__'.&escape($value);
10912:     }
10913:     return &escape($value);
10914: }
10915: 
10916: 
10917: sub thaw_unescape {
10918:     my ($value)=@_;
10919:     if ($value =~ /^__FROZEN__/) {
10920: 	substr($value,0,10,undef);
10921: 	$value=&unescape($value);
10922: 	return &thaw($value);
10923:     }
10924:     return &unescape($value);
10925: }
10926: 
10927: sub correct_line_ends {
10928:     my ($result)=@_;
10929:     $$result =~s/\r\n/\n/mg;
10930:     $$result =~s/\r/\n/mg;
10931: }
10932: # ================================================================ Main Program
10933: 
10934: sub goodbye {
10935:    &logthis("Starting Shut down");
10936: #not converted to using infrastruture and probably shouldn't be
10937:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
10938: #converted
10939: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
10940:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
10941: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
10942: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
10943: #1.1 only
10944: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
10945: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
10946: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
10947: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
10948:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
10949:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
10950:    &logthis(sprintf("%-20s is %s",'hits',$hits));
10951:    &flushcourselogs();
10952:    &logthis("Shutting down");
10953: }
10954: 
10955: sub get_dns {
10956:     my ($url,$func,$ignore_cache) = @_;
10957:     if (!$ignore_cache) {
10958: 	my ($content,$cached)=
10959: 	    &Apache::lonnet::is_cached_new('dns',$url);
10960: 	if ($cached) {
10961: 	    &$func($content);
10962: 	    return;
10963: 	}
10964:     }
10965: 
10966:     my %alldns;
10967:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
10968:     foreach my $dns (<$config>) {
10969: 	next if ($dns !~ /^\^(\S*)/x);
10970:         my $line = $1;
10971:         my ($host,$protocol) = split(/:/,$line);
10972:         if ($protocol ne 'https') {
10973:             $protocol = 'http';
10974:         }
10975: 	$alldns{$host} = $protocol;
10976:     }
10977:     while (%alldns) {
10978: 	my ($dns) = keys(%alldns);
10979: 	my $ua=new LWP::UserAgent;
10980:         $ua->timeout(30);
10981: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
10982: 	my $response=$ua->request($request);
10983:         delete($alldns{$dns});
10984: 	next if ($response->is_error());
10985: 	my @content = split("\n",$response->content);
10986: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
10987: 	&$func(\@content);
10988: 	return;
10989:     }
10990:     close($config);
10991:     my $which = (split('/',$url))[3];
10992:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
10993:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
10994:     my @content = <$config>;
10995:     &$func(\@content);
10996:     return;
10997: }
10998: # ------------------------------------------------------------ Read domain file
10999: {
11000:     my $loaded;
11001:     my %domain;
11002: 
11003:     sub parse_domain_tab {
11004: 	my ($lines) = @_;
11005: 	foreach my $line (@$lines) {
11006: 	    next if ($line =~ /^(\#|\s*$ )/x);
11007: 
11008: 	    chomp($line);
11009: 	    my ($name,@elements) = split(/:/,$line,9);
11010: 	    my %this_domain;
11011: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
11012: 			       'lang_def', 'city', 'longi', 'lati',
11013: 			       'primary') {
11014: 		$this_domain{$field} = shift(@elements);
11015: 	    }
11016: 	    $domain{$name} = \%this_domain;
11017: 	}
11018:     }
11019: 
11020:     sub reset_domain_info {
11021: 	undef($loaded);
11022: 	undef(%domain);
11023:     }
11024: 
11025:     sub load_domain_tab {
11026: 	my ($ignore_cache) = @_;
11027: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
11028: 	my $fh;
11029: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
11030: 	    my @lines = <$fh>;
11031: 	    &parse_domain_tab(\@lines);
11032: 	}
11033: 	close($fh);
11034: 	$loaded = 1;
11035:     }
11036: 
11037:     sub domain {
11038: 	&load_domain_tab() if (!$loaded);
11039: 
11040: 	my ($name,$what) = @_;
11041: 	return if ( !exists($domain{$name}) );
11042: 
11043: 	if (!$what) {
11044: 	    return $domain{$name}{'description'};
11045: 	}
11046: 	return $domain{$name}{$what};
11047:     }
11048: 
11049:     sub domain_info {
11050:         &load_domain_tab() if (!$loaded);
11051:         return %domain;
11052:     }
11053: 
11054: }
11055: 
11056: 
11057: # ------------------------------------------------------------- Read hosts file
11058: {
11059:     my %hostname;
11060:     my %hostdom;
11061:     my %libserv;
11062:     my $loaded;
11063:     my %name_to_host;
11064:     my %internetdom;
11065:     my %LC_dns_serv;
11066: 
11067:     sub parse_hosts_tab {
11068: 	my ($file) = @_;
11069: 	foreach my $configline (@$file) {
11070: 	    next if ($configline =~ /^(\#|\s*$ )/x);
11071:             chomp($configline);
11072: 	    if ($configline =~ /^\^/) {
11073:                 if ($configline =~ /^\^([\w.\-]+)/) {
11074:                     $LC_dns_serv{$1} = 1;
11075:                 }
11076:                 next;
11077:             }
11078: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
11079: 	    $name=~s/\s//g;
11080: 	    if ($id && $domain && $role && $name) {
11081: 		$hostname{$id}=$name;
11082: 		push(@{$name_to_host{$name}}, $id);
11083: 		$hostdom{$id}=$domain;
11084: 		if ($role eq 'library') { $libserv{$id}=$name; }
11085:                 if (defined($protocol)) {
11086:                     if ($protocol eq 'https') {
11087:                         $protocol{$id} = $protocol;
11088:                     } else {
11089:                         $protocol{$id} = 'http'; 
11090:                     }
11091:                 } else {
11092:                     $protocol{$id} = 'http';
11093:                 }
11094:                 if (defined($intdom)) {
11095:                     $internetdom{$id} = $intdom;
11096:                 }
11097: 	    }
11098: 	}
11099:     }
11100:     
11101:     sub reset_hosts_info {
11102: 	&purge_remembered();
11103: 	&reset_domain_info();
11104: 	&reset_hosts_ip_info();
11105: 	undef(%name_to_host);
11106: 	undef(%hostname);
11107: 	undef(%hostdom);
11108: 	undef(%libserv);
11109: 	undef($loaded);
11110:     }
11111: 
11112:     sub load_hosts_tab {
11113: 	my ($ignore_cache) = @_;
11114: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
11115: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11116: 	my @config = <$config>;
11117: 	&parse_hosts_tab(\@config);
11118: 	close($config);
11119: 	$loaded=1;
11120:     }
11121: 
11122:     sub hostname {
11123: 	&load_hosts_tab() if (!$loaded);
11124: 
11125: 	my ($lonid) = @_;
11126: 	return $hostname{$lonid};
11127:     }
11128: 
11129:     sub all_hostnames {
11130: 	&load_hosts_tab() if (!$loaded);
11131: 
11132: 	return %hostname;
11133:     }
11134: 
11135:     sub all_names {
11136: 	&load_hosts_tab() if (!$loaded);
11137: 
11138: 	return %name_to_host;
11139:     }
11140: 
11141:     sub all_host_domain {
11142:         &load_hosts_tab() if (!$loaded);
11143:         return %hostdom;
11144:     }
11145: 
11146:     sub is_library {
11147: 	&load_hosts_tab() if (!$loaded);
11148: 
11149: 	return exists($libserv{$_[0]});
11150:     }
11151: 
11152:     sub all_library {
11153: 	&load_hosts_tab() if (!$loaded);
11154: 
11155: 	return %libserv;
11156:     }
11157: 
11158:     sub unique_library {
11159: 	#2x reverse removes all hostnames that appear more than once
11160:         my %unique = reverse &all_library();
11161:         return reverse %unique;
11162:     }
11163: 
11164:     sub get_servers {
11165: 	&load_hosts_tab() if (!$loaded);
11166: 
11167: 	my ($domain,$type) = @_;
11168: 	my %possible_hosts = ($type eq 'library') ? %libserv
11169: 	                                          : %hostname;
11170: 	my %result;
11171: 	if (ref($domain) eq 'ARRAY') {
11172: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
11173: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
11174: 		    $result{$host} = $hostname;
11175: 		}
11176: 	    }
11177: 	} else {
11178: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
11179: 		if ($hostdom{$host} eq $domain) {
11180: 		    $result{$host} = $hostname;
11181: 		}
11182: 	    }
11183: 	}
11184: 	return %result;
11185:     }
11186: 
11187:     sub get_unique_servers {
11188:         my %unique = reverse &get_servers(@_);
11189: 	return reverse %unique;
11190:     }
11191: 
11192:     sub host_domain {
11193: 	&load_hosts_tab() if (!$loaded);
11194: 
11195: 	my ($lonid) = @_;
11196: 	return $hostdom{$lonid};
11197:     }
11198: 
11199:     sub all_domains {
11200: 	&load_hosts_tab() if (!$loaded);
11201: 
11202: 	my %seen;
11203: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
11204: 	return @uniq;
11205:     }
11206: 
11207:     sub internet_dom {
11208:         &load_hosts_tab() if (!$loaded);
11209: 
11210:         my ($lonid) = @_;
11211:         return $internetdom{$lonid};
11212:     }
11213: 
11214:     sub is_LC_dns {
11215:         &load_hosts_tab() if (!$loaded);
11216: 
11217:         my ($hostname) = @_;
11218:         return exists($LC_dns_serv{$hostname});
11219:     }
11220: 
11221: }
11222: 
11223: { 
11224:     my %iphost;
11225:     my %name_to_ip;
11226:     my %lonid_to_ip;
11227: 
11228:     sub get_hosts_from_ip {
11229: 	my ($ip) = @_;
11230: 	my %iphosts = &get_iphost();
11231: 	if (ref($iphosts{$ip})) {
11232: 	    return @{$iphosts{$ip}};
11233: 	}
11234: 	return;
11235:     }
11236:     
11237:     sub reset_hosts_ip_info {
11238: 	undef(%iphost);
11239: 	undef(%name_to_ip);
11240: 	undef(%lonid_to_ip);
11241:     }
11242: 
11243:     sub get_host_ip {
11244: 	my ($lonid) = @_;
11245: 	if (exists($lonid_to_ip{$lonid})) {
11246: 	    return $lonid_to_ip{$lonid};
11247: 	}
11248: 	my $name=&hostname($lonid);
11249:    	my $ip = gethostbyname($name);
11250: 	return if (!$ip || length($ip) ne 4);
11251: 	$ip=inet_ntoa($ip);
11252: 	$name_to_ip{$name}   = $ip;
11253: 	$lonid_to_ip{$lonid} = $ip;
11254: 	return $ip;
11255:     }
11256:     
11257:     sub get_iphost {
11258: 	my ($ignore_cache) = @_;
11259: 
11260: 	if (!$ignore_cache) {
11261: 	    if (%iphost) {
11262: 		return %iphost;
11263: 	    }
11264: 	    my ($ip_info,$cached)=
11265: 		&Apache::lonnet::is_cached_new('iphost','iphost');
11266: 	    if ($cached) {
11267: 		%iphost      = %{$ip_info->[0]};
11268: 		%name_to_ip  = %{$ip_info->[1]};
11269: 		%lonid_to_ip = %{$ip_info->[2]};
11270: 		return %iphost;
11271: 	    }
11272: 	}
11273: 
11274: 	# get yesterday's info for fallback
11275: 	my %old_name_to_ip;
11276: 	my ($ip_info,$cached)=
11277: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
11278: 	if ($cached) {
11279: 	    %old_name_to_ip = %{$ip_info->[1]};
11280: 	}
11281: 
11282: 	my %name_to_host = &all_names();
11283: 	foreach my $name (keys(%name_to_host)) {
11284: 	    my $ip;
11285: 	    if (!exists($name_to_ip{$name})) {
11286: 		$ip = gethostbyname($name);
11287: 		if (!$ip || length($ip) ne 4) {
11288: 		    if (defined($old_name_to_ip{$name})) {
11289: 			$ip = $old_name_to_ip{$name};
11290: 			&logthis("Can't find $name defaulting to old $ip");
11291: 		    } else {
11292: 			&logthis("Name $name no IP found");
11293: 			next;
11294: 		    }
11295: 		} else {
11296: 		    $ip=inet_ntoa($ip);
11297: 		}
11298: 		$name_to_ip{$name} = $ip;
11299: 	    } else {
11300: 		$ip = $name_to_ip{$name};
11301: 	    }
11302: 	    foreach my $id (@{ $name_to_host{$name} }) {
11303: 		$lonid_to_ip{$id} = $ip;
11304: 	    }
11305: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
11306: 	}
11307: 	&Apache::lonnet::do_cache_new('iphost','iphost',
11308: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
11309: 				      48*60*60);
11310: 
11311: 	return %iphost;
11312:     }
11313: 
11314:     #
11315:     #  Given a DNS returns the loncapa host name for that DNS 
11316:     # 
11317:     sub host_from_dns {
11318:         my ($dns) = @_;
11319:         my @hosts;
11320:         my $ip;
11321: 
11322:         if (exists($name_to_ip{$dns})) {
11323:             $ip = $name_to_ip{$dns};
11324:         }
11325:         if (!$ip) {
11326:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
11327:             if (length($ip) == 4) { 
11328: 	        $ip   = &IO::Socket::inet_ntoa($ip);
11329:             }
11330:         }
11331:         if ($ip) {
11332: 	    @hosts = get_hosts_from_ip($ip);
11333: 	    return $hosts[0];
11334:         }
11335:         return undef;
11336:     }
11337: 
11338:     sub get_internet_names {
11339:         my ($lonid) = @_;
11340:         return if ($lonid eq '');
11341:         my ($idnref,$cached)=
11342:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
11343:         if ($cached) {
11344:             return $idnref;
11345:         }
11346:         my $ip = &get_host_ip($lonid);
11347:         my @hosts = &get_hosts_from_ip($ip);
11348:         my %iphost = &get_iphost();
11349:         my (@idns,%seen);
11350:         foreach my $id (@hosts) {
11351:             my $dom = &host_domain($id);
11352:             my $prim_id = &domain($dom,'primary');
11353:             my $prim_ip = &get_host_ip($prim_id);
11354:             next if ($seen{$prim_ip});
11355:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
11356:                 foreach my $id (@{$iphost{$prim_ip}}) {
11357:                     my $intdom = &internet_dom($id);
11358:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
11359:                         push(@idns,$intdom);
11360:                     }
11361:                 }
11362:             }
11363:             $seen{$prim_ip} = 1;
11364:         }
11365:         return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
11366:     }
11367: 
11368: }
11369: 
11370: sub all_loncaparevs {
11371:     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);
11372: }
11373: 
11374: BEGIN {
11375: 
11376: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
11377:     unless ($readit) {
11378: {
11379:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
11380:     %perlvar = (%perlvar,%{$configvars});
11381: }
11382: 
11383: 
11384: # ------------------------------------------------------ Read spare server file
11385: {
11386:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
11387: 
11388:     while (my $configline=<$config>) {
11389:        chomp($configline);
11390:        if ($configline) {
11391: 	   my ($host,$type) = split(':',$configline,2);
11392: 	   if (!defined($type) || $type eq '') { $type = 'default' };
11393: 	   push(@{ $spareid{$type} }, $host);
11394:        }
11395:     }
11396:     close($config);
11397: }
11398: # ------------------------------------------------------------ Read permissions
11399: {
11400:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
11401: 
11402:     while (my $configline=<$config>) {
11403: 	chomp($configline);
11404: 	if ($configline) {
11405: 	    my ($role,$perm)=split(/ /,$configline);
11406: 	    if ($perm ne '') { $pr{$role}=$perm; }
11407: 	}
11408:     }
11409:     close($config);
11410: }
11411: 
11412: # -------------------------------------------- Read plain texts for permissions
11413: {
11414:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
11415: 
11416:     while (my $configline=<$config>) {
11417: 	chomp($configline);
11418: 	if ($configline) {
11419: 	    my ($short,@plain)=split(/:/,$configline);
11420:             %{$prp{$short}} = ();
11421: 	    if (@plain > 0) {
11422:                 $prp{$short}{'std'} = $plain[0];
11423:                 for (my $i=1; $i<@plain; $i++) {
11424:                     $prp{$short}{'alt'.$i} = $plain[$i];  
11425:                 }
11426:             }
11427: 	}
11428:     }
11429:     close($config);
11430: }
11431: 
11432: # ---------------------------------------------------------- Read package table
11433: {
11434:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
11435: 
11436:     while (my $configline=<$config>) {
11437: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
11438: 	chomp($configline);
11439: 	my ($short,$plain)=split(/:/,$configline);
11440: 	my ($pack,$name)=split(/\&/,$short);
11441: 	if ($plain ne '') {
11442: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
11443: 	    $packagetab{$short}=$plain; 
11444: 	}
11445:     }
11446:     close($config);
11447: }
11448: 
11449: # ---------------------------------------------------------- Read loncaparev table
11450: {
11451:     if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
11452:         if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
11453:             while (my $configline=<$config>) {
11454:                 chomp($configline);
11455:                 my ($hostid,$loncaparev)=split(/:/,$configline);
11456:                 $loncaparevs{$hostid}=$loncaparev;
11457:             }
11458:             close($config);
11459:         }
11460:     }
11461: }
11462: 
11463: # ---------------------------------------------------------- Read serverhostID table
11464: {
11465:     if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
11466:         if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
11467:             while (my $configline=<$config>) {
11468:                 chomp($configline);
11469:                 my ($name,$id)=split(/:/,$configline);
11470:                 $serverhomeIDs{$name}=$id;
11471:             }
11472:             close($config);
11473:         }
11474:     }
11475: }
11476: 
11477: {
11478:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
11479:     if (-e $file) {
11480:         my $parser = HTML::LCParser->new($file);
11481:         while (my $token = $parser->get_token()) {
11482:             if ($token->[0] eq 'S') {
11483:                 my $item = $token->[1];
11484:                 my $name = $token->[2]{'name'};
11485:                 my $value = $token->[2]{'value'};
11486:                 if ($item ne '' && $name ne '' && $value ne '') {
11487:                     my $release = $parser->get_text();
11488:                     $release =~ s/(^\s*|\s*$ )//gx;
11489:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
11490:                 }
11491:             }
11492:         }
11493:     }
11494: }
11495: 
11496: # ---------------------------------------------------------- Read managers table
11497: {
11498:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
11499:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
11500:             while (my $configline=<$config>) {
11501:                 chomp($configline);
11502:                 next if ($configline =~ /^\#/);
11503:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
11504:                     $managerstab{$configline} = 1;
11505:                 }
11506:             }
11507:             close($config);
11508:         }
11509:     }
11510: }
11511: 
11512: # ------------- set up temporary directory
11513: {
11514:     $tmpdir = LONCAPA::tempdir();
11515: 
11516: }
11517: 
11518: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
11519: 				'compress_threshold'=> 20_000,
11520:  			        });
11521: 
11522: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
11523: $dumpcount=0;
11524: $locknum=0;
11525: 
11526: &logtouch();
11527: &logthis('<font color="yellow">INFO: Read configuration</font>');
11528: $readit=1;
11529:     {
11530: 	use integer;
11531: 	my $test=(2**32)+1;
11532: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
11533: 	&logthis(" Detected 64bit platform ($_64bit)");
11534:     }
11535: }
11536: }
11537: 
11538: 1;
11539: __END__
11540: 
11541: =pod
11542: 
11543: =head1 NAME
11544: 
11545: Apache::lonnet - Subroutines to ask questions about things in the network.
11546: 
11547: =head1 SYNOPSIS
11548: 
11549: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
11550: 
11551:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
11552: 
11553: Common parameters:
11554: 
11555: =over 4
11556: 
11557: =item *
11558: 
11559: $uname : an internal username (if $cname expecting a course Id specifically)
11560: 
11561: =item *
11562: 
11563: $udom : a domain (if $cdom expecting a course's domain specifically)
11564: 
11565: =item *
11566: 
11567: $symb : a resource instance identifier
11568: 
11569: =item *
11570: 
11571: $namespace : the name of a .db file that contains the data needed or
11572: being set.
11573: 
11574: =back
11575: 
11576: =head1 OVERVIEW
11577: 
11578: lonnet provides subroutines which interact with the
11579: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
11580: about classes, users, and resources.
11581: 
11582: For many of these objects you can also use this to store data about
11583: them or modify them in various ways.
11584: 
11585: =head2 Symbs
11586: 
11587: To identify a specific instance of a resource, LON-CAPA uses symbols
11588: or "symbs"X<symb>. These identifiers are built from the URL of the
11589: map, the resource number of the resource in the map, and the URL of
11590: the resource itself. The latter is somewhat redundant, but might help
11591: if maps change.
11592: 
11593: An example is
11594: 
11595:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
11596: 
11597: The respective map entry is
11598: 
11599:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
11600:   title="Problem 2">
11601:  </resource>
11602: 
11603: Symbs are used by the random number generator, as well as to store and
11604: restore data specific to a certain instance of for example a problem.
11605: 
11606: =head2 Storing And Retrieving Data
11607: 
11608: X<store()>X<cstore()>X<restore()>Three of the most important functions
11609: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
11610: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
11611: is is the non-critical message twin of cstore. These functions are for
11612: handlers to store a perl hash to a user's permanent data space in an
11613: easy manner, and to retrieve it again on another call. It is expected
11614: that a handler would use this once at the beginning to retrieve data,
11615: and then again once at the end to send only the new data back.
11616: 
11617: The data is stored in the user's data directory on the user's
11618: homeserver under the ID of the course.
11619: 
11620: The hash that is returned by restore will have all of the previous
11621: value for all of the elements of the hash.
11622: 
11623: Example:
11624: 
11625:  #creating a hash
11626:  my %hash;
11627:  $hash{'foo'}='bar';
11628: 
11629:  #storing it
11630:  &Apache::lonnet::cstore(\%hash);
11631: 
11632:  #changing a value
11633:  $hash{'foo'}='notbar';
11634: 
11635:  #adding a new value
11636:  $hash{'bar'}='foo';
11637:  &Apache::lonnet::cstore(\%hash);
11638: 
11639:  #retrieving the hash
11640:  my %history=&Apache::lonnet::restore();
11641: 
11642:  #print the hash
11643:  foreach my $key (sort(keys(%history))) {
11644:    print("\%history{$key} = $history{$key}");
11645:  }
11646: 
11647: Will print out:
11648: 
11649:  %history{1:foo} = bar
11650:  %history{1:keys} = foo:timestamp
11651:  %history{1:timestamp} = 990455579
11652:  %history{2:bar} = foo
11653:  %history{2:foo} = notbar
11654:  %history{2:keys} = foo:bar:timestamp
11655:  %history{2:timestamp} = 990455580
11656:  %history{bar} = foo
11657:  %history{foo} = notbar
11658:  %history{timestamp} = 990455580
11659:  %history{version} = 2
11660: 
11661: Note that the special hash entries C<keys>, C<version> and
11662: C<timestamp> were added to the hash. C<version> will be equal to the
11663: total number of versions of the data that have been stored. The
11664: C<timestamp> attribute will be the UNIX time the hash was
11665: stored. C<keys> is available in every historical section to list which
11666: keys were added or changed at a specific historical revision of a
11667: hash.
11668: 
11669: B<Warning>: do not store the hash that restore returns directly. This
11670: will cause a mess since it will restore the historical keys as if the
11671: were new keys. I.E. 1:foo will become 1:1:foo etc.
11672: 
11673: Calling convention:
11674: 
11675:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
11676:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
11677: 
11678: For more detailed information, see lonnet specific documentation.
11679: 
11680: =head1 RETURN MESSAGES
11681: 
11682: =over 4
11683: 
11684: =item * B<con_lost>: unable to contact remote host
11685: 
11686: =item * B<con_delayed>: unable to contact remote host, message will be delivered
11687: when the connection is brought back up
11688: 
11689: =item * B<con_failed>: unable to contact remote host and unable to save message
11690: for later delivery
11691: 
11692: =item * B<error:>: an error a occurred, a description of the error follows the :
11693: 
11694: =item * B<no_such_host>: unable to fund a host associated with the user/domain
11695: that was requested
11696: 
11697: =back
11698: 
11699: =head1 PUBLIC SUBROUTINES
11700: 
11701: =head2 Session Environment Functions
11702: 
11703: =over 4
11704: 
11705: =item * 
11706: X<appenv()>
11707: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
11708: the user envirnoment file, and will be restored for each access this
11709: user makes during this session, also modifies the %env for the current
11710: process. Optional rolesarrayref - if defined contains a reference to an array
11711: of roles which are exempt from the restriction on modifying user.role entries 
11712: in the user's environment.db and in %env.    
11713: 
11714: =item *
11715: X<delenv()>
11716: B<delenv($delthis,$regexp)>: removes all items from the session
11717: environment file that begin with $delthis. If the 
11718: optional second arg - $regexp - is true, $delthis is treated as a 
11719: regular expression, otherwise \Q$delthis\E is used. 
11720: The values are also deleted from the current processes %env.
11721: 
11722: =item * get_env_multiple($name) 
11723: 
11724: gets $name from the %env hash, it seemlessly handles the cases where multiple
11725: values may be defined and end up as an array ref.
11726: 
11727: returns an array of values
11728: 
11729: =back
11730: 
11731: =head2 User Information
11732: 
11733: =over 4
11734: 
11735: =item *
11736: X<queryauthenticate()>
11737: B<queryauthenticate($uname,$udom)>: try to determine user's current 
11738: authentication scheme
11739: 
11740: =item *
11741: X<authenticate()>
11742: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
11743: authenticate user from domain's lib servers (first use the current
11744: one). C<$upass> should be the users password.
11745: $checkdefauth is optional (value is 1 if a check should be made to
11746:    authenticate user using default authentication method, and allow
11747:    account creation if username does not have account in the domain).
11748: $clientcancheckhost is optional (value is 1 if checking whether the
11749:    server can host will occur on the client side in lonauth.pm).   
11750: 
11751: =item *
11752: X<homeserver()>
11753: B<homeserver($uname,$udom)>: find the server which has
11754: the user's directory and files (there must be only one), this caches
11755: the answer, and also caches if there is a borken connection.
11756: 
11757: =item *
11758: X<idget()>
11759: B<idget($udom,@ids)>: find the usernames behind a list of IDs
11760: (IDs are a unique resource in a domain, there must be only 1 ID per
11761: username, and only 1 username per ID in a specific domain) (returns
11762: hash: id=>name,id=>name)
11763: 
11764: =item *
11765: X<idrget()>
11766: B<idrget($udom,@unames)>: find the IDs behind a list of
11767: usernames (returns hash: name=>id,name=>id)
11768: 
11769: =item *
11770: X<idput()>
11771: B<idput($udom,%ids)>: store away a list of names and associated IDs
11772: 
11773: =item *
11774: X<rolesinit()>
11775: B<rolesinit($udom,$username)>: get user privileges.
11776: returns user role, first access and timer interval hashes
11777: 
11778: =item *
11779: X<privileged()>
11780: B<privileged($username,$domain)>: returns a true if user has a
11781: privileged and active role (i.e. su or dc), false otherwise.
11782: 
11783: =item *
11784: X<getsection()>
11785: B<getsection($udom,$uname,$cname)>: finds the section of student in the
11786: course $cname, return section name/number or '' for "not in course"
11787: and '-1' for "no section"
11788: 
11789: =item *
11790: X<userenvironment()>
11791: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
11792: passed in @what from the requested user's environment, returns a hash
11793: 
11794: =item * 
11795: X<userlog_query()>
11796: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
11797: activity.log file. %filters defines filters applied when parsing the
11798: log file. These can be start or end timestamps, or the type of action
11799: - log to look for Login or Logout events, check for Checkin or
11800: Checkout, role for role selection. The response is in the form
11801: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
11802: escaped strings of the action recorded in the activity.log file.
11803: 
11804: =back
11805: 
11806: =head2 User Roles
11807: 
11808: =over 4
11809: 
11810: =item *
11811: 
11812: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
11813:  F: full access
11814:  U,I,K: authentication modes (cxx only)
11815:  '': forbidden
11816:  1: user needs to choose course
11817:  2: browse allowed
11818:  A: passphrase authentication needed
11819: 
11820: =item *
11821: 
11822: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
11823: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
11824: and course level
11825: 
11826: =item *
11827: 
11828: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
11829: (rolesplain.tab); plain text explanation of a user role term.
11830: $type is Course (default) or Community.
11831: If $forcedefault evaluates to true, text returned will be default 
11832: text for $type. Otherwise, if this is a course, the text returned 
11833: will be a custom name for the role (if defined in the course's 
11834: environment).  If no custom name is defined the default is returned.
11835:    
11836: =item *
11837: 
11838: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
11839: All arguments are optional. Returns a hash of a roles, either for
11840: co-author/assistant author roles for a user's Construction Space
11841: (default), or if $context is 'userroles', roles for the user himself,
11842: In the hash, keys are set to colon-separated $uname,$udom,$role, and
11843: (optionally) if $withsec is true, a fourth colon-separated item - $section.
11844: For each key, value is set to colon-separated start and end times for
11845: the role.  If no username and domain are specified, will default to
11846: current user/domain. Types, roles, and roledoms are references to arrays
11847: of role statuses (active, future or previous), roles 
11848: (e.g., cc,in, st etc.) and domains of the roles which can be used
11849: to restrict the list of roles reported. If no array ref is 
11850: provided for types, will default to return only active roles.
11851: 
11852: =back
11853: 
11854: =head2 User Modification
11855: 
11856: =over 4
11857: 
11858: =item *
11859: 
11860: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
11861: user for the level given by URL.  Optional start and end dates (leave empty
11862: string or zero for "no date")
11863: 
11864: =item *
11865: 
11866: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
11867: change a users, password, possible return values are: ok,
11868: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
11869: refused
11870: 
11871: =item *
11872: 
11873: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
11874: 
11875: =item *
11876: 
11877: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
11878:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
11879: 
11880: will update user information (firstname,middlename,lastname,generation,
11881: permanentemail), and if forceid is true, student/employee ID also.
11882: A user's institutional affiliation(s) can also be updated.
11883: User information fields will not be overwritten with empty entries 
11884: unless the field is included in the $candelete array reference.
11885: This array is included when a single user is modified via "Manage Users",
11886: or when Autoupdate.pl is run by cron in a domain.
11887: 
11888: =item *
11889: 
11890: modifystudent
11891: 
11892: modify a student's enrollment and identification information.
11893: The course id is resolved based on the current users environment.  
11894: This means the envoking user must be a course coordinator or otherwise
11895: associated with a course.
11896: 
11897: This call is essentially a wrapper for lonnet::modifyuser and
11898: lonnet::modify_student_enrollment
11899: 
11900: Inputs: 
11901: 
11902: =over 4
11903: 
11904: =item B<$udom> Student's loncapa domain
11905: 
11906: =item B<$uname> Student's loncapa login name
11907: 
11908: =item B<$uid> Student/Employee ID
11909: 
11910: =item B<$umode> Student's authentication mode
11911: 
11912: =item B<$upass> Student's password
11913: 
11914: =item B<$first> Student's first name
11915: 
11916: =item B<$middle> Student's middle name
11917: 
11918: =item B<$last> Student's last name
11919: 
11920: =item B<$gene> Student's generation
11921: 
11922: =item B<$usec> Student's section in course
11923: 
11924: =item B<$end> Unix time of the roles expiration
11925: 
11926: =item B<$start> Unix time of the roles start date
11927: 
11928: =item B<$forceid> If defined, allow $uid to be changed
11929: 
11930: =item B<$desiredhome> server to use as home server for student
11931: 
11932: =item B<$email> Student's permanent e-mail address
11933: 
11934: =item B<$type> Type of enrollment (auto or manual)
11935: 
11936: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
11937: 
11938: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
11939: 
11940: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
11941: 
11942: =item B<$context> role change context (shown in User Management Logs display in a course)
11943: 
11944: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
11945: 
11946: =back
11947: 
11948: =item *
11949: 
11950: modify_student_enrollment
11951: 
11952: Change a students enrollment status in a class.  The environment variable
11953: 'role.request.course' must be defined for this function to proceed.
11954: 
11955: Inputs:
11956: 
11957: =over 4
11958: 
11959: =item $udom, students domain
11960: 
11961: =item $uname, students name
11962: 
11963: =item $uid, students user id
11964: 
11965: =item $first, students first name
11966: 
11967: =item $middle
11968: 
11969: =item $last
11970: 
11971: =item $gene
11972: 
11973: =item $usec
11974: 
11975: =item $end
11976: 
11977: =item $start
11978: 
11979: =item $type
11980: 
11981: =item $locktype
11982: 
11983: =item $cid
11984: 
11985: =item $selfenroll
11986: 
11987: =item $context
11988: 
11989: =back
11990: 
11991: 
11992: =item *
11993: 
11994: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
11995: custom role; give a custom role to a user for the level given by URL.  Specify
11996: name and domain of role author, and role name
11997: 
11998: =item *
11999: 
12000: revokerole($udom,$uname,$url,$role) : revoke a role for url
12001: 
12002: =item *
12003: 
12004: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
12005: 
12006: =back
12007: 
12008: =head2 Course Infomation
12009: 
12010: =over 4
12011: 
12012: =item *
12013: 
12014: coursedescription($courseid,$options) : returns a hash of information about the
12015: specified course id, including all environment settings for the
12016: course, the description of the course will be in the hash under the
12017: key 'description'
12018: 
12019: $options is an optional parameter that if supplied is a hash reference that controls
12020: what how this function works.  It has the following key/values:
12021: 
12022: =over 4
12023: 
12024: =item freshen_cache
12025: 
12026: If defined, and the environment cache for the course is valid, it is 
12027: returned in the returned hash.
12028: 
12029: =item one_time
12030: 
12031: If defined, the last cache time is set to _now_
12032: 
12033: =item user
12034: 
12035: If defined, the supplied username is used instead of the current user.
12036: 
12037: 
12038: =back
12039: 
12040: =item *
12041: 
12042: resdata($name,$domain,$type,@which) : request for current parameter
12043: setting for a specific $type, where $type is either 'course' or 'user',
12044: @what should be a list of parameters to ask about. This routine caches
12045: answers for 5 minutes.
12046: 
12047: =item *
12048: 
12049: get_courseresdata($courseid, $domain) : dump the entire course resource
12050: data base, returning a hash that is keyed by the resource name and has
12051: values that are the resource value.  I believe that the timestamps and
12052: versions are also returned.
12053: 
12054: 
12055: =back
12056: 
12057: =head2 Course Modification
12058: 
12059: =over 4
12060: 
12061: =item *
12062: 
12063: writecoursepref($courseid,%prefs) : write preferences (environment
12064: database) for a course
12065: 
12066: =item *
12067: 
12068: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
12069: 
12070: =item *
12071: 
12072: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
12073: 
12074: =item *
12075: 
12076: is_course($courseid), is_course($cdom, $cnum)
12077: 
12078: Accepts either a combined $courseid (in the form of domain_courseid) or the
12079: two component version $cdom, $cnum. It checks if the specified course exists.
12080: 
12081: Returns:
12082:     undef if the course doesn't exist, otherwise
12083:     in scalar context the combined courseid.
12084:     in list context the two components of the course identifier, domain and 
12085:     courseid.    
12086: 
12087: =back
12088: 
12089: =head2 Resource Subroutines
12090: 
12091: =over 4
12092: 
12093: =item *
12094: 
12095: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
12096: 
12097: =item *
12098: 
12099: repcopy($filename) : subscribes to the requested file, and attempts to
12100: replicate from the owning library server, Might return
12101: 'unavailable', 'not_found', 'forbidden', 'ok', or
12102: 'bad_request', also attempts to grab the metadata for the
12103: resource. Expects the local filesystem pathname
12104: (/home/httpd/html/res/....)
12105: 
12106: =back
12107: 
12108: =head2 Resource Information
12109: 
12110: =over 4
12111: 
12112: =item *
12113: 
12114: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
12115: a vairety of different possible values, $varname should be a request
12116: string, and the other parameters can be used to specify who and what
12117: one is asking about.
12118: 
12119: Possible values for $varname are environment.lastname (or other item
12120: from the envirnment hash), user.name (or someother aspect about the
12121: user), resource.0.maxtries (or some other part and parameter of a
12122: resource)
12123: 
12124: =item *
12125: 
12126: directcondval($number) : get current value of a condition; reads from a state
12127: string
12128: 
12129: =item *
12130: 
12131: condval($condidx) : value of condition index based on state
12132: 
12133: =item *
12134: 
12135: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
12136: resource's metadata, $what should be either a specific key, or either
12137: 'keys' (to get a list of possible keys) or 'packages' to get a list of
12138: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
12139: 
12140: this function automatically caches all requests
12141: 
12142: =item *
12143: 
12144: metadata_query($query,$custom,$customshow) : make a metadata query against the
12145: network of library servers; returns file handle of where SQL and regex results
12146: will be stored for query
12147: 
12148: =item *
12149: 
12150: symbread($filename) : return symbolic list entry (filename argument optional);
12151: returns the data handle
12152: 
12153: =item *
12154: 
12155: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
12156: a possible symb for the URL in $thisfn, and if is an encryypted
12157: resource that the user accessed using /enc/ returns a 1 on success, 0
12158: on failure, user must be in a course, as it assumes the existance of
12159: the course initial hash, and uses $env('request.course.id'}
12160: 
12161: 
12162: =item *
12163: 
12164: symbclean($symb) : removes versions numbers from a symb, returns the
12165: cleaned symb
12166: 
12167: =item *
12168: 
12169: is_on_map($uri) : checks if the $uri is somewhere on the current
12170: course map, user must be in a course for it to work.
12171: 
12172: =item *
12173: 
12174: numval($salt) : return random seed value (addend for rndseed)
12175: 
12176: =item *
12177: 
12178: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
12179: a random seed, all arguments are optional, if they aren't sent it uses the
12180: environment to derive them. Note: if symb isn't sent and it can't get one
12181: from &symbread it will use the current time as its return value
12182: 
12183: =item *
12184: 
12185: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
12186: unfakeable, receipt
12187: 
12188: =item *
12189: 
12190: receipt() : API to ireceipt working off of env values; given out to users
12191: 
12192: =item *
12193: 
12194: countacc($url) : count the number of accesses to a given URL
12195: 
12196: =item *
12197: 
12198: 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
12199: 
12200: =item *
12201: 
12202: 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)
12203: 
12204: =item *
12205: 
12206: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
12207: 
12208: =item *
12209: 
12210: devalidate($symb) : devalidate temporary spreadsheet calculations,
12211: forcing spreadsheet to reevaluate the resource scores next time.
12212: 
12213: =back
12214: 
12215: =head2 Storing/Retreiving Data
12216: 
12217: =over 4
12218: 
12219: =item *
12220: 
12221: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
12222: for this url; hashref needs to be given and should be a \%hashname; the
12223: remaining args aren't required and if they aren't passed or are '' they will
12224: be derived from the env
12225: 
12226: =item *
12227: 
12228: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
12229: uses critical subroutine
12230: 
12231: =item *
12232: 
12233: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
12234: all args are optional
12235: 
12236: =item *
12237: 
12238: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
12239: dumps the complete (or key matching regexp) namespace into a hash
12240: ($udom, $uname, $regexp, $range are optional) for a namespace that is
12241: normally &store()ed into
12242: 
12243: $range should be either an integer '100' (give me the first 100
12244:                                            matching records)
12245:               or be  two integers sperated by a - with no spaces
12246:                  '30-50' (give me the 30th through the 50th matching
12247:                           records)
12248: 
12249: 
12250: =item *
12251: 
12252: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
12253: replaces a &store() version of data with a replacement set of data
12254: for a particular resource in a namespace passed in the $storehash hash 
12255: reference
12256: 
12257: =item *
12258: 
12259: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
12260: works very similar to store/cstore, but all data is stored in a
12261: temporary location and can be reset using tmpreset, $storehash should
12262: be a hash reference, returns nothing on success
12263: 
12264: =item *
12265: 
12266: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
12267: similar to restore, but all data is stored in a temporary location and
12268: can be reset using tmpreset. Returns a hash of values on success,
12269: error string otherwise.
12270: 
12271: =item *
12272: 
12273: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
12274: deltes all keys for $symb form the temporary storage hash.
12275: 
12276: =item *
12277: 
12278: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
12279: reference filled in from namesp ($udom and $uname are optional)
12280: 
12281: =item *
12282: 
12283: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
12284: namesp ($udom and $uname are optional)
12285: 
12286: =item *
12287: 
12288: dump($namespace,$udom,$uname,$regexp,$range) : 
12289: dumps the complete (or key matching regexp) namespace into a hash
12290: ($udom, $uname, $regexp, $range are optional)
12291: 
12292: $range should be either an integer '100' (give me the first 100
12293:                                            matching records)
12294:               or be  two integers sperated by a - with no spaces
12295:                  '30-50' (give me the 30th through the 50th matching
12296:                           records)
12297: =item *
12298: 
12299: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
12300: $store can be a scalar, an array reference, or if the amount to be 
12301: incremented is > 1, a hash reference.
12302: 
12303: ($udom and $uname are optional)
12304: 
12305: =item *
12306: 
12307: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
12308: ($udom and $uname are optional)
12309: 
12310: =item *
12311: 
12312: cput($namespace,$storehash,$udom,$uname) : critical put
12313: ($udom and $uname are optional)
12314: 
12315: =item *
12316: 
12317: newput($namespace,$storehash,$udom,$uname) :
12318: 
12319: Attempts to store the items in the $storehash, but only if they don't
12320: currently exist, if this succeeds you can be certain that you have 
12321: successfully created a new key value pair in the $namespace db.
12322: 
12323: 
12324: Args:
12325:  $namespace: name of database to store values to
12326:  $storehash: hashref to store to the db
12327:  $udom: (optional) domain of user containing the db
12328:  $uname: (optional) name of user caontaining the db
12329: 
12330: Returns:
12331:  'ok' -> succeeded in storing all keys of $storehash
12332:  'key_exists: <key>' -> failed to anything out of $storehash, as at
12333:                         least <key> already existed in the db (other
12334:                         requested keys may also already exist)
12335:  'error: <msg>' -> unable to tie the DB or other error occurred
12336:  'con_lost' -> unable to contact request server
12337:  'refused' -> action was not allowed by remote machine
12338: 
12339: 
12340: =item *
12341: 
12342: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
12343: reference filled in from namesp (encrypts the return communication)
12344: ($udom and $uname are optional)
12345: 
12346: =item *
12347: 
12348: log($udom,$name,$home,$message) : write to permanent log for user; use
12349: critical subroutine
12350: 
12351: =item *
12352: 
12353: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
12354: array reference filled in from namespace found in domain level on either
12355: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
12356: 
12357: =item *
12358: 
12359: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
12360: domain level either on specified domain server ($uhome) or primary domain 
12361: server ($udom and $uhome are optional)
12362: 
12363: =item * 
12364: 
12365: get_domain_defaults($target_domain) : returns hash with defaults for
12366: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
12367: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
12368: or localauth), initial password or a kerberos realm, language (e.g., en-us).
12369: Values are retrieved from cache (if current), or from domain's configuration.db
12370: (if available), or lastly from values in lonTabs/dns_domain,tab, 
12371: or lonTabs/domain.tab. 
12372: 
12373: %domdefaults = &get_auth_defaults($target_domain);
12374: 
12375: =back
12376: 
12377: =head2 Network Status Functions
12378: 
12379: =over 4
12380: 
12381: =item *
12382: 
12383: dirlist() : return directory list based on URI (first arg).
12384: 
12385: Inputs: 1 required, 5 optional.
12386: 
12387: =over
12388: 
12389: =item 
12390: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
12391: 
12392: =item
12393: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
12394: 
12395: =item
12396: $username -  username of user/course to be listed. Extracted from $uri if absent. 
12397: 
12398: =item
12399: $getpropath - boolean: 1 if prepend path using &propath(). 
12400: 
12401: =item
12402: $getuserdir - boolean: 1 if prepend path for "userfiles".
12403: 
12404: =item 
12405: $alternateRoot - path to prepend in place of path from $uri.
12406: 
12407: =back
12408: 
12409: Returns: Array of up to two items.
12410: 
12411: =over
12412: 
12413: a reference to an array of files/subdirectories
12414: 
12415: =over
12416: 
12417: Each element in the array of files/subdirectories is a & separated list of
12418: item name and the result of running stat on the item.  If dirlist was requested
12419: for a file instead of a directory, the item name will be ''. For a directory 
12420: listing, if the item is a metadata file, the element will end &N&M 
12421: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
12422: default copyright set (1).  
12423: 
12424: =back
12425: 
12426: a scalar containing error condition (if encountered).
12427: 
12428: =over
12429: 
12430: =item 
12431: no_host (no homeserver identified for $username:$domain).
12432: 
12433: =item 
12434: no_such_host (server contacted for listing not identified as valid host).
12435: 
12436: =item 
12437: con_lost (connection to remote server failed).
12438: 
12439: =item 
12440: refused (invalid $username:$domain received on lond side).
12441: 
12442: =item 
12443: no_such_dir (directory at specified path on lond side does not exist). 
12444: 
12445: =item 
12446: empty (directory at specified path on lond side is empty).
12447: 
12448: =over
12449: 
12450: This is currently not encountered because the &ls3, &ls2, 
12451: &ls (_handler) routines on the lond side do not filter out
12452: . and .. from a directory listing. 
12453: 
12454: =back
12455: 
12456: =back
12457: 
12458: =back
12459: 
12460: =item *
12461: 
12462: spareserver() : find server with least workload from spare.tab
12463: 
12464: 
12465: =item *
12466: 
12467: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
12468: if there is no corresponding loncapa host.
12469: 
12470: =back
12471: 
12472: 
12473: =head2 Apache Request
12474: 
12475: =over 4
12476: 
12477: =item *
12478: 
12479: ssi($url,%hash) : server side include, does a complete request cycle on url to
12480: localhost, posts hash
12481: 
12482: =back
12483: 
12484: =head2 Data to String to Data
12485: 
12486: =over 4
12487: 
12488: =item *
12489: 
12490: hash2str(%hash) : convert a hash into a string complete with escaping and '='
12491: and '&' separators, supports elements that are arrayrefs and hashrefs
12492: 
12493: =item *
12494: 
12495: hashref2str($hashref) : convert a hashref into a string complete with
12496: escaping and '=' and '&' separators, supports elements that are
12497: arrayrefs and hashrefs
12498: 
12499: =item *
12500: 
12501: arrayref2str($arrayref) : convert an arrayref into a string complete
12502: with escaping and '&' separators, supports elements that are arrayrefs
12503: and hashrefs
12504: 
12505: =item *
12506: 
12507: str2hash($string) : convert string to hash using unescaping and
12508: splitting on '=' and '&', supports elements that are arrayrefs and
12509: hashrefs
12510: 
12511: =item *
12512: 
12513: str2array($string) : convert string to hash using unescaping and
12514: splitting on '&', supports elements that are arrayrefs and hashrefs
12515: 
12516: =back
12517: 
12518: =head2 Logging Routines
12519: 
12520: 
12521: These routines allow one to make log messages in the lonnet.log and
12522: lonnet.perm logfiles.
12523: 
12524: =over 4
12525: 
12526: =item *
12527: 
12528: logtouch() : make sure the logfile, lonnet.log, exists
12529: 
12530: =item *
12531: 
12532: logthis() : append message to the normal lonnet.log file, it gets
12533: preiodically rolled over and deleted.
12534: 
12535: =item *
12536: 
12537: logperm() : append a permanent message to lonnet.perm.log, this log
12538: file never gets deleted by any automated portion of the system, only
12539: messages of critical importance should go in here.
12540: 
12541: 
12542: =back
12543: 
12544: =head2 General File Helper Routines
12545: 
12546: =over 4
12547: 
12548: =item *
12549: 
12550: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
12551: (a) files in /uploaded
12552:   (i) If a local copy of the file exists - 
12553:       compares modification date of local copy with last-modified date for 
12554:       definitive version stored on home server for course. If local copy is 
12555:       stale, requests a new version from the home server and stores it. 
12556:       If the original has been removed from the home server, then local copy 
12557:       is unlinked.
12558:   (ii) If local copy does not exist -
12559:       requests the file from the home server and stores it. 
12560:   
12561:   If $caller is 'uploadrep':  
12562:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
12563:     for request for files originally uploaded via DOCS. 
12564:      - returns 'ok' if fresh local copy now available, -1 otherwise.
12565:   
12566:   Otherwise:
12567:      This indicates a call from the content generation phase of the request.
12568:      -  returns the entire contents of the file or -1.
12569:      
12570: (b) files in /res
12571:    - returns the entire contents of a file or -1; 
12572:    it properly subscribes to and replicates the file if neccessary.
12573: 
12574: 
12575: =item *
12576: 
12577: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
12578:                   reference
12579: 
12580: returns either a stat() list of data about the file or an empty list
12581: if the file doesn't exist or couldn't find out about it (connection
12582: problems or user unknown)
12583: 
12584: =item *
12585: 
12586: filelocation($dir,$file) : returns file system location of a file
12587: based on URI; meant to be "fairly clean" absolute reference, $dir is a
12588: directory that relative $file lookups are to looked in ($dir of /a/dir
12589: and a file of ../bob will become /a/bob)
12590: 
12591: =item *
12592: 
12593: hreflocation($dir,$file) : returns file system location or a URL; same as
12594: filelocation except for hrefs
12595: 
12596: =item *
12597: 
12598: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
12599: 
12600: =back
12601: 
12602: =head2 Usererfile file routines (/uploaded*)
12603: 
12604: =over 4
12605: 
12606: =item *
12607: 
12608: userfileupload(): main rotine for putting a file in a user or course's
12609:                   filespace, arguments are,
12610: 
12611:  formname - required - this is the name of the element in $env where the
12612:            filename, and the contents of the file to create/modifed exist
12613:            the filename is in $env{'form.'.$formname.'.filename'} and the
12614:            contents of the file is located in $env{'form.'.$formname}
12615:  context - if coursedoc, store the file in the course of the active role
12616:              of the current user; 
12617:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
12618:            if 'canceloverwrite': delete file in tmp/overwrites directory
12619:  subdir - required - subdirectory to put the file in under ../userfiles/
12620:          if undefined, it will be placed in "unknown"
12621: 
12622:  (This routine calls clean_filename() to remove any dangerous
12623:  characters from the filename, and then calls finuserfileupload() to
12624:  complete the transaction)
12625: 
12626:  returns either the url of the uploaded file (/uploaded/....) if successful
12627:  and /adm/notfound.html if unsuccessful
12628: 
12629: =item *
12630: 
12631: clean_filename(): routine for cleaing a filename up for storage in
12632:                  userfile space, argument is:
12633: 
12634:  filename - proposed filename
12635: 
12636: returns: the new clean filename
12637: 
12638: =item *
12639: 
12640: finishuserfileupload(): routine that creates and sends the file to
12641: userspace, probably shouldn't be called directly
12642: 
12643:   docuname: username or courseid of destination for the file
12644:   docudom: domain of user/course of destination for the file
12645:   formname: same as for userfileupload()
12646:   fname: filename (including subdirectories) for the file
12647:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
12648:   allfiles: reference to hash used to store objects found by parser
12649:   codebase: reference to hash used for codebases of java objects found by parser
12650:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
12651:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
12652:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
12653:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
12654:   context: if 'overwrite', will move the uploaded file from its temporary location to
12655:             userfiles to facilitate overwriting a previously uploaded file with same name.
12656:   mimetype: reference to scalar to accommodate mime type determined
12657:             from File::MMagic if $parser = parse.
12658: 
12659:  returns either the url of the uploaded file (/uploaded/....) if successful
12660:  and /adm/notfound.html if unsuccessful (or an error message if context 
12661:  was 'overwrite').
12662:  
12663: 
12664: =item *
12665: 
12666: renameuserfile(): renames an existing userfile to a new name
12667: 
12668:   Args:
12669:    docuname: username or courseid of destination for the file
12670:    docudom: domain of user/course of destination for the file
12671:    old: current file name (including any subdirs under userfiles)
12672:    new: desired file name (including any subdirs under userfiles)
12673: 
12674: =item *
12675: 
12676: mkdiruserfile(): creates a directory is a userfiles dir
12677: 
12678:   Args:
12679:    docuname: username or courseid of destination for the file
12680:    docudom: domain of user/course of destination for the file
12681:    dir: dir to create (including any subdirs under userfiles)
12682: 
12683: =item *
12684: 
12685: removeuserfile(): removes a file that exists in userfiles
12686: 
12687:   Args:
12688:    docuname: username or courseid of destination for the file
12689:    docudom: domain of user/course of destination for the file
12690:    fname: filname to delete (including any subdirs under userfiles)
12691: 
12692: =item *
12693: 
12694: removeuploadedurl(): convience function for removeuserfile()
12695: 
12696:   Args:
12697:    url:  a full /uploaded/... url to delete
12698: 
12699: =item * 
12700: 
12701: get_portfile_permissions():
12702:   Args:
12703:     domain: domain of user or course contain the portfolio files
12704:     user: name of user or num of course contain the portfolio files
12705:   Returns:
12706:     hashref of a dump of the proper file_permissions.db
12707:    
12708: 
12709: =item * 
12710: 
12711: get_access_controls():
12712: 
12713: Args:
12714:   current_permissions: the hash ref returned from get_portfile_permissions()
12715:   group: (optional) the group you want the files associated with
12716:   file: (optional) the file you want access info on
12717: 
12718: Returns:
12719:     a hash (keys are file names) of hashes containing
12720:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
12721:         values are XML containing access control settings (see below) 
12722: 
12723: Internal notes:
12724: 
12725:  access controls are stored in file_permissions.db as key=value pairs.
12726:     key -> path to file/file_name\0uniqueID:scope_end_start
12727:         where scope -> public,guest,course,group,domains or users.
12728:               end -> UNIX time for end of access (0 -> no end date)
12729:               start -> UNIX time for start of access
12730: 
12731:     value -> XML description of access control
12732:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
12733:             <start></start>
12734:             <end></end>
12735: 
12736:             <password></password>  for scope type = guest
12737: 
12738:             <domain></domain>     for scope type = course or group
12739:             <number></number>
12740:             <roles id="">
12741:              <role></role>
12742:              <access></access>
12743:              <section></section>
12744:              <group></group>
12745:             </roles>
12746: 
12747:             <dom></dom>         for scope type = domains
12748: 
12749:             <users>             for scope type = users
12750:              <user>
12751:               <uname></uname>
12752:               <udom></udom>
12753:              </user>
12754:             </users>
12755:            </scope> 
12756:               
12757:  Access data is also aggregated for each file in an additional key=value pair:
12758:  key -> path to file/file_name\0accesscontrol 
12759:  value -> reference to hash
12760:           hash contains key = value pairs
12761:           where key = uniqueID:scope_end_start
12762:                 value = UNIX time record was last updated
12763: 
12764:           Used to improve speed of look-ups of access controls for each file.  
12765:  
12766:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
12767: 
12768: modify_access_controls():
12769: 
12770: Modifies access controls for a portfolio file
12771: Args
12772: 1. file name
12773: 2. reference to hash of required changes,
12774: 3. domain
12775: 4. username
12776:   where domain,username are the domain of the portfolio owner 
12777:   (either a user or a course) 
12778: 
12779: Returns:
12780: 1. result of additions or updates ('ok' or 'error', with error message). 
12781: 2. result of deletions ('ok' or 'error', with error message).
12782: 3. reference to hash of any new or updated access controls.
12783: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
12784:    key = integer (inbound ID)
12785:    value = uniqueID  
12786: 
12787: =back
12788: 
12789: =head2 HTTP Helper Routines
12790: 
12791: =over 4
12792: 
12793: =item *
12794: 
12795: escape() : unpack non-word characters into CGI-compatible hex codes
12796: 
12797: =item *
12798: 
12799: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
12800: 
12801: =back
12802: 
12803: =head1 PRIVATE SUBROUTINES
12804: 
12805: =head2 Underlying communication routines (Shouldn't call)
12806: 
12807: =over 4
12808: 
12809: =item *
12810: 
12811: subreply() : tries to pass a message to lonc, returns con_lost if incapable
12812: 
12813: =item *
12814: 
12815: reply() : uses subreply to send a message to remote machine, logs all failures
12816: 
12817: =item *
12818: 
12819: critical() : passes a critical message to another server; if cannot
12820: get through then place message in connection buffer directory and
12821: returns con_delayed, if incapable of saving message, returns
12822: con_failed
12823: 
12824: =item *
12825: 
12826: reconlonc() : tries to reconnect lonc client processes.
12827: 
12828: =back
12829: 
12830: =head2 Resource Access Logging
12831: 
12832: =over 4
12833: 
12834: =item *
12835: 
12836: flushcourselogs() : flush (save) buffer logs and access logs
12837: 
12838: =item *
12839: 
12840: courselog($what) : save message for course in hash
12841: 
12842: =item *
12843: 
12844: courseacclog($what) : save message for course using &courselog().  Perform
12845: special processing for specific resource types (problems, exams, quizzes, etc).
12846: 
12847: =item *
12848: 
12849: goodbye() : flush course logs and log shutting down; it is called in srm.conf
12850: as a PerlChildExitHandler
12851: 
12852: =back
12853: 
12854: =head2 Other
12855: 
12856: =over 4
12857: 
12858: =item *
12859: 
12860: symblist($mapname,%newhash) : update symbolic storage links
12861: 
12862: =back
12863: 
12864: =cut
12865: 

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