File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1145: download - view: text, annotated - select for diffs
Wed Nov 9 13:14:20 2011 UTC (12 years, 7 months ago) by bisitz
Branches: MAIN
CVS tags: HEAD
Remove remains of remote control. "textual_remote_display" switch doesn't exist anymore.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1145 2011/11/09 13:14:20 bisitz Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: ###
   29: 
   30: =pod
   31: 
   32: =head1 NAME
   33: 
   34: Apache::lonnet.pm
   35: 
   36: =head1 SYNOPSIS
   37: 
   38: This file is an interface to the lonc processes of
   39: the LON-CAPA network as well as set of elaborated functions for handling information
   40: necessary for navigating through a given cluster of LON-CAPA machines within a
   41: domain. There are over 40 specialized functions in this module which handle the
   42: reading and transmission of metadata, user information (ids, names, environments, roles,
   43: logs), file information (storage, reading, directories, extensions, replication, embedded
   44: styles and descriptors), educational resources (course descriptions, section names and
   45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
   46: and from more descriptive phrases or explanations.
   47: 
   48: This is part of the LearningOnline Network with CAPA project
   49: described at http://www.lon-capa.org.
   50: 
   51: =head1 Package Variables
   52: 
   53: These are largely undocumented, so if you decipher one please note it here.
   54: 
   55: =over 4
   56: 
   57: =item $processmarker
   58: 
   59: Contains the time this process was started and this servers host id.
   60: 
   61: =item $dumpcount
   62: 
   63: Counts the number of times a message log flush has been attempted (regardless
   64: of success) by this process.  Used as part of the filename when messages are
   65: delayed.
   66: 
   67: =back
   68: 
   69: =cut
   70: 
   71: package Apache::lonnet;
   72: 
   73: use strict;
   74: use LWP::UserAgent();
   75: use HTTP::Date;
   76: use Image::Magick;
   77: 
   78: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
   79:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
   80:             %managerstab);
   81: 
   82: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
   83:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
   84:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
   85:     %courseownerbuf, %coursetypebuf,$locknum);
   86: 
   87: use IO::Socket;
   88: use GDBM_File;
   89: use HTML::LCParser;
   90: use Fcntl qw(:flock);
   91: use Storable qw(thaw nfreeze);
   92: use Time::HiRes qw( gettimeofday tv_interval );
   93: use Cache::Memcached;
   94: use Digest::MD5;
   95: use Math::Random;
   96: use File::MMagic;
   97: use LONCAPA qw(:DEFAULT :match);
   98: use LONCAPA::Configuration;
   99: 
  100: use File::Copy;
  101: 
  102: my $readit;
  103: my $max_connection_retries = 10;     # Or some such value.
  104: 
  105: require Exporter;
  106: 
  107: our @ISA = qw (Exporter);
  108: our @EXPORT = qw(%env);
  109: 
  110: 
  111: # --------------------------------------------------------------------- Logging
  112: {
  113:     my $logid;
  114:     sub instructor_log {
  115: 	my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
  116:         if (($cnum eq '') || ($cdom eq '')) {
  117:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  118:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  119:         }
  120: 	$logid++;
  121:         my $now = time();
  122: 	my $id=$now.'00000'.$$.'00000'.$logid;
  123: 	return &Apache::lonnet::put('nohist_'.$hash_name,
  124: 				    { $id => {
  125: 					'exe_uname' => $env{'user.name'},
  126: 					'exe_udom'  => $env{'user.domain'},
  127: 					'exe_time'  => $now,
  128: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
  129: 					'delflag'   => $delflag,
  130: 					'logentry'  => $storehash,
  131: 					'uname'     => $uname,
  132: 					'udom'      => $udom,
  133: 				    }
  134: 				  },$cdom,$cnum);
  135:     }
  136: }
  137: 
  138: sub logtouch {
  139:     my $execdir=$perlvar{'lonDaemons'};
  140:     unless (-e "$execdir/logs/lonnet.log") {	
  141: 	open(my $fh,">>$execdir/logs/lonnet.log");
  142: 	close $fh;
  143:     }
  144:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  145:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  146: }
  147: 
  148: sub logthis {
  149:     my $message=shift;
  150:     my $execdir=$perlvar{'lonDaemons'};
  151:     my $now=time;
  152:     my $local=localtime($now);
  153:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
  154: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
  155: 	print $fh $logstring;
  156: 	close($fh);
  157:     }
  158:     return 1;
  159: }
  160: 
  161: sub logperm {
  162:     my $message=shift;
  163:     my $execdir=$perlvar{'lonDaemons'};
  164:     my $now=time;
  165:     my $local=localtime($now);
  166:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
  167: 	print $fh "$now:$message:$local\n";
  168: 	close($fh);
  169:     }
  170:     return 1;
  171: }
  172: 
  173: sub create_connection {
  174:     my ($hostname,$lonid) = @_;
  175:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  176: 				     Type    => SOCK_STREAM,
  177: 				     Timeout => 10);
  178:     return 0 if (!$client);
  179:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
  180:     my $result = <$client>;
  181:     chomp($result);
  182:     return 1 if ($result eq 'done');
  183:     return 0;
  184: }
  185: 
  186: sub get_server_timezone {
  187:     my ($cnum,$cdom) = @_;
  188:     my $home=&homeserver($cnum,$cdom);
  189:     if ($home ne 'no_host') {
  190:         my $cachetime = 24*3600;
  191:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
  192:         if (defined($cached)) {
  193:             return $timezone;
  194:         } else {
  195:             my $timezone = &reply('servertimezone',$home);
  196:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
  197:         }
  198:     }
  199: }
  200: 
  201: sub get_server_distarch {
  202:     my ($lonhost,$ignore_cache) = @_;
  203:     if (defined($lonhost)) {
  204:         if (!defined(&hostname($lonhost))) {
  205:             return;
  206:         }
  207:         my $cachetime = 12*3600;
  208:         if (!$ignore_cache) {
  209:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
  210:             if (defined($cached)) {
  211:                 return $distarch;
  212:             }
  213:         }
  214:         my $rep = &reply('serverdistarch',$lonhost);
  215:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
  216:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
  217:                 $rep eq '') {
  218:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
  219:         }
  220:     }
  221:     return;
  222: }
  223: 
  224: sub get_server_loncaparev {
  225:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
  226:     if (defined($lonhost)) {
  227:         if (!defined(&hostname($lonhost))) {
  228:             undef($lonhost);
  229:         }
  230:     }
  231:     if (!defined($lonhost)) {
  232:         if (defined(&domain($dom,'primary'))) {
  233:             $lonhost=&domain($dom,'primary');
  234:             if ($lonhost eq 'no_host') {
  235:                 undef($lonhost);
  236:             }
  237:         }
  238:     }
  239:     if (defined($lonhost)) {
  240:         my $cachetime = 12*3600;
  241:         if (!$ignore_cache) {
  242:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
  243:             if (defined($cached)) {
  244:                 return $loncaparev;
  245:             }
  246:         }
  247:         my ($answer,$loncaparev);
  248:         my @ids=&current_machine_ids();
  249:         if (grep(/^\Q$lonhost\E$/,@ids)) {
  250:             $answer = $perlvar{'lonVersion'};
  251:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  252:                 $loncaparev = $1;
  253:             }
  254:         } else {
  255:             $answer = &reply('serverloncaparev',$lonhost);
  256:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
  257:                 if ($caller eq 'loncron') {
  258:                     my $ua=new LWP::UserAgent;
  259:                     $ua->timeout(4);
  260:                     my $protocol = $protocol{$lonhost};
  261:                     $protocol = 'http' if ($protocol ne 'https');
  262:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
  263:                     my $request=new HTTP::Request('GET',$url);
  264:                     my $response=$ua->request($request);
  265:                     unless ($response->is_error()) {
  266:                         my $content = $response->content;
  267:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
  268:                             $loncaparev = $1;
  269:                         }
  270:                     }
  271:                 } else {
  272:                     $loncaparev = $loncaparevs{$lonhost};
  273:                 }
  274:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  275:                 $loncaparev = $1;
  276:             }
  277:         }
  278:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
  279:     }
  280: }
  281: 
  282: sub get_server_homeID {
  283:     my ($hostname,$ignore_cache,$caller) = @_;
  284:     unless ($ignore_cache) {
  285:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
  286:         if (defined($cached)) {
  287:             return $serverhomeID;
  288:         }
  289:     }
  290:     my $cachetime = 12*3600;
  291:     my $serverhomeID;
  292:     if ($caller eq 'loncron') { 
  293:         my @machine_ids = &machine_ids($hostname);
  294:         foreach my $id (@machine_ids) {
  295:             my $response = &reply('serverhomeID',$id);
  296:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
  297:                 $serverhomeID = $response;
  298:                 last;
  299:             }
  300:         }
  301:         if ($serverhomeID eq '') {
  302:             $serverhomeID = $machine_ids[-1];
  303:         }
  304:     } else {
  305:         $serverhomeID = $serverhomeIDs{$hostname};
  306:     }
  307:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
  308: }
  309: 
  310: sub get_remote_globals {
  311:     my ($lonhost,$whathash,$ignore_cache) = @_;
  312:     my ($result,%returnhash,%whatneeded);
  313:     if (ref($whathash) eq 'HASH') {
  314:         foreach my $what (sort(keys(%{$whathash}))) {
  315:             my $hashid = $lonhost.'-'.$what;
  316:             my ($response,$cached);
  317:             unless ($ignore_cache) {
  318:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
  319:             }
  320:             if (defined($cached)) {
  321:                 $returnhash{$what} = $response;
  322:             } else {
  323:                 $whatneeded{$what} = 1;
  324:             }
  325:         }
  326:         if (keys(%whatneeded) == 0) {
  327:             $result = 'ok';
  328:         } else {
  329:             my $requested = &freeze_escape(\%whatneeded);
  330:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
  331:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  332:                 ($rep eq 'unknown_cmd')) {
  333:                 $result = $rep;
  334:             } else {
  335:                 $result = 'ok';
  336:                 my @pairs=split(/\&/,$rep);
  337:                 foreach my $item (@pairs) {
  338:                     my ($key,$value)=split(/=/,$item,2);
  339:                     my $what = &unescape($key);
  340:                     my $hashid = $lonhost.'-'.$what;
  341:                     $returnhash{$what}=&thaw_unescape($value);
  342:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
  343:                 }
  344:             }
  345:         }
  346:     }
  347:     return ($result,\%returnhash);
  348: }
  349: 
  350: sub remote_devalidate_cache {
  351:     my ($lonhost,$name,$id) = @_;
  352:     my $response = &reply('devalidatecache:'.&escape($name).':'.&escape($id),$lonhost);
  353:     return $response;
  354: }
  355: 
  356: # -------------------------------------------------- Non-critical communication
  357: sub subreply {
  358:     my ($cmd,$server)=@_;
  359:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  360:     #
  361:     #  With loncnew process trimming, there's a timing hole between lonc server
  362:     #  process exit and the master server picking up the listen on the AF_UNIX
  363:     #  socket.  In that time interval, a lock file will exist:
  364: 
  365:     my $lockfile=$peerfile.".lock";
  366:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  367: 	sleep(1);
  368:     }
  369:     # At this point, either a loncnew parent is listening or an old lonc
  370:     # or loncnew child is listening so we can connect or everything's dead.
  371:     #
  372:     #   We'll give the connection a few tries before abandoning it.  If
  373:     #   connection is not possible, we'll con_lost back to the client.
  374:     #   
  375:     my $client;
  376:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  377: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  378: 				      Type    => SOCK_STREAM,
  379: 				      Timeout => 10);
  380: 	if ($client) {
  381: 	    last;		# Connected!
  382: 	} else {
  383: 	    &create_connection(&hostname($server),$server);
  384: 	}
  385:         sleep(1);		# Try again later if failed connection.
  386:     }
  387:     my $answer;
  388:     if ($client) {
  389: 	print $client "sethost:$server:$cmd\n";
  390: 	$answer=<$client>;
  391: 	if (!$answer) { $answer="con_lost"; }
  392: 	chomp($answer);
  393:     } else {
  394: 	$answer = 'con_lost';	# Failed connection.
  395:     }
  396:     return $answer;
  397: }
  398: 
  399: sub reply {
  400:     my ($cmd,$server)=@_;
  401:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  402:     my $answer=subreply($cmd,$server);
  403:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  404:        &logthis("<font color=\"blue\">WARNING:".
  405:                 " $cmd to $server returned $answer</font>");
  406:     }
  407:     return $answer;
  408: }
  409: 
  410: # ----------------------------------------------------------- Send USR1 to lonc
  411: 
  412: sub reconlonc {
  413:     my ($lonid) = @_;
  414:     my $hostname = &hostname($lonid);
  415:     if ($lonid) {
  416: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  417: 	if ($hostname && -e $peerfile) {
  418: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  419: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  420: 					     Type    => SOCK_STREAM,
  421: 					     Timeout => 10);
  422: 	    if ($client) {
  423: 		print $client ("reset_retries\n");
  424: 		my $answer=<$client>;
  425: 		#reset just this one.
  426: 	    }
  427: 	}
  428: 	return;
  429:     }
  430: 
  431:     &logthis("Trying to reconnect lonc");
  432:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  433:     if (open(my $fh,"<$loncfile")) {
  434: 	my $loncpid=<$fh>;
  435:         chomp($loncpid);
  436:         if (kill 0 => $loncpid) {
  437: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  438:             kill USR1 => $loncpid;
  439:             sleep 1;
  440:          } else {
  441: 	    &logthis(
  442:                "<font color=\"blue\">WARNING:".
  443:                " lonc at pid $loncpid not responding, giving up</font>");
  444:         }
  445:     } else {
  446: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  447:     }
  448: }
  449: 
  450: # ------------------------------------------------------ Critical communication
  451: 
  452: sub critical {
  453:     my ($cmd,$server)=@_;
  454:     unless (&hostname($server)) {
  455:         &logthis("<font color=\"blue\">WARNING:".
  456:                " Critical message to unknown server ($server)</font>");
  457:         return 'no_such_host';
  458:     }
  459:     my $answer=reply($cmd,$server);
  460:     if ($answer eq 'con_lost') {
  461: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
  462: 	my $answer=reply($cmd,$server);
  463:         if ($answer eq 'con_lost') {
  464:             my $now=time;
  465:             my $middlename=$cmd;
  466:             $middlename=substr($middlename,0,16);
  467:             $middlename=~s/\W//g;
  468:             my $dfilename=
  469:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  470:             $dumpcount++;
  471:             {
  472: 		my $dfh;
  473: 		if (open($dfh,">$dfilename")) {
  474: 		    print $dfh "$cmd\n"; 
  475: 		    close($dfh);
  476: 		}
  477:             }
  478:             sleep 2;
  479:             my $wcmd='';
  480:             {
  481: 		my $dfh;
  482: 		if (open($dfh,"<$dfilename")) {
  483: 		    $wcmd=<$dfh>; 
  484: 		    close($dfh);
  485: 		}
  486:             }
  487:             chomp($wcmd);
  488:             if ($wcmd eq $cmd) {
  489: 		&logthis("<font color=\"blue\">WARNING: ".
  490:                          "Connection buffer $dfilename: $cmd</font>");
  491:                 &logperm("D:$server:$cmd");
  492: 	        return 'con_delayed';
  493:             } else {
  494:                 &logthis("<font color=\"red\">CRITICAL:"
  495:                         ." Critical connection failed: $server $cmd</font>");
  496:                 &logperm("F:$server:$cmd");
  497:                 return 'con_failed';
  498:             }
  499:         }
  500:     }
  501:     return $answer;
  502: }
  503: 
  504: # ------------------------------------------- check if return value is an error
  505: 
  506: sub error {
  507:     my ($result) = @_;
  508:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  509: 	if ($2 == 2) { return undef; }
  510: 	return $1;
  511:     }
  512:     return undef;
  513: }
  514: 
  515: sub convert_and_load_session_env {
  516:     my ($lonidsdir,$handle)=@_;
  517:     my @profile;
  518:     {
  519: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  520: 	if (!$opened) {
  521: 	    return 0;
  522: 	}
  523: 	flock($idf,LOCK_SH);
  524: 	@profile=<$idf>;
  525: 	close($idf);
  526:     }
  527:     my %temp_env;
  528:     foreach my $line (@profile) {
  529: 	if ($line !~ m/=/) {
  530: 	    return 0;
  531: 	}
  532: 	chomp($line);
  533: 	my ($envname,$envvalue)=split(/=/,$line,2);
  534: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  535:     }
  536:     unlink("$lonidsdir/$handle.id");
  537:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  538: 	    0640)) {
  539: 	%disk_env = %temp_env;
  540: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  541: 	untie(%disk_env);
  542:     }
  543:     return 1;
  544: }
  545: 
  546: # ------------------------------------------- Transfer profile into environment
  547: my $env_loaded;
  548: sub transfer_profile_to_env {
  549:     my ($lonidsdir,$handle,$force_transfer) = @_;
  550:     if (!$force_transfer && $env_loaded) { return; } 
  551: 
  552:     if (!defined($lonidsdir)) {
  553: 	$lonidsdir = $perlvar{'lonIDsDir'};
  554:     }
  555:     if (!defined($handle)) {
  556:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  557:     }
  558: 
  559:     my $convert;
  560:     {
  561:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  562: 	if (!$opened) {
  563: 	    return;
  564: 	}
  565: 	flock($idf,LOCK_SH);
  566: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  567: 		&GDBM_READER(),0640)) {
  568: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  569: 	    untie(%disk_env);
  570: 	} else {
  571: 	    $convert = 1;
  572: 	}
  573:     }
  574:     if ($convert) {
  575: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  576: 	    &logthis("Failed to load session, or convert session.");
  577: 	}
  578:     }
  579: 
  580:     my %remove;
  581:     while ( my $envname = each(%env) ) {
  582:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  583:             if ($time < time-300) {
  584:                 $remove{$key}++;
  585:             }
  586:         }
  587:     }
  588: 
  589:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  590:     $env_loaded=1;
  591:     foreach my $expired_key (keys(%remove)) {
  592:         &delenv($expired_key);
  593:     }
  594: }
  595: 
  596: # ---------------------------------------------------- Check for valid session 
  597: sub check_for_valid_session {
  598:     my ($r) = @_;
  599:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  600:     my $lonid=$cookies{'lonID'};
  601:     return undef if (!$lonid);
  602: 
  603:     my $handle=&LONCAPA::clean_handle($lonid->value);
  604:     my $lonidsdir=$r->dir_config('lonIDsDir');
  605:     return undef if (!-e "$lonidsdir/$handle.id");
  606: 
  607:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  608:     return undef if (!$opened);
  609: 
  610:     flock($idf,LOCK_SH);
  611:     my %disk_env;
  612:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  613: 	    &GDBM_READER(),0640)) {
  614: 	return undef;	
  615:     }
  616: 
  617:     if (!defined($disk_env{'user.name'})
  618: 	|| !defined($disk_env{'user.domain'})) {
  619: 	return undef;
  620:     }
  621:     return $handle;
  622: }
  623: 
  624: sub timed_flock {
  625:     my ($file,$lock_type) = @_;
  626:     my $failed=0;
  627:     eval {
  628: 	local $SIG{__DIE__}='DEFAULT';
  629: 	local $SIG{ALRM}=sub {
  630: 	    $failed=1;
  631: 	    die("failed lock");
  632: 	};
  633: 	alarm(13);
  634: 	flock($file,$lock_type);
  635: 	alarm(0);
  636:     };
  637:     if ($failed) {
  638: 	return undef;
  639:     } else {
  640: 	return 1;
  641:     }
  642: }
  643: 
  644: # ---------------------------------------------------------- Append Environment
  645: 
  646: sub appenv {
  647:     my ($newenv,$roles) = @_;
  648:     if (ref($newenv) eq 'HASH') {
  649:         foreach my $key (keys(%{$newenv})) {
  650:             my $refused = 0;
  651: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  652:                 $refused = 1;
  653:                 if (ref($roles) eq 'ARRAY') {
  654:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
  655:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  656:                         $refused = 0;
  657:                     }
  658:                 }
  659:             }
  660:             if ($refused) {
  661:                 &logthis("<font color=\"blue\">WARNING: ".
  662:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  663:                          .'</font>');
  664: 	        delete($newenv->{$key});
  665:             } else {
  666:                 $env{$key}=$newenv->{$key};
  667:             }
  668:         }
  669:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
  670:         if ($opened
  671: 	    && &timed_flock($env_file,LOCK_EX)
  672: 	    &&
  673: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  674: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  675: 	    while (my ($key,$value) = each(%{$newenv})) {
  676: 	        $disk_env{$key} = $value;
  677: 	    }
  678: 	    untie(%disk_env);
  679:         }
  680:     }
  681:     return 'ok';
  682: }
  683: # ----------------------------------------------------- Delete from Environment
  684: 
  685: sub delenv {
  686:     my ($delthis,$regexp,$roles) = @_;
  687:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
  688:         my $refused = 1;
  689:         if (ref($roles) eq 'ARRAY') {
  690:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
  691:             if (grep(/^\Q$role\E$/,@{$roles})) {
  692:                 $refused = 0;
  693:             }
  694:         }
  695:         if ($refused) {
  696:             &logthis("<font color=\"blue\">WARNING: ".
  697:                      "Attempt to delete from environment ".$delthis);
  698:             return 'error';
  699:         }
  700:     }
  701:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  702:     if ($opened
  703: 	&& &timed_flock($env_file,LOCK_EX)
  704: 	&&
  705: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  706: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  707: 	foreach my $key (keys(%disk_env)) {
  708: 	    if ($regexp) {
  709:                 if ($key=~/^$delthis/) {
  710:                     delete($env{$key});
  711:                     delete($disk_env{$key});
  712:                 } 
  713:             } else {
  714:                 if ($key=~/^\Q$delthis\E/) {
  715: 		    delete($env{$key});
  716: 		    delete($disk_env{$key});
  717: 	        }
  718:             }
  719: 	}
  720: 	untie(%disk_env);
  721:     }
  722:     return 'ok';
  723: }
  724: 
  725: sub get_env_multiple {
  726:     my ($name) = @_;
  727:     my @values;
  728:     if (defined($env{$name})) {
  729:         # exists is it an array
  730:         if (ref($env{$name})) {
  731:             @values=@{ $env{$name} };
  732:         } else {
  733:             $values[0]=$env{$name};
  734:         }
  735:     }
  736:     return(@values);
  737: }
  738: 
  739: # ------------------------------------------------------------------- Locking
  740: 
  741: sub set_lock {
  742:     my ($text)=@_;
  743:     $locknum++;
  744:     my $id=$$.'-'.$locknum;
  745:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  746:              'session.lock.'.$id => $text});
  747:     return $id;
  748: }
  749: 
  750: sub get_locks {
  751:     my $num=0;
  752:     my %texts=();
  753:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  754:        if ($lock=~/\w/) {
  755:           $num++;
  756:           $texts{$lock}=$env{'session.lock.'.$lock};
  757:        }
  758:    }
  759:    return ($num,%texts);
  760: }
  761: 
  762: sub remove_lock {
  763:     my ($id)=@_;
  764:     my $newlocks='';
  765:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  766:        if (($lock=~/\w/) && ($lock ne $id)) {
  767:           $newlocks.=','.$lock;
  768:        }
  769:     }
  770:     &appenv({'session.locks' => $newlocks});
  771:     &delenv('session.lock.'.$id);
  772: }
  773: 
  774: sub remove_all_locks {
  775:     my $activelocks=$env{'session.locks'};
  776:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  777:        if ($lock=~/\w/) {
  778:           &remove_lock($lock);
  779:        }
  780:     }
  781: }
  782: 
  783: 
  784: # ------------------------------------------ Find out current server userload
  785: sub userload {
  786:     my $numusers=0;
  787:     {
  788: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  789: 	my $filename;
  790: 	my $curtime=time;
  791: 	while ($filename=readdir(LONIDS)) {
  792: 	    next if ($filename eq '.' || $filename eq '..');
  793: 	    next if ($filename =~ /publicuser_\d+\.id/);
  794: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  795: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  796: 	}
  797: 	closedir(LONIDS);
  798:     }
  799:     my $userloadpercent=0;
  800:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  801:     if ($maxuserload) {
  802: 	$userloadpercent=100*$numusers/$maxuserload;
  803:     }
  804:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  805:     return $userloadpercent;
  806: }
  807: 
  808: # ------------------------------ Find server with least workload from spare.tab
  809: 
  810: sub spareserver {
  811:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
  812:     my $spare_server;
  813:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  814:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  815:                                                      :  $userloadpercent;
  816:     my ($uint_dom,$remotesessions);
  817:     if (($udom ne '') && (&domain($udom) ne '')) {
  818:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
  819:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
  820:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
  821:         $remotesessions = $udomdefaults{'remotesessions'};
  822:     }
  823:     my $spareshash = &this_host_spares($udom);
  824:     if (ref($spareshash) eq 'HASH') {
  825:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  826:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  827:                 if ($uint_dom) {
  828:                     next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
  829:                                                  $try_server));
  830:                 }
  831: 	        ($spare_server, $lowest_load) =
  832: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
  833:             }
  834:         }
  835: 
  836:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
  837: 
  838:         if (!$found_server) {
  839:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
  840: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
  841:                     if ($uint_dom) {
  842:                         next unless (&spare_can_host($udom,$uint_dom,
  843:                                                      $remotesessions,$try_server));
  844:                     }
  845: 	            ($spare_server, $lowest_load) =
  846: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
  847:                 }
  848: 	    }
  849:         }
  850:     }
  851: 
  852:     if (!$want_server_name) {
  853:         my $protocol = 'http';
  854:         if ($protocol{$spare_server} eq 'https') {
  855:             $protocol = $protocol{$spare_server};
  856:         }
  857:         if (defined($spare_server)) {
  858:             my $hostname = &hostname($spare_server);
  859:             if (defined($hostname)) {
  860: 	        $spare_server = $protocol.'://'.$hostname;
  861:             }
  862:         }
  863:     }
  864:     return $spare_server;
  865: }
  866: 
  867: sub compare_server_load {
  868:     my ($try_server, $spare_server, $lowest_load) = @_;
  869: 
  870:     my $loadans     = &reply('load',    $try_server);
  871:     my $userloadans = &reply('userload',$try_server);
  872: 
  873:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  874: 	return ($spare_server, $lowest_load); #didn't get a number from the server
  875:     }
  876: 
  877:     my $load;
  878:     if ($loadans =~ /\d/) {
  879: 	if ($userloadans =~ /\d/) {
  880: 	    #both are numbers, pick the bigger one
  881: 	    $load = ($loadans > $userloadans) ? $loadans 
  882: 		                              : $userloadans;
  883: 	} else {
  884: 	    $load = $loadans;
  885: 	}
  886:     } else {
  887: 	$load = $userloadans;
  888:     }
  889: 
  890:     if (($load =~ /\d/) && ($load < $lowest_load)) {
  891: 	$spare_server = $try_server;
  892: 	$lowest_load  = $load;
  893:     }
  894:     return ($spare_server,$lowest_load);
  895: }
  896: 
  897: # --------------------------- ask offload servers if user already has a session
  898: sub find_existing_session {
  899:     my ($udom,$uname) = @_;
  900:     my $spareshash = &this_host_spares($udom);
  901:     if (ref($spareshash) eq 'HASH') {
  902:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  903:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  904:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
  905:             }
  906:         }
  907:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
  908:             foreach my $try_server (@{ $spareshash->{'default'} }) {
  909:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
  910:             }
  911:         }
  912:     }
  913:     return;
  914: }
  915: 
  916: # -------------------------------- ask if server already has a session for user
  917: sub has_user_session {
  918:     my ($lonid,$udom,$uname) = @_;
  919:     my $result = &reply(join(':','userhassession',
  920: 			     map {&escape($_)} ($udom,$uname)),$lonid);
  921:     return 1 if ($result eq 'ok');
  922: 
  923:     return 0;
  924: }
  925: 
  926: # --------- determine least loaded server in a user's domain which allows login
  927: 
  928: sub choose_server {
  929:     my ($udom,$checkloginvia) = @_;
  930:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
  931:     my %servers = &get_servers($udom);
  932:     my $lowest_load = 30000;
  933:     my ($login_host,$hostname,$portal_path);
  934:     foreach my $lonhost (keys(%servers)) {
  935:         my $loginvia;
  936:         if ($checkloginvia) {
  937:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
  938:             if ($loginvia) {
  939:                 my ($server,$path) = split(/:/,$loginvia);
  940:                 ($login_host, $lowest_load) =
  941:                     &compare_server_load($server, $login_host, $lowest_load);
  942:                 if ($login_host eq $server) {
  943:                     $portal_path = $path;
  944:                 }
  945:             } else {
  946:                 ($login_host, $lowest_load) =
  947:                     &compare_server_load($lonhost, $login_host, $lowest_load);
  948:                 if ($login_host eq $lonhost) {
  949:                     $portal_path = '';
  950:                 }
  951:             }
  952:         } else {
  953:             ($login_host, $lowest_load) =
  954:                 &compare_server_load($lonhost, $login_host, $lowest_load);
  955:         }
  956:     }
  957:     if ($login_host ne '') {
  958:         $hostname = &hostname($login_host);
  959:     }
  960:     return ($login_host,$hostname,$portal_path);
  961: }
  962: 
  963: # --------------------------------------------- Try to change a user's password
  964: 
  965: sub changepass {
  966:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
  967:     $currentpass = &escape($currentpass);
  968:     $newpass     = &escape($newpass);
  969:     my $lonhost = $perlvar{'lonHostID'};
  970:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
  971: 		       $server);
  972:     if (! $answer) {
  973: 	&logthis("No reply on password change request to $server ".
  974: 		 "by $uname in domain $udom.");
  975:     } elsif ($answer =~ "^ok") {
  976:         &logthis("$uname in $udom successfully changed their password ".
  977: 		 "on $server.");
  978:     } elsif ($answer =~ "^pwchange_failure") {
  979: 	&logthis("$uname in $udom was unable to change their password ".
  980: 		 "on $server.  The action was blocked by either lcpasswd ".
  981: 		 "or pwchange");
  982:     } elsif ($answer =~ "^non_authorized") {
  983:         &logthis("$uname in $udom did not get their password correct when ".
  984: 		 "attempting to change it on $server.");
  985:     } elsif ($answer =~ "^auth_mode_error") {
  986:         &logthis("$uname in $udom attempted to change their password despite ".
  987: 		 "not being locally or internally authenticated on $server.");
  988:     } elsif ($answer =~ "^unknown_user") {
  989:         &logthis("$uname in $udom attempted to change their password ".
  990: 		 "on $server but were unable to because $server is not ".
  991: 		 "their home server.");
  992:     } elsif ($answer =~ "^refused") {
  993: 	&logthis("$server refused to change $uname in $udom password because ".
  994: 		 "it was sent an unencrypted request to change the password.");
  995:     } elsif ($answer =~ "invalid_client") {
  996:         &logthis("$server refused to change $uname in $udom password because ".
  997:                  "it was a reset by e-mail originating from an invalid server.");
  998:     }
  999:     return $answer;
 1000: }
 1001: 
 1002: # ----------------------- Try to determine user's current authentication scheme
 1003: 
 1004: sub queryauthenticate {
 1005:     my ($uname,$udom)=@_;
 1006:     my $uhome=&homeserver($uname,$udom);
 1007:     if (!$uhome) {
 1008: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
 1009: 	return 'no_host';
 1010:     }
 1011:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
 1012:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
 1013: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1014:     }
 1015:     return $answer;
 1016: }
 1017: 
 1018: # --------- Try to authenticate user from domain's lib servers (first this one)
 1019: 
 1020: sub authenticate {
 1021:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
 1022:     $upass=&escape($upass);
 1023:     $uname= &LONCAPA::clean_username($uname);
 1024:     my $uhome=&homeserver($uname,$udom,1);
 1025:     my $newhome;
 1026:     if ((!$uhome) || ($uhome eq 'no_host')) {
 1027: # Maybe the machine was offline and only re-appeared again recently?
 1028:         &reconlonc();
 1029: # One more
 1030: 	$uhome=&homeserver($uname,$udom,1);
 1031:         if (($uhome eq 'no_host') && $checkdefauth) {
 1032:             if (defined(&domain($udom,'primary'))) {
 1033:                 $newhome=&domain($udom,'primary');
 1034:             }
 1035:             if ($newhome ne '') {
 1036:                 $uhome = $newhome;
 1037:             }
 1038:         }
 1039: 	if ((!$uhome) || ($uhome eq 'no_host')) {
 1040: 	    &logthis("User $uname at $udom is unknown in authenticate");
 1041: 	    return 'no_host';
 1042:         }
 1043:     }
 1044:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
 1045:     if ($answer eq 'authorized') {
 1046:         if ($newhome) {
 1047:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
 1048:             return 'no_account_on_host'; 
 1049:         } else {
 1050:             &logthis("User $uname at $udom authorized by $uhome");
 1051:             return $uhome;
 1052:         }
 1053:     }
 1054:     if ($answer eq 'non_authorized') {
 1055: 	&logthis("User $uname at $udom rejected by $uhome");
 1056: 	return 'no_host'; 
 1057:     }
 1058:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1059:     return 'no_host';
 1060: }
 1061: 
 1062: sub can_host_session {
 1063:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
 1064:     my $canhost = 1;
 1065:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
 1066:     if (ref($remotesessions) eq 'HASH') {
 1067:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
 1068:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
 1069:                 $canhost = 0;
 1070:             } else {
 1071:                 $canhost = 1;
 1072:             }
 1073:         }
 1074:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
 1075:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
 1076:                 $canhost = 1;
 1077:             } else {
 1078:                 $canhost = 0;
 1079:             }
 1080:         }
 1081:         if ($canhost) {
 1082:             if ($remotesessions->{'version'} ne '') {
 1083:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
 1084:                 if ($reqmajor ne '' && $reqminor ne '') {
 1085:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
 1086:                         my $major = $1;
 1087:                         my $minor = $2;
 1088:                         if (($major < $reqmajor ) ||
 1089:                             (($major == $reqmajor) && ($minor < $reqminor))) {
 1090:                             $canhost = 0;
 1091:                         }
 1092:                     } else {
 1093:                         $canhost = 0;
 1094:                     }
 1095:                 }
 1096:             }
 1097:         }
 1098:     }
 1099:     if ($canhost) {
 1100:         if (ref($hostedsessions) eq 'HASH') {
 1101:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1102:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 1103:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
 1104:                 if (($uint_dom ne '') && 
 1105:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
 1106:                     $canhost = 0;
 1107:                 } else {
 1108:                     $canhost = 1;
 1109:                 }
 1110:             }
 1111:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
 1112:                 if (($uint_dom ne '') && 
 1113:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
 1114:                     $canhost = 1;
 1115:                 } else {
 1116:                     $canhost = 0;
 1117:                 }
 1118:             }
 1119:         }
 1120:     }
 1121:     return $canhost;
 1122: }
 1123: 
 1124: sub spare_can_host {
 1125:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
 1126:     my $canhost=1;
 1127:     my @intdoms;
 1128:     my $internet_names = &Apache::lonnet::get_internet_names($try_server);
 1129:     if (ref($internet_names) eq 'ARRAY') {
 1130:         @intdoms = @{$internet_names};
 1131:     }
 1132:     unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1133:         my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
 1134:         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
 1135:         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
 1136:         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
 1137:         $canhost = &can_host_session($udom,$try_server,$remoterev,
 1138:                                      $remotesessions,
 1139:                                      $defdomdefaults{'hostedsessions'});
 1140:     }
 1141:     return $canhost;
 1142: }
 1143: 
 1144: sub this_host_spares {
 1145:     my ($dom) = @_;
 1146:     my ($dom_in_use,$lonhost_in_use,$result);
 1147:     my @hosts = &current_machine_ids();
 1148:     foreach my $lonhost (@hosts) {
 1149:         if (&host_domain($lonhost) eq $dom) {
 1150:             $dom_in_use = $dom;
 1151:             $lonhost_in_use = $lonhost;
 1152:             last;
 1153:         }
 1154:     }
 1155:     if ($dom_in_use ne '') {
 1156:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1157:     }
 1158:     if (ref($result) ne 'HASH') {
 1159:         $lonhost_in_use = $perlvar{'lonHostID'};
 1160:         $dom_in_use = &host_domain($lonhost_in_use);
 1161:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1162:         if (ref($result) ne 'HASH') {
 1163:             $result = \%spareid;
 1164:         }
 1165:     }
 1166:     return $result;
 1167: }
 1168: 
 1169: sub spares_for_offload  {
 1170:     my ($dom_in_use,$lonhost_in_use) = @_;
 1171:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
 1172:     if (defined($cached)) {
 1173:         return $result;
 1174:     } else {
 1175:         my $cachetime = 60*60*24;
 1176:         my %domconfig =
 1177:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
 1178:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1179:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
 1180:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
 1181:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
 1182:                 }
 1183:             }
 1184:         }
 1185:     }
 1186:     return;
 1187: }
 1188: 
 1189: sub get_lonbalancer_config {
 1190:     my ($servers) = @_;
 1191:     my ($currbalancer,$currtargets);
 1192:     if (ref($servers) eq 'HASH') {
 1193:         foreach my $server (keys(%{$servers})) {
 1194:             my %what = (
 1195:                          spareid => 1,
 1196:                          perlvar => 1,
 1197:                        );
 1198:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
 1199:             if ($result eq 'ok') {
 1200:                 if (ref($returnhash) eq 'HASH') {
 1201:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
 1202:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
 1203:                             $currbalancer = $server;
 1204:                             $currtargets = {};
 1205:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
 1206:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
 1207:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
 1208:                                 }
 1209:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
 1210:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
 1211:                                 }
 1212:                             }
 1213:                             last;
 1214:                         }
 1215:                     }
 1216:                 }
 1217:             }
 1218:         }
 1219:     }
 1220:     return ($currbalancer,$currtargets);
 1221: }
 1222: 
 1223: sub check_loadbalancing {
 1224:     my ($uname,$udom) = @_;
 1225:     my ($is_balancer,$dom_in_use,$homeintdom,$rule_in_effect,
 1226:         $offloadto,$otherserver);
 1227:     my $lonhost = $perlvar{'lonHostID'};
 1228:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1229:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
 1230:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
 1231:     my $serverhomedom = &host_domain($lonhost);
 1232: 
 1233:     my $cachetime = 60*60*24;
 1234: 
 1235:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1236:         $dom_in_use = $udom;
 1237:         $homeintdom = 1;
 1238:     } else {
 1239:         $dom_in_use = $serverhomedom;
 1240:     }
 1241:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
 1242:     unless (defined($cached)) {
 1243:         my %domconfig =
 1244:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
 1245:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1246:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1247:         }
 1248:     }
 1249:     if (ref($result) eq 'HASH') {
 1250:         my $currbalancer = $result->{'lonhost'};
 1251:         my $currtargets = $result->{'targets'};
 1252:         my $currrules = $result->{'rules'};
 1253:         if ($currbalancer ne '') {
 1254:             my @hosts = &current_machine_ids();
 1255:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
 1256:                 $is_balancer = 1;
 1257:             }
 1258:         }
 1259:         if ($is_balancer) {
 1260:             if (ref($currrules) eq 'HASH') {
 1261:                 if ($homeintdom) {
 1262:                     if ($uname ne '') {
 1263:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
 1264:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
 1265:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
 1266:                                 $rule_in_effect = $currrules->{'_LC_author'};
 1267:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
 1268:                                 $rule_in_effect = $currrules->{'_LC_adv'}
 1269:                             }
 1270:                         }
 1271:                         if ($rule_in_effect eq '') {
 1272:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
 1273:                             if ($userenv{'inststatus'} ne '') {
 1274:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
 1275:                                 my ($othertitle,$usertypes,$types) =
 1276:                                     &Apache::loncommon::sorted_inst_types($udom);
 1277:                                 if (ref($types) eq 'ARRAY') {
 1278:                                     foreach my $type (@{$types}) {
 1279:                                         if (grep(/^\Q$type\E$/,@statuses)) {
 1280:                                             if (exists($currrules->{$type})) {
 1281:                                                 $rule_in_effect = $currrules->{$type};
 1282:                                             }
 1283:                                         }
 1284:                                     }
 1285:                                 }
 1286:                             } else {
 1287:                                 if (exists($currrules->{'default'})) {
 1288:                                     $rule_in_effect = $currrules->{'default'};
 1289:                                 }
 1290:                             }
 1291:                         }
 1292:                     } else {
 1293:                         if (exists($currrules->{'default'})) {
 1294:                             $rule_in_effect = $currrules->{'default'};
 1295:                         }
 1296:                     }
 1297:                 } else {
 1298:                     if ($currrules->{'_LC_external'} ne '') {
 1299:                         $rule_in_effect = $currrules->{'_LC_external'};
 1300:                     }
 1301:                 }
 1302:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1303:                                                        $uname,$udom);
 1304:             }
 1305:         }
 1306:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
 1307:         my ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
 1308:         unless (defined($cached)) {
 1309:             my %domconfig =
 1310:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
 1311:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1312:                 $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1313:             }
 1314:         }
 1315:         if (ref($result) eq 'HASH') {
 1316:             my $currbalancer = $result->{'lonhost'};
 1317:             my $currtargets = $result->{'targets'};
 1318:             my $currrules = $result->{'rules'};
 1319: 
 1320:             if ($currbalancer eq $lonhost) {
 1321:                 $is_balancer = 1;
 1322:                 if (ref($currrules) eq 'HASH') {
 1323:                     if ($currrules->{'_LC_internetdom'} ne '') {
 1324:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
 1325:                     }
 1326:                 }
 1327:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1328:                                                        $uname,$udom);
 1329:             }
 1330:         } else {
 1331:             if ($perlvar{'lonBalancer'} eq 'yes') {
 1332:                 $is_balancer = 1;
 1333:                 $offloadto = &this_host_spares($dom_in_use);
 1334:             }
 1335:         }
 1336:     } else {
 1337:         if ($perlvar{'lonBalancer'} eq 'yes') {
 1338:             $is_balancer = 1;
 1339:             $offloadto = &this_host_spares($dom_in_use);
 1340:         }
 1341:     }
 1342:     my $lowest_load = 30000;
 1343:     if (ref($offloadto) eq 'HASH') {
 1344:         if (ref($offloadto->{'primary'}) eq 'ARRAY') {
 1345:             foreach my $try_server (@{$offloadto->{'primary'}}) {
 1346:                 ($otherserver,$lowest_load) =
 1347:                     &compare_server_load($try_server,$otherserver,$lowest_load);
 1348:             }
 1349:         }
 1350:         my $found_server = ($otherserver ne '' && $lowest_load < 100);
 1351: 
 1352:         if (!$found_server) {
 1353:             if (ref($offloadto->{'default'}) eq 'ARRAY') {
 1354:                 foreach my $try_server (@{$offloadto->{'default'}}) {
 1355:                     ($otherserver,$lowest_load) =
 1356:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1357:                 }
 1358:             }
 1359:         }
 1360:     } elsif (ref($offloadto) eq 'ARRAY') {
 1361:         if (@{$offloadto} == 1) {
 1362:             $otherserver = $offloadto->[0];
 1363:         } elsif (@{$offloadto} > 1) {
 1364:             foreach my $try_server (@{$offloadto}) {
 1365:                 ($otherserver,$lowest_load) =
 1366:                     &compare_server_load($try_server,$otherserver,$lowest_load);
 1367:             }
 1368:         }
 1369:     }
 1370:     return ($is_balancer,$otherserver);
 1371: }
 1372: 
 1373: sub get_loadbalancer_targets {
 1374:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
 1375:     my $offloadto;
 1376:     if ($rule_in_effect eq '') {
 1377:         $offloadto = $currtargets;
 1378:     } else {
 1379:         if ($rule_in_effect eq 'homeserver') {
 1380:             my $homeserver = &homeserver($uname,$udom);
 1381:             if ($homeserver ne 'no_host') {
 1382:                 $offloadto = [$homeserver];
 1383:             }
 1384:         } elsif ($rule_in_effect eq 'externalbalancer') {
 1385:             my %domconfig =
 1386:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1387:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1388:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
 1389:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
 1390:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
 1391:                     }
 1392:                 }
 1393:             } else {
 1394:                 my %servers = &dom_servers($udom);
 1395:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
 1396:                 if (&hostname($remotebalancer) ne '') {
 1397:                     $offloadto = [$remotebalancer];
 1398:                 }
 1399:             }
 1400:         } elsif (&hostname($rule_in_effect) ne '') {
 1401:             $offloadto = [$rule_in_effect];
 1402:         }
 1403:     }
 1404:     return $offloadto;
 1405: }
 1406: 
 1407: sub internet_dom_servers {
 1408:     my ($dom) = @_;
 1409:     my (%uniqservers,%servers);
 1410:     my $primaryserver = &hostname(&domain($dom,'primary'));
 1411:     my @machinedoms = &machine_domains($primaryserver);
 1412:     foreach my $mdom (@machinedoms) {
 1413:         my %currservers = %servers;
 1414:         my %server = &get_servers($mdom);
 1415:         %servers = (%currservers,%server);
 1416:     }
 1417:     my %by_hostname;
 1418:     foreach my $id (keys(%servers)) {
 1419:         push(@{$by_hostname{$servers{$id}}},$id);
 1420:     }
 1421:     foreach my $hostname (sort(keys(%by_hostname))) {
 1422:         if (@{$by_hostname{$hostname}} > 1) {
 1423:             my $match = 0;
 1424:             foreach my $id (@{$by_hostname{$hostname}}) {
 1425:                 if (&host_domain($id) eq $dom) {
 1426:                     $uniqservers{$id} = $hostname;
 1427:                     $match = 1;
 1428:                 }
 1429:             }
 1430:             unless ($match) {
 1431:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1432:             }
 1433:         } else {
 1434:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1435:         }
 1436:     }
 1437:     return %uniqservers;
 1438: }
 1439: 
 1440: # ---------------------- Find the homebase for a user from domain's lib servers
 1441: 
 1442: my %homecache;
 1443: sub homeserver {
 1444:     my ($uname,$udom,$ignoreBadCache)=@_;
 1445:     my $index="$uname:$udom";
 1446: 
 1447:     if (exists($homecache{$index})) { return $homecache{$index}; }
 1448: 
 1449:     my %servers = &get_servers($udom,'library');
 1450:     foreach my $tryserver (keys(%servers)) {
 1451:         next if ($ignoreBadCache ne 'true' && 
 1452: 		 exists($badServerCache{$tryserver}));
 1453: 
 1454: 	my $answer=reply("home:$udom:$uname",$tryserver);
 1455: 	if ($answer eq 'found') {
 1456: 	    delete($badServerCache{$tryserver}); 
 1457: 	    return $homecache{$index}=$tryserver;
 1458: 	} elsif ($answer eq 'no_host') {
 1459: 	    $badServerCache{$tryserver}=1;
 1460: 	}
 1461:     }    
 1462:     return 'no_host';
 1463: }
 1464: 
 1465: # ------------------------------------- Find the usernames behind a list of IDs
 1466: 
 1467: sub idget {
 1468:     my ($udom,@ids)=@_;
 1469:     my %returnhash=();
 1470:     
 1471:     my %servers = &get_servers($udom,'library');
 1472:     foreach my $tryserver (keys(%servers)) {
 1473: 	my $idlist=join('&',@ids);
 1474: 	$idlist=~tr/A-Z/a-z/; 
 1475: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
 1476: 	my @answer=();
 1477: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
 1478: 	    @answer=split(/\&/,$reply);
 1479: 	}                    ;
 1480: 	my $i;
 1481: 	for ($i=0;$i<=$#ids;$i++) {
 1482: 	    if ($answer[$i]) {
 1483: 		$returnhash{$ids[$i]}=$answer[$i];
 1484: 	    } 
 1485: 	}
 1486:     } 
 1487:     return %returnhash;
 1488: }
 1489: 
 1490: # ------------------------------------- Find the IDs behind a list of usernames
 1491: 
 1492: sub idrget {
 1493:     my ($udom,@unames)=@_;
 1494:     my %returnhash=();
 1495:     foreach my $uname (@unames) {
 1496:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
 1497:     }
 1498:     return %returnhash;
 1499: }
 1500: 
 1501: # ------------------------------- Store away a list of names and associated IDs
 1502: 
 1503: sub idput {
 1504:     my ($udom,%ids)=@_;
 1505:     my %servers=();
 1506:     foreach my $uname (keys(%ids)) {
 1507: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
 1508:         my $uhom=&homeserver($uname,$udom);
 1509:         if ($uhom ne 'no_host') {
 1510:             my $id=&escape($ids{$uname});
 1511:             $id=~tr/A-Z/a-z/;
 1512:             my $esc_unam=&escape($uname);
 1513: 	    if ($servers{$uhom}) {
 1514: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
 1515:             } else {
 1516:                 $servers{$uhom}=$id.'='.$esc_unam;
 1517:             }
 1518:         }
 1519:     }
 1520:     foreach my $server (keys(%servers)) {
 1521:         &critical('idput:'.$udom.':'.$servers{$server},$server);
 1522:     }
 1523: }
 1524: 
 1525: # ------------------------------dump from db file owned by domainconfig user
 1526: sub dump_dom {
 1527:     my ($namespace,$udom,$regexp,$range)=@_;
 1528:     if (!$udom) {
 1529:         $udom=$env{'user.domain'};
 1530:     }
 1531:     my %returnhash;
 1532:     if ($udom) {
 1533:         my $uname = &get_domainconfiguser($udom);
 1534:         %returnhash = &dump($namespace,$udom,$uname,$regexp,$range);
 1535:     }
 1536:     return %returnhash;
 1537: }
 1538: 
 1539: # ------------------------------------------ get items from domain db files   
 1540: 
 1541: sub get_dom {
 1542:     my ($namespace,$storearr,$udom,$uhome)=@_;
 1543:     my $items='';
 1544:     foreach my $item (@$storearr) {
 1545:         $items.=&escape($item).'&';
 1546:     }
 1547:     $items=~s/\&$//;
 1548:     if (!$udom) {
 1549:         $udom=$env{'user.domain'};
 1550:         if (defined(&domain($udom,'primary'))) {
 1551:             $uhome=&domain($udom,'primary');
 1552:         } else {
 1553:             undef($uhome);
 1554:         }
 1555:     } else {
 1556:         if (!$uhome) {
 1557:             if (defined(&domain($udom,'primary'))) {
 1558:                 $uhome=&domain($udom,'primary');
 1559:             }
 1560:         }
 1561:     }
 1562:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1563:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 1564:         my %returnhash;
 1565:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 1566:             return %returnhash;
 1567:         }
 1568:         my @pairs=split(/\&/,$rep);
 1569:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 1570:             return @pairs;
 1571:         }
 1572:         my $i=0;
 1573:         foreach my $item (@$storearr) {
 1574:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 1575:             $i++;
 1576:         }
 1577:         return %returnhash;
 1578:     } else {
 1579:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 1580:     }
 1581: }
 1582: 
 1583: # -------------------------------------------- put items in domain db files 
 1584: 
 1585: sub put_dom {
 1586:     my ($namespace,$storehash,$udom,$uhome)=@_;
 1587:     if (!$udom) {
 1588:         $udom=$env{'user.domain'};
 1589:         if (defined(&domain($udom,'primary'))) {
 1590:             $uhome=&domain($udom,'primary');
 1591:         } else {
 1592:             undef($uhome);
 1593:         }
 1594:     } else {
 1595:         if (!$uhome) {
 1596:             if (defined(&domain($udom,'primary'))) {
 1597:                 $uhome=&domain($udom,'primary');
 1598:             }
 1599:         }
 1600:     } 
 1601:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1602:         my $items='';
 1603:         foreach my $item (keys(%$storehash)) {
 1604:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 1605:         }
 1606:         $items=~s/\&$//;
 1607:         return &reply("putdom:$udom:$namespace:$items",$uhome);
 1608:     } else {
 1609:         &logthis("put_dom failed - no homeserver and/or domain");
 1610:     }
 1611: }
 1612: 
 1613: # --------------------- newput for items in db file owned by domainconfig user
 1614: sub newput_dom {
 1615:     my ($namespace,$storehash,$udom) = @_;
 1616:     my $result;
 1617:     if (!$udom) {
 1618:         $udom=$env{'user.domain'};
 1619:     }
 1620:     if ($udom) {
 1621:         my $uname = &get_domainconfiguser($udom);
 1622:         $result = &newput($namespace,$storehash,$udom,$uname);
 1623:     }
 1624:     return $result;
 1625: }
 1626: 
 1627: # --------------------- delete for items in db file owned by domainconfig user
 1628: sub del_dom {
 1629:     my ($namespace,$storearr,$udom)=@_;
 1630:     if (ref($storearr) eq 'ARRAY') {
 1631:         if (!$udom) {
 1632:             $udom=$env{'user.domain'};
 1633:         }
 1634:         if ($udom) {
 1635:             my $uname = &get_domainconfiguser($udom); 
 1636:             return &del($namespace,$storearr,$udom,$uname);
 1637:         }
 1638:     }
 1639: }
 1640: 
 1641: # ----------------------------------construct domainconfig user for a domain 
 1642: sub get_domainconfiguser {
 1643:     my ($udom) = @_;
 1644:     return $udom.'-domainconfig';
 1645: }
 1646: 
 1647: sub retrieve_inst_usertypes {
 1648:     my ($udom) = @_;
 1649:     my (%returnhash,@order);
 1650:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 1651:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 1652:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 1653:         %returnhash = %{$domdefs{'inststatustypes'}};
 1654:         @order = @{$domdefs{'inststatusorder'}};
 1655:     } else {
 1656:         if (defined(&domain($udom,'primary'))) {
 1657:             my $uhome=&domain($udom,'primary');
 1658:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 1659:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 1660:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
 1661:                 return (\%returnhash,\@order);
 1662:             }
 1663:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 1664:             my @pairs=split(/\&/,$hashitems);
 1665:             foreach my $item (@pairs) {
 1666:                 my ($key,$value)=split(/=/,$item,2);
 1667:                 $key = &unescape($key);
 1668:                 next if ($key =~ /^error: 2 /);
 1669:                 $returnhash{$key}=&thaw_unescape($value);
 1670:             }
 1671:             my @esc_order = split(/\&/,$orderitems);
 1672:             foreach my $item (@esc_order) {
 1673:                 push(@order,&unescape($item));
 1674:             }
 1675:         } else {
 1676:             &logthis("get_dom failed - no primary domain server for $udom");
 1677:         }
 1678:     }
 1679:     return (\%returnhash,\@order);
 1680: }
 1681: 
 1682: sub is_domainimage {
 1683:     my ($url) = @_;
 1684:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
 1685:         if (&domain($1) ne '') {
 1686:             return '1';
 1687:         }
 1688:     }
 1689:     return;
 1690: }
 1691: 
 1692: sub inst_directory_query {
 1693:     my ($srch) = @_;
 1694:     my $udom = $srch->{'srchdomain'};
 1695:     my %results;
 1696:     my $homeserver = &domain($udom,'primary');
 1697:     my $outcome;
 1698:     if ($homeserver ne '') {
 1699: 	my $queryid=&reply("querysend:instdirsearch:".
 1700: 			   &escape($srch->{'srchby'}).':'.
 1701: 			   &escape($srch->{'srchterm'}).':'.
 1702: 			   &escape($srch->{'srchtype'}),$homeserver);
 1703: 	my $host=&hostname($homeserver);
 1704: 	if ($queryid !~/^\Q$host\E\_/) {
 1705: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1706: 	    return;
 1707: 	}
 1708: 	my $response = &get_query_reply($queryid);
 1709: 	my $maxtries = 5;
 1710: 	my $tries = 1;
 1711: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1712: 	    $response = &get_query_reply($queryid);
 1713: 	    $tries ++;
 1714: 	}
 1715: 
 1716:         if (!&error($response) && $response ne 'refused') {
 1717:             if ($response eq 'unavailable') {
 1718:                 $outcome = $response;
 1719:             } else {
 1720:                 $outcome = 'ok';
 1721:                 my @matches = split(/\n/,$response);
 1722:                 foreach my $match (@matches) {
 1723:                     my ($key,$value) = split(/=/,$match);
 1724:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 1725:                 }
 1726:             }
 1727:         }
 1728:     }
 1729:     return ($outcome,%results);
 1730: }
 1731: 
 1732: sub usersearch {
 1733:     my ($srch) = @_;
 1734:     my $dom = $srch->{'srchdomain'};
 1735:     my %results;
 1736:     my %libserv = &all_library();
 1737:     my $query = 'usersearch';
 1738:     foreach my $tryserver (keys(%libserv)) {
 1739:         if (&host_domain($tryserver) eq $dom) {
 1740:             my $host=&hostname($tryserver);
 1741:             my $queryid=
 1742:                 &reply("querysend:".&escape($query).':'.
 1743:                        &escape($srch->{'srchby'}).':'.
 1744:                        &escape($srch->{'srchtype'}).':'.
 1745:                        &escape($srch->{'srchterm'}),$tryserver);
 1746:             if ($queryid !~/^\Q$host\E\_/) {
 1747:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 1748:                 next;
 1749:             }
 1750:             my $reply = &get_query_reply($queryid);
 1751:             my $maxtries = 1;
 1752:             my $tries = 1;
 1753:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 1754:                 $reply = &get_query_reply($queryid);
 1755:                 $tries ++;
 1756:             }
 1757:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 1758:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 1759:             } else {
 1760:                 my @matches;
 1761:                 if ($reply =~ /\n/) {
 1762:                     @matches = split(/\n/,$reply);
 1763:                 } else {
 1764:                     @matches = split(/\&/,$reply);
 1765:                 }
 1766:                 foreach my $match (@matches) {
 1767:                     my ($uname,$udom,%userhash);
 1768:                     foreach my $entry (split(/:/,$match)) {
 1769:                         my ($key,$value) =
 1770:                             map {&unescape($_);} split(/=/,$entry);
 1771:                         $userhash{$key} = $value;
 1772:                         if ($key eq 'username') {
 1773:                             $uname = $value;
 1774:                         } elsif ($key eq 'domain') {
 1775:                             $udom = $value;
 1776:                         }
 1777:                     }
 1778:                     $results{$uname.':'.$udom} = \%userhash;
 1779:                 }
 1780:             }
 1781:         }
 1782:     }
 1783:     return %results;
 1784: }
 1785: 
 1786: sub get_instuser {
 1787:     my ($udom,$uname,$id) = @_;
 1788:     my $homeserver = &domain($udom,'primary');
 1789:     my ($outcome,%results);
 1790:     if ($homeserver ne '') {
 1791:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 1792:                            &escape($id).':'.&escape($udom),$homeserver);
 1793:         my $host=&hostname($homeserver);
 1794:         if ($queryid !~/^\Q$host\E\_/) {
 1795:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1796:             return;
 1797:         }
 1798:         my $response = &get_query_reply($queryid);
 1799:         my $maxtries = 5;
 1800:         my $tries = 1;
 1801:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1802:             $response = &get_query_reply($queryid);
 1803:             $tries ++;
 1804:         }
 1805:         if (!&error($response) && $response ne 'refused') {
 1806:             if ($response eq 'unavailable') {
 1807:                 $outcome = $response;
 1808:             } else {
 1809:                 $outcome = 'ok';
 1810:                 my @matches = split(/\n/,$response);
 1811:                 foreach my $match (@matches) {
 1812:                     my ($key,$value) = split(/=/,$match);
 1813:                     $results{&unescape($key)} = &thaw_unescape($value);
 1814:                 }
 1815:             }
 1816:         }
 1817:     }
 1818:     my %userinfo;
 1819:     if (ref($results{$uname}) eq 'HASH') {
 1820:         %userinfo = %{$results{$uname}};
 1821:     } 
 1822:     return ($outcome,%userinfo);
 1823: }
 1824: 
 1825: sub inst_rulecheck {
 1826:     my ($udom,$uname,$id,$item,$rules) = @_;
 1827:     my %returnhash;
 1828:     if ($udom ne '') {
 1829:         if (ref($rules) eq 'ARRAY') {
 1830:             @{$rules} = map {&escape($_);} (@{$rules});
 1831:             my $rulestr = join(':',@{$rules});
 1832:             my $homeserver=&domain($udom,'primary');
 1833:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1834:                 my $response;
 1835:                 if ($item eq 'username') {                
 1836:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 1837:                                               ':'.&escape($uname).':'.$rulestr,
 1838:                                               $homeserver));
 1839:                 } elsif ($item eq 'id') {
 1840:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 1841:                                               ':'.&escape($id).':'.$rulestr,
 1842:                                               $homeserver));
 1843:                 } elsif ($item eq 'selfcreate') {
 1844:                     $response=&unescape(&reply('instselfcreatecheck:'.
 1845:                                                &escape($udom).':'.&escape($uname).
 1846:                                               ':'.$rulestr,$homeserver));
 1847:                 }
 1848:                 if ($response ne 'refused') {
 1849:                     my @pairs=split(/\&/,$response);
 1850:                     foreach my $item (@pairs) {
 1851:                         my ($key,$value)=split(/=/,$item,2);
 1852:                         $key = &unescape($key);
 1853:                         next if ($key =~ /^error: 2 /);
 1854:                         $returnhash{$key}=&thaw_unescape($value);
 1855:                     }
 1856:                 }
 1857:             }
 1858:         }
 1859:     }
 1860:     return %returnhash;
 1861: }
 1862: 
 1863: sub inst_userrules {
 1864:     my ($udom,$check) = @_;
 1865:     my (%ruleshash,@ruleorder);
 1866:     if ($udom ne '') {
 1867:         my $homeserver=&domain($udom,'primary');
 1868:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1869:             my $response;
 1870:             if ($check eq 'id') {
 1871:                 $response=&reply('instidrules:'.&escape($udom),
 1872:                                  $homeserver);
 1873:             } elsif ($check eq 'email') {
 1874:                 $response=&reply('instemailrules:'.&escape($udom),
 1875:                                  $homeserver);
 1876:             } else {
 1877:                 $response=&reply('instuserrules:'.&escape($udom),
 1878:                                  $homeserver);
 1879:             }
 1880:             if (($response ne 'refused') && ($response ne 'error') && 
 1881:                 ($response ne 'unknown_cmd') && 
 1882:                 ($response ne 'no_such_host')) {
 1883:                 my ($hashitems,$orderitems) = split(/:/,$response);
 1884:                 my @pairs=split(/\&/,$hashitems);
 1885:                 foreach my $item (@pairs) {
 1886:                     my ($key,$value)=split(/=/,$item,2);
 1887:                     $key = &unescape($key);
 1888:                     next if ($key =~ /^error: 2 /);
 1889:                     $ruleshash{$key}=&thaw_unescape($value);
 1890:                 }
 1891:                 my @esc_order = split(/\&/,$orderitems);
 1892:                 foreach my $item (@esc_order) {
 1893:                     push(@ruleorder,&unescape($item));
 1894:                 }
 1895:             }
 1896:         }
 1897:     }
 1898:     return (\%ruleshash,\@ruleorder);
 1899: }
 1900: 
 1901: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 1902: 
 1903: sub get_domain_defaults {
 1904:     my ($domain) = @_;
 1905:     my $cachetime = 60*60*24;
 1906:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 1907:     if (defined($cached)) {
 1908:         if (ref($result) eq 'HASH') {
 1909:             return %{$result};
 1910:         }
 1911:     }
 1912:     my %domdefaults;
 1913:     my %domconfig =
 1914:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 1915:                                   'requestcourses','inststatus',
 1916:                                   'coursedefaults','usersessions'],$domain);
 1917:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 1918:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 1919:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 1920:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 1921:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 1922:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 1923:     } else {
 1924:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 1925:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 1926:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 1927:     }
 1928:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 1929:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 1930:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 1931:         } else {
 1932:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 1933:         } 
 1934:         my @usertools = ('aboutme','blog','portfolio');
 1935:         foreach my $item (@usertools) {
 1936:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 1937:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 1938:             }
 1939:         }
 1940:     }
 1941:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 1942:         foreach my $item ('official','unofficial','community') {
 1943:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 1944:         }
 1945:     }
 1946:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 1947:         foreach my $item ('inststatustypes','inststatusorder') {
 1948:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 1949:         }
 1950:     }
 1951:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 1952:         foreach my $item ('canuse_pdfforms') {
 1953:             $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
 1954:         }
 1955:     }
 1956:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1957:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 1958:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 1959:         }
 1960:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 1961:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 1962:         }
 1963:     }
 1964:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
 1965:                                   $cachetime);
 1966:     return %domdefaults;
 1967: }
 1968: 
 1969: # --------------------------------------------------- Assign a key to a student
 1970: 
 1971: sub assign_access_key {
 1972: #
 1973: # a valid key looks like uname:udom#comments
 1974: # comments are being appended
 1975: #
 1976:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 1977:     $kdom=
 1978:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 1979:     $knum=
 1980:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 1981:     $cdom=
 1982:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1983:     $cnum=
 1984:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1985:     $udom=$env{'user.name'} unless (defined($udom));
 1986:     $uname=$env{'user.domain'} unless (defined($uname));
 1987:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 1988:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 1989:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 1990:                                                   # assigned to this person
 1991:                                                   # - this should not happen,
 1992:                                                   # unless something went wrong
 1993:                                                   # the first time around
 1994: # ready to assign
 1995:         $logentry=$1.'; '.$logentry;
 1996:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 1997:                                                  $kdom,$knum) eq 'ok') {
 1998: # key now belongs to user
 1999: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 2000:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 2001:                 &appenv({'environment.'.$envkey => $ckey});
 2002:                 return 'ok';
 2003:             } else {
 2004:                 return 
 2005:   'error: Count not permanently assign key, will need to be re-entered later.';
 2006: 	    }
 2007:         } else {
 2008:             return 'error: Could not assign key, try again later.';
 2009:         }
 2010:     } elsif (!$existing{$ckey}) {
 2011: # the key does not exist
 2012: 	return 'error: The key does not exist';
 2013:     } else {
 2014: # the key is somebody else's
 2015: 	return 'error: The key is already in use';
 2016:     }
 2017: }
 2018: 
 2019: # ------------------------------------------ put an additional comment on a key
 2020: 
 2021: sub comment_access_key {
 2022: #
 2023: # a valid key looks like uname:udom#comments
 2024: # comments are being appended
 2025: #
 2026:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 2027:     $cdom=
 2028:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2029:     $cnum=
 2030:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2031:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2032:     if ($existing{$ckey}) {
 2033:         $existing{$ckey}.='; '.$logentry;
 2034: # ready to assign
 2035:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 2036:                                                  $cdom,$cnum) eq 'ok') {
 2037: 	    return 'ok';
 2038:         } else {
 2039: 	    return 'error: Count not store comment.';
 2040:         }
 2041:     } else {
 2042: # the key does not exist
 2043: 	return 'error: The key does not exist';
 2044:     }
 2045: }
 2046: 
 2047: # ------------------------------------------------------ Generate a set of keys
 2048: 
 2049: sub generate_access_keys {
 2050:     my ($number,$cdom,$cnum,$logentry)=@_;
 2051:     $cdom=
 2052:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2053:     $cnum=
 2054:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2055:     unless (&allowed('mky',$cdom)) { return 0; }
 2056:     unless (($cdom) && ($cnum)) { return 0; }
 2057:     if ($number>10000) { return 0; }
 2058:     sleep(2); # make sure don't get same seed twice
 2059:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 2060:     my $total=0;
 2061:     for (my $i=1;$i<=$number;$i++) {
 2062:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 2063:                   sprintf("%lx",int(100000*rand)).'-'.
 2064:                   sprintf("%lx",int(100000*rand));
 2065:        $newkey=~s/1/g/g; # folks mix up 1 and l
 2066:        $newkey=~s/0/h/g; # and also 0 and O
 2067:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 2068:        if ($existing{$newkey}) {
 2069:            $i--;
 2070:        } else {
 2071: 	  if (&put('accesskeys',
 2072:               { $newkey => '# generated '.localtime().
 2073:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 2074:                            '; '.$logentry },
 2075: 		   $cdom,$cnum) eq 'ok') {
 2076:               $total++;
 2077: 	  }
 2078:        }
 2079:     }
 2080:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 2081:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 2082:     return $total;
 2083: }
 2084: 
 2085: # ------------------------------------------------------- Validate an accesskey
 2086: 
 2087: sub validate_access_key {
 2088:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 2089:     $cdom=
 2090:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2091:     $cnum=
 2092:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2093:     $udom=$env{'user.domain'} unless (defined($udom));
 2094:     $uname=$env{'user.name'} unless (defined($uname));
 2095:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2096:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 2097: }
 2098: 
 2099: # ------------------------------------- Find the section of student in a course
 2100: sub devalidate_getsection_cache {
 2101:     my ($udom,$unam,$courseid)=@_;
 2102:     my $hashid="$udom:$unam:$courseid";
 2103:     &devalidate_cache_new('getsection',$hashid);
 2104: }
 2105: 
 2106: sub courseid_to_courseurl {
 2107:     my ($courseid) = @_;
 2108:     #already url style courseid
 2109:     return $courseid if ($courseid =~ m{^/});
 2110: 
 2111:     if (exists($env{'course.'.$courseid.'.num'})) {
 2112: 	my $cnum = $env{'course.'.$courseid.'.num'};
 2113: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 2114: 	return "/$cdom/$cnum";
 2115:     }
 2116: 
 2117:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 2118:     if (exists($courseinfo{'num'})) {
 2119: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 2120:     }
 2121: 
 2122:     return undef;
 2123: }
 2124: 
 2125: sub getsection {
 2126:     my ($udom,$unam,$courseid)=@_;
 2127:     my $cachetime=1800;
 2128: 
 2129:     my $hashid="$udom:$unam:$courseid";
 2130:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 2131:     if (defined($cached)) { return $result; }
 2132: 
 2133:     my %Pending; 
 2134:     my %Expired;
 2135:     #
 2136:     # Each role can either have not started yet (pending), be active, 
 2137:     #    or have expired.
 2138:     #
 2139:     # If there is an active role, we are done.
 2140:     #
 2141:     # If there is more than one role which has not started yet, 
 2142:     #     choose the one which will start sooner
 2143:     # If there is one role which has not started yet, return it.
 2144:     #
 2145:     # If there is more than one expired role, choose the one which ended last.
 2146:     # If there is a role which has expired, return it.
 2147:     #
 2148:     $courseid = &courseid_to_courseurl($courseid);
 2149:     my $extra = &freeze_escape({'skipcheck' => 1});
 2150:     my %roleshash = &dump('roles',$udom,$unam,$courseid,undef,$extra);
 2151:     foreach my $key (keys(%roleshash)) {
 2152:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 2153:         my $section=$1;
 2154:         if ($key eq $courseid.'_st') { $section=''; }
 2155:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 2156:         my $now=time;
 2157:         if (defined($end) && $end && ($now > $end)) {
 2158:             $Expired{$end}=$section;
 2159:             next;
 2160:         }
 2161:         if (defined($start) && $start && ($now < $start)) {
 2162:             $Pending{$start}=$section;
 2163:             next;
 2164:         }
 2165:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 2166:     }
 2167:     #
 2168:     # Presumedly there will be few matching roles from the above
 2169:     # loop and the sorting time will be negligible.
 2170:     if (scalar(keys(%Pending))) {
 2171:         my ($time) = sort {$a <=> $b} keys(%Pending);
 2172:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 2173:     } 
 2174:     if (scalar(keys(%Expired))) {
 2175:         my @sorted = sort {$a <=> $b} keys(%Expired);
 2176:         my $time = pop(@sorted);
 2177:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 2178:     }
 2179:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 2180: }
 2181: 
 2182: sub save_cache {
 2183:     &purge_remembered();
 2184:     #&Apache::loncommon::validate_page();
 2185:     undef(%env);
 2186:     undef($env_loaded);
 2187: }
 2188: 
 2189: my $to_remember=-1;
 2190: my %remembered;
 2191: my %accessed;
 2192: my $kicks=0;
 2193: my $hits=0;
 2194: sub make_key {
 2195:     my ($name,$id) = @_;
 2196:     if (length($id) > 65 
 2197: 	&& length(&escape($id)) > 200) {
 2198: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 2199:     }
 2200:     return &escape($name.':'.$id);
 2201: }
 2202: 
 2203: sub devalidate_cache_new {
 2204:     my ($name,$id,$debug) = @_;
 2205:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 2206:     $id=&make_key($name,$id);
 2207:     $memcache->delete($id);
 2208:     delete($remembered{$id});
 2209:     delete($accessed{$id});
 2210: }
 2211: 
 2212: sub is_cached_new {
 2213:     my ($name,$id,$debug) = @_;
 2214:     $id=&make_key($name,$id);
 2215:     if (exists($remembered{$id})) {
 2216: 	if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
 2217: 	$accessed{$id}=[&gettimeofday()];
 2218: 	$hits++;
 2219: 	return ($remembered{$id},1);
 2220:     }
 2221:     my $value = $memcache->get($id);
 2222:     if (!(defined($value))) {
 2223: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 2224: 	return (undef,undef);
 2225:     }
 2226:     if ($value eq '__undef__') {
 2227: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 2228: 	$value=undef;
 2229:     }
 2230:     &make_room($id,$value,$debug);
 2231:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 2232:     return ($value,1);
 2233: }
 2234: 
 2235: sub do_cache_new {
 2236:     my ($name,$id,$value,$time,$debug) = @_;
 2237:     $id=&make_key($name,$id);
 2238:     my $setvalue=$value;
 2239:     if (!defined($setvalue)) {
 2240: 	$setvalue='__undef__';
 2241:     }
 2242:     if (!defined($time) ) {
 2243: 	$time=600;
 2244:     }
 2245:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 2246:     my $result = $memcache->set($id,$setvalue,$time);
 2247:     if (! $result) {
 2248: 	&logthis("caching of id -> $id  failed");
 2249: 	$memcache->disconnect_all();
 2250:     }
 2251:     # need to make a copy of $value
 2252:     &make_room($id,$value,$debug);
 2253:     return $value;
 2254: }
 2255: 
 2256: sub make_room {
 2257:     my ($id,$value,$debug)=@_;
 2258: 
 2259:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
 2260:                                     : $value;
 2261:     if ($to_remember<0) { return; }
 2262:     $accessed{$id}=[&gettimeofday()];
 2263:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 2264:     my $to_kick;
 2265:     my $max_time=0;
 2266:     foreach my $other (keys(%accessed)) {
 2267: 	if (&tv_interval($accessed{$other}) > $max_time) {
 2268: 	    $to_kick=$other;
 2269: 	    $max_time=&tv_interval($accessed{$other});
 2270: 	}
 2271:     }
 2272:     delete($remembered{$to_kick});
 2273:     delete($accessed{$to_kick});
 2274:     $kicks++;
 2275:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 2276:     return;
 2277: }
 2278: 
 2279: sub purge_remembered {
 2280:     #&logthis("Tossing ".scalar(keys(%remembered)));
 2281:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 2282:     undef(%remembered);
 2283:     undef(%accessed);
 2284: }
 2285: # ------------------------------------- Read an entry from a user's environment
 2286: 
 2287: sub userenvironment {
 2288:     my ($udom,$unam,@what)=@_;
 2289:     my $items;
 2290:     foreach my $item (@what) {
 2291:         $items.=&escape($item).'&';
 2292:     }
 2293:     $items=~s/\&$//;
 2294:     my %returnhash=();
 2295:     my $uhome = &homeserver($unam,$udom);
 2296:     unless ($uhome eq 'no_host') {
 2297:         my @answer=split(/\&/, 
 2298:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 2299:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 2300:             return %returnhash;
 2301:         }
 2302:         my $i;
 2303:         for ($i=0;$i<=$#what;$i++) {
 2304: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 2305:         }
 2306:     }
 2307:     return %returnhash;
 2308: }
 2309: 
 2310: # ---------------------------------------------------------- Get a studentphoto
 2311: sub studentphoto {
 2312:     my ($udom,$unam,$ext) = @_;
 2313:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2314:     if (defined($env{'request.course.id'})) {
 2315:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 2316:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 2317:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 2318:             } else {
 2319:                 my ($result,$perm_reqd)=
 2320: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2321:                 if ($result eq 'ok') {
 2322:                     if (!($perm_reqd eq 'yes')) {
 2323:                         return(&retrievestudentphoto($udom,$unam,$ext));
 2324:                     }
 2325:                 }
 2326:             }
 2327:         }
 2328:     } else {
 2329:         my ($result,$perm_reqd) = 
 2330: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2331:         if ($result eq 'ok') {
 2332:             if (!($perm_reqd eq 'yes')) {
 2333:                 return(&retrievestudentphoto($udom,$unam,$ext));
 2334:             }
 2335:         }
 2336:     }
 2337:     return '/adm/lonKaputt/lonlogo_broken.gif';
 2338: }
 2339: 
 2340: sub retrievestudentphoto {
 2341:     my ($udom,$unam,$ext,$type) = @_;
 2342:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2343:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 2344:     if ($ret eq 'ok') {
 2345:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 2346:         if ($type eq 'thumbnail') {
 2347:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 2348:         }
 2349:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 2350:         return $tokenurl;
 2351:     } else {
 2352:         if ($type eq 'thumbnail') {
 2353:             return '/adm/lonKaputt/genericstudent_tn.gif';
 2354:         } else { 
 2355:             return '/adm/lonKaputt/lonlogo_broken.gif';
 2356:         }
 2357:     }
 2358: }
 2359: 
 2360: # -------------------------------------------------------------------- New chat
 2361: 
 2362: sub chatsend {
 2363:     my ($newentry,$anon,$group)=@_;
 2364:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 2365:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2366:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 2367:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 2368: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 2369: 		   &escape($newentry)).':'.$group,$chome);
 2370: }
 2371: 
 2372: # ------------------------------------------ Find current version of a resource
 2373: 
 2374: sub getversion {
 2375:     my $fname=&clutter(shift);
 2376:     unless ($fname=~/^\/res\//) { return -1; }
 2377:     return &currentversion(&filelocation('',$fname));
 2378: }
 2379: 
 2380: sub currentversion {
 2381:     my $fname=shift;
 2382:     my $author=$fname;
 2383:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2384:     my ($udom,$uname)=split(/\//,$author);
 2385:     my $home=&homeserver($uname,$udom);
 2386:     if ($home eq 'no_host') { 
 2387:         return -1; 
 2388:     }
 2389:     my $answer=&reply("currentversion:$fname",$home);
 2390:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 2391: 	return -1;
 2392:     }
 2393:     return $answer;
 2394: }
 2395: 
 2396: #
 2397: # Return special version number of resource if set by override, empty otherwise
 2398: #
 2399: sub usedversion {
 2400:     my $fname=shift;
 2401:     unless ($fname) { $fname=$env{'request.uri'}; }
 2402:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 2403:     if ($urlversion) { return $urlversion; }
 2404:     return '';
 2405: }
 2406: 
 2407: # ----------------------------- Subscribe to a resource, return URL if possible
 2408: 
 2409: sub subscribe {
 2410:     my $fname=shift;
 2411:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 2412:     $fname=~s/[\n\r]//g;
 2413:     my $author=$fname;
 2414:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2415:     my ($udom,$uname)=split(/\//,$author);
 2416:     my $home=homeserver($uname,$udom);
 2417:     if ($home eq 'no_host') {
 2418:         return 'not_found';
 2419:     }
 2420:     my $answer=reply("sub:$fname",$home);
 2421:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 2422: 	$answer.=' by '.$home;
 2423:     }
 2424:     return $answer;
 2425: }
 2426:     
 2427: # -------------------------------------------------------------- Replicate file
 2428: 
 2429: sub repcopy {
 2430:     my $filename=shift;
 2431:     $filename=~s/\/+/\//g;
 2432:     my $londocroot = $perlvar{'lonDocRoot'};
 2433:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 2434:     if ($filename=~m{^\Q$londocroot/lonUsers/\E}) { return 'ok'; }
 2435:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 2436: 	$filename=~m{^/*(uploaded|editupload)/}) {
 2437: 	return &repcopy_userfile($filename);
 2438:     }
 2439:     $filename=~s/[\n\r]//g;
 2440:     my $transname="$filename.in.transfer";
 2441: # FIXME: this should flock
 2442:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 2443:     my $remoteurl=subscribe($filename);
 2444:     if ($remoteurl =~ /^con_lost by/) {
 2445: 	   &logthis("Subscribe returned $remoteurl: $filename");
 2446:            return 'unavailable';
 2447:     } elsif ($remoteurl eq 'not_found') {
 2448: 	   #&logthis("Subscribe returned not_found: $filename");
 2449: 	   return 'not_found';
 2450:     } elsif ($remoteurl =~ /^rejected by/) {
 2451: 	   &logthis("Subscribe returned $remoteurl: $filename");
 2452:            return 'forbidden';
 2453:     } elsif ($remoteurl eq 'directory') {
 2454:            return 'ok';
 2455:     } else {
 2456:         my $author=$filename;
 2457:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2458:         my ($udom,$uname)=split(/\//,$author);
 2459:         my $home=homeserver($uname,$udom);
 2460:         unless ($home eq $perlvar{'lonHostID'}) {
 2461:            my @parts=split(/\//,$filename);
 2462:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 2463:            if ($path ne "$londocroot/res") {
 2464:                &logthis("Malconfiguration for replication: $filename");
 2465: 	       return 'bad_request';
 2466:            }
 2467:            my $count;
 2468:            for ($count=5;$count<$#parts;$count++) {
 2469:                $path.="/$parts[$count]";
 2470:                if ((-e $path)!=1) {
 2471: 		   mkdir($path,0777);
 2472:                }
 2473:            }
 2474:            my $ua=new LWP::UserAgent;
 2475:            my $request=new HTTP::Request('GET',"$remoteurl");
 2476:            my $response=$ua->request($request,$transname);
 2477:            if ($response->is_error()) {
 2478: 	       unlink($transname);
 2479:                my $message=$response->status_line;
 2480:                &logthis("<font color=\"blue\">WARNING:"
 2481:                        ." LWP get: $message: $filename</font>");
 2482:                return 'unavailable';
 2483:            } else {
 2484: 	       if ($remoteurl!~/\.meta$/) {
 2485:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 2486:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 2487:                   if ($mresponse->is_error()) {
 2488: 		      unlink($filename.'.meta');
 2489:                       &logthis(
 2490:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 2491:                   }
 2492: 	       }
 2493:                rename($transname,$filename);
 2494:                return 'ok';
 2495:            }
 2496:        }
 2497:     }
 2498: }
 2499: 
 2500: # ------------------------------------------------ Get server side include body
 2501: sub ssi_body {
 2502:     my ($filelink,%form)=@_;
 2503:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 2504:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 2505:     }
 2506:     my $output='';
 2507:     my $response;
 2508:     if ($filelink=~/^https?\:/) {
 2509:        ($output,$response)=&externalssi($filelink);
 2510:     } else {
 2511:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 2512:        $filelink .= 'inhibitmenu=yes';
 2513:        ($output,$response)=&ssi($filelink,%form);
 2514:     }
 2515:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 2516:     $output=~s/^.*?\<body[^\>]*\>//si;
 2517:     $output=~s/\<\/body\s*\>.*?$//si;
 2518:     if (wantarray) {
 2519:         return ($output, $response);
 2520:     } else {
 2521:         return $output;
 2522:     }
 2523: }
 2524: 
 2525: # --------------------------------------------------------- Server Side Include
 2526: 
 2527: sub absolute_url {
 2528:     my ($host_name) = @_;
 2529:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 2530:     if ($host_name eq '') {
 2531: 	$host_name = $ENV{'SERVER_NAME'};
 2532:     }
 2533:     return $protocol.$host_name;
 2534: }
 2535: 
 2536: #
 2537: #   Server side include.
 2538: # Parameters:
 2539: #  fn     Possibly encrypted resource name/id.
 2540: #  form   Hash that describes how the rendering should be done
 2541: #         and other things.
 2542: # Returns:
 2543: #   Scalar context: The content of the response.
 2544: #   Array context:  2 element list of the content and the full response object.
 2545: #     
 2546: sub ssi {
 2547: 
 2548:     my ($fn,%form)=@_;
 2549:     my $ua=new LWP::UserAgent;
 2550:     my $request;
 2551: 
 2552:     $form{'no_update_last_known'}=1;
 2553:     &Apache::lonenc::check_encrypt(\$fn);
 2554:     if (%form) {
 2555:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 2556:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
 2557:     } else {
 2558:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 2559:     }
 2560: 
 2561:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 2562:     my $response=$ua->request($request);
 2563: 
 2564:     if (wantarray) {
 2565: 	return ($response->content, $response);
 2566:     } else {
 2567: 	return $response->content;
 2568:     }
 2569: }
 2570: 
 2571: sub externalssi {
 2572:     my ($url)=@_;
 2573:     my $ua=new LWP::UserAgent;
 2574:     my $request=new HTTP::Request('GET',$url);
 2575:     my $response=$ua->request($request);
 2576:     if (wantarray) {
 2577:         return ($response->content, $response);
 2578:     } else {
 2579:         return $response->content;
 2580:     }
 2581: }
 2582: 
 2583: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 2584: 
 2585: sub allowuploaded {
 2586:     my ($srcurl,$url)=@_;
 2587:     $url=&clutter(&declutter($url));
 2588:     my $dir=$url;
 2589:     $dir=~s/\/[^\/]+$//;
 2590:     my %httpref=();
 2591:     my $httpurl=&hreflocation('',$url);
 2592:     $httpref{'httpref.'.$httpurl}=$srcurl;
 2593:     &Apache::lonnet::appenv(\%httpref);
 2594: }
 2595: 
 2596: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 2597: # input: action, courseID, current domain, intended
 2598: #        path to file, source of file, instruction to parse file for objects,
 2599: #        ref to hash for embedded objects,
 2600: #        ref to hash for codebase of java objects.
 2601: #        reference to scalar to accommodate mime type determined
 2602: #          from File::MMagic if $parser = parse.
 2603: #
 2604: # output: url to file (if action was uploaddoc), 
 2605: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 2606: #
 2607: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 2608: # course.
 2609: #
 2610: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2611: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 2612: #          course's home server.
 2613: #
 2614: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 2615: #          be copied from $source (current location) to 
 2616: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2617: #         and will then be copied to
 2618: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 2619: #         course's home server.
 2620: #
 2621: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2622: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 2623: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2624: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 2625: #         in course's home server.
 2626: #
 2627: 
 2628: sub process_coursefile {
 2629:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 2630:         $mimetype)=@_;
 2631:     my $fetchresult;
 2632:     my $home=&homeserver($docuname,$docudom);
 2633:     if ($action eq 'propagate') {
 2634:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2635: 			     $home);
 2636:     } else {
 2637:         my $fpath = '';
 2638:         my $fname = $file;
 2639:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 2640:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 2641:         my $filepath = &build_filepath($fpath);
 2642:         if ($action eq 'copy') {
 2643:             if ($source eq '') {
 2644:                 $fetchresult = 'no source file';
 2645:                 return $fetchresult;
 2646:             } else {
 2647:                 my $destination = $filepath.'/'.$fname;
 2648:                 rename($source,$destination);
 2649:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2650:                                  $home);
 2651:             }
 2652:         } elsif ($action eq 'uploaddoc') {
 2653:             open(my $fh,'>'.$filepath.'/'.$fname);
 2654:             print $fh $env{'form.'.$source};
 2655:             close($fh);
 2656:             if ($parser eq 'parse') {
 2657:                 my $mm = new File::MMagic;
 2658:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 2659:                 if ($type eq 'text/html') {
 2660:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 2661:                     unless ($parse_result eq 'ok') {
 2662:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 2663:                     }
 2664:                 }
 2665:                 if (ref($mimetype)) {
 2666:                     $$mimetype = $type;
 2667:                 } 
 2668:             }
 2669:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2670:                                  $home);
 2671:             if ($fetchresult eq 'ok') {
 2672:                 return '/uploaded/'.$fpath.'/'.$fname;
 2673:             } else {
 2674:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2675:                         ' to host '.$home.': '.$fetchresult);
 2676:                 return '/adm/notfound.html';
 2677:             }
 2678:         }
 2679:     }
 2680:     unless ( $fetchresult eq 'ok') {
 2681:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2682:              ' to host '.$home.': '.$fetchresult);
 2683:     }
 2684:     return $fetchresult;
 2685: }
 2686: 
 2687: sub build_filepath {
 2688:     my ($fpath) = @_;
 2689:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 2690:     unless ($fpath eq '') {
 2691:         my @parts=split('/',$fpath);
 2692:         foreach my $part (@parts) {
 2693:             $filepath.= '/'.$part;
 2694:             if ((-e $filepath)!=1) {
 2695:                 mkdir($filepath,0777);
 2696:             }
 2697:         }
 2698:     }
 2699:     return $filepath;
 2700: }
 2701: 
 2702: sub store_edited_file {
 2703:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 2704:     my $file = $primary_url;
 2705:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 2706:     my $fpath = '';
 2707:     my $fname = $file;
 2708:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 2709:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 2710:     my $filepath = &build_filepath($fpath);
 2711:     open(my $fh,'>'.$filepath.'/'.$fname);
 2712:     print $fh $content;
 2713:     close($fh);
 2714:     my $home=&homeserver($docuname,$docudom);
 2715:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2716: 			  $home);
 2717:     if ($$fetchresult eq 'ok') {
 2718:         return '/uploaded/'.$fpath.'/'.$fname;
 2719:     } else {
 2720:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2721: 		 ' to host '.$home.': '.$$fetchresult);
 2722:         return '/adm/notfound.html';
 2723:     }
 2724: }
 2725: 
 2726: sub clean_filename {
 2727:     my ($fname,$args)=@_;
 2728: # Replace Windows backslashes by forward slashes
 2729:     $fname=~s/\\/\//g;
 2730:     if (!$args->{'keep_path'}) {
 2731:         # Get rid of everything but the actual filename
 2732: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 2733:     }
 2734: # Replace spaces by underscores
 2735:     $fname=~s/\s+/\_/g;
 2736: # Replace all other weird characters by nothing
 2737:     $fname=~s{[^/\w\.\-]}{}g;
 2738: # Replace all .\d. sequences with _\d. so they no longer look like version
 2739: # numbers
 2740:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 2741:     return $fname;
 2742: }
 2743: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 2744: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 2745: # image with the same aspect ratio as the original, but with dimensions which do 
 2746: # not exceed $resizewidth and $resizeheight.
 2747:  
 2748: sub resizeImage {
 2749:     my ($img_path,$resizewidth,$resizeheight) = @_;
 2750:     my $ima = Image::Magick->new;
 2751:     my $resized;
 2752:     if (-e $img_path) {
 2753:         $ima->Read($img_path);
 2754:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 2755:             my $width = $ima->Get('width');
 2756:             my $height = $ima->Get('height');
 2757:             if ($width > $resizewidth) {
 2758: 	        my $factor = $width/$resizewidth;
 2759:                 my $newheight = $height/$factor;
 2760:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 2761:                 $resized = 1;
 2762:             }
 2763:         }
 2764:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 2765:             my $width = $ima->Get('width');
 2766:             my $height = $ima->Get('height');
 2767:             if ($height > $resizeheight) {
 2768:                 my $factor = $height/$resizeheight;
 2769:                 my $newwidth = $width/$factor;
 2770:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 2771:                 $resized = 1;
 2772:             }
 2773:         }
 2774:         if ($resized) {
 2775:             $ima->Write($img_path);
 2776:         }
 2777:     }
 2778:     return;
 2779: }
 2780: 
 2781: # --------------- Take an uploaded file and put it into the userfiles directory
 2782: # input: $formname - the contents of the file are in $env{"form.$formname"}
 2783: #                    the desired filename is in $env{"form.$formname.filename"}
 2784: #        $context - possible values: coursedoc, existingfile, overwrite, 
 2785: #                                    canceloverwrite, or ''. 
 2786: #                   if 'coursedoc': upload to the current course
 2787: #                   if 'existingfile': write file to tmp/overwrites directory 
 2788: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 2789: #                   $context is passed as argument to &finishuserfileupload
 2790: #        $subdir - directory in userfile to store the file into
 2791: #        $parser - instruction to parse file for objects ($parser = parse)    
 2792: #        $allfiles - reference to hash for embedded objects
 2793: #        $codebase - reference to hash for codebase of java objects
 2794: #        $desuname - username for permanent storage of uploaded file
 2795: #        $dsetudom - domain for permanaent storage of uploaded file
 2796: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 2797: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 2798: #        $resizewidth - width (pixels) to which to resize uploaded image
 2799: #        $resizeheight - height (pixels) to which to resize uploaded image
 2800: #        $mimetype - reference to scalar to accommodate mime type determined
 2801: #                    from File::MMagic if $parser = parse.
 2802: # 
 2803: # output: url of file in userspace, or error: <message> 
 2804: #             or /adm/notfound.html if failure to upload occurse
 2805: 
 2806: sub userfileupload {
 2807:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 2808:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 2809:     if (!defined($subdir)) { $subdir='unknown'; }
 2810:     my $fname=$env{'form.'.$formname.'.filename'};
 2811:     $fname=&clean_filename($fname);
 2812:     # See if there is anything left
 2813:     unless ($fname) { return 'error: no uploaded file'; }
 2814:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 2815:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 2816:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 2817:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 2818:         my $now = time;
 2819:         my $filepath;
 2820:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 2821:              $filepath = 'tmp/helprequests/'.$now;
 2822:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 2823:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 2824:                          '_'.$env{'user.domain'}.'/pending';
 2825:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 2826:             my ($docuname,$docudom);
 2827:             if ($destudom) {
 2828:                 $docudom = $destudom;
 2829:             } else {
 2830:                 $docudom = $env{'user.domain'};
 2831:             }
 2832:             if ($destuname) {
 2833:                 $docuname = $destuname;
 2834:             } else {
 2835:                 $docuname = $env{'user.name'};
 2836:             }
 2837:             if (exists($env{'form.group'})) {
 2838:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2839:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2840:             }
 2841:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 2842:             if ($context eq 'canceloverwrite') {
 2843:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 2844:                 if (-e  $tempfile) {
 2845:                     my @info = stat($tempfile);
 2846:                     if ($info[9] eq $env{'form.timestamp'}) {
 2847:                         unlink($tempfile);
 2848:                     }
 2849:                 }
 2850:                 return;
 2851:             }
 2852:         }
 2853:         # Create the directory if not present
 2854:         my @parts=split(/\//,$filepath);
 2855:         my $fullpath = $perlvar{'lonDaemons'};
 2856:         for (my $i=0;$i<@parts;$i++) {
 2857:             $fullpath .= '/'.$parts[$i];
 2858:             if ((-e $fullpath)!=1) {
 2859:                 mkdir($fullpath,0777);
 2860:             }
 2861:         }
 2862:         open(my $fh,'>'.$fullpath.'/'.$fname);
 2863:         print $fh $env{'form.'.$formname};
 2864:         close($fh);
 2865:         if ($context eq 'existingfile') {
 2866:             my @info = stat($fullpath.'/'.$fname);
 2867:             return ($fullpath.'/'.$fname,$info[9]);
 2868:         } else {
 2869:             return $fullpath.'/'.$fname;
 2870:         }
 2871:     }
 2872:     if ($subdir eq 'scantron') {
 2873:         $fname = 'scantron_orig_'.$fname;
 2874:     } else {
 2875:         $fname="$subdir/$fname";
 2876:     }
 2877:     if ($context eq 'coursedoc') {
 2878: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2879: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2880:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 2881:             return &finishuserfileupload($docuname,$docudom,
 2882: 					 $formname,$fname,$parser,$allfiles,
 2883: 					 $codebase,$thumbwidth,$thumbheight,
 2884:                                          $resizewidth,$resizeheight,$context,$mimetype);
 2885:         } else {
 2886:             $fname=$env{'form.folder'}.'/'.$fname;
 2887:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 2888: 				       $fname,$formname,$parser,
 2889: 				       $allfiles,$codebase,$mimetype);
 2890:         }
 2891:     } elsif (defined($destuname)) {
 2892:         my $docuname=$destuname;
 2893:         my $docudom=$destudom;
 2894: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 2895: 				     $parser,$allfiles,$codebase,
 2896:                                      $thumbwidth,$thumbheight,
 2897:                                      $resizewidth,$resizeheight,$context,$mimetype);
 2898:     } else {
 2899:         my $docuname=$env{'user.name'};
 2900:         my $docudom=$env{'user.domain'};
 2901:         if (exists($env{'form.group'})) {
 2902:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2903:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2904:         }
 2905: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 2906: 				     $parser,$allfiles,$codebase,
 2907:                                      $thumbwidth,$thumbheight,
 2908:                                      $resizewidth,$resizeheight,$context,$mimetype);
 2909:     }
 2910: }
 2911: 
 2912: sub finishuserfileupload {
 2913:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 2914:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 2915:     my $path=$docudom.'/'.$docuname.'/';
 2916:     my $filepath=$perlvar{'lonDocRoot'};
 2917:   
 2918:     my ($fnamepath,$file,$fetchthumb);
 2919:     $file=$fname;
 2920:     if ($fname=~m|/|) {
 2921:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 2922: 	$path.=$fnamepath.'/';
 2923:     }
 2924:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 2925:     my $count;
 2926:     for ($count=4;$count<=$#parts;$count++) {
 2927:         $filepath.="/$parts[$count]";
 2928:         if ((-e $filepath)!=1) {
 2929: 	    mkdir($filepath,0777);
 2930:         }
 2931:     }
 2932: 
 2933: # Save the file
 2934:     {
 2935: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 2936: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 2937: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 2938: 	    return '/adm/notfound.html';
 2939: 	}
 2940:         if ($context eq 'overwrite') {
 2941:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 2942:             my $target = $filepath.'/'.$file;
 2943:             if (-e $source) {
 2944:                 my @info = stat($source);
 2945:                 if ($info[9] eq $env{'form.timestamp'}) {   
 2946:                     unless (&File::Copy::move($source,$target)) {
 2947:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 2948:                         return "Moving from $source failed";
 2949:                     }
 2950:                 } else {
 2951:                     return "Temporary file: $source had unexpected date/time for last modification";
 2952:                 }
 2953:             } else {
 2954:                 return "Temporary file: $source missing";
 2955:             }
 2956:         } elsif (!print FH ($env{'form.'.$formname})) {
 2957: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 2958: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 2959: 	    return '/adm/notfound.html';
 2960: 	}
 2961: 	close(FH);
 2962:         if ($resizewidth && $resizeheight) {
 2963:             my $mm = new File::MMagic;
 2964:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 2965:             if ($mime_type =~ m{^image/}) {
 2966: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 2967:             }  
 2968: 	}
 2969:     }
 2970:     if ($parser eq 'parse') {
 2971:         my $mm = new File::MMagic;
 2972:         my $type = $mm->checktype_filename($filepath.'/'.$file);
 2973:         if ($type eq 'text/html') {
 2974:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 2975:                                                        $allfiles,$codebase);
 2976:             unless ($parse_result eq 'ok') {
 2977:                 &logthis('Failed to parse '.$filepath.$file.
 2978: 	   	         ' for embedded media: '.$parse_result); 
 2979:             }
 2980:         }
 2981:         if (ref($mimetype)) {
 2982:             $$mimetype = $type;
 2983:         }
 2984:     }
 2985:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 2986:         my $input = $filepath.'/'.$file;
 2987:         my $output = $filepath.'/'.'tn-'.$file;
 2988:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 2989:         system("convert -sample $thumbsize $input $output");
 2990:         if (-e $filepath.'/'.'tn-'.$file) {
 2991:             $fetchthumb  = 1; 
 2992:         }
 2993:     }
 2994:  
 2995: # Notify homeserver to grep it
 2996: #
 2997:     my $docuhome=&homeserver($docuname,$docudom);	
 2998:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 2999:     if ($fetchresult eq 'ok') {
 3000:         if ($fetchthumb) {
 3001:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 3002:             if ($thumbresult ne 'ok') {
 3003:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 3004:                          $docuhome.': '.$thumbresult);
 3005:             }
 3006:         }
 3007: #
 3008: # Return the URL to it
 3009:         return '/uploaded/'.$path.$file;
 3010:     } else {
 3011:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 3012: 		 ': '.$fetchresult);
 3013:         return '/adm/notfound.html';
 3014:     }
 3015: }
 3016: 
 3017: sub extract_embedded_items {
 3018:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 3019:     my @state = ();
 3020:     my %javafiles = (
 3021:                       codebase => '',
 3022:                       code => '',
 3023:                       archive => ''
 3024:                     );
 3025:     my %mediafiles = (
 3026:                       src => '',
 3027:                       movie => '',
 3028:                      );
 3029:     my $p;
 3030:     if ($content) {
 3031:         $p = HTML::LCParser->new($content);
 3032:     } else {
 3033:         $p = HTML::LCParser->new($fullpath);
 3034:     }
 3035:     while (my $t=$p->get_token()) {
 3036: 	if ($t->[0] eq 'S') {
 3037: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 3038: 	    push(@state, $tagname);
 3039:             if (lc($tagname) eq 'allow') {
 3040:                 &add_filetype($allfiles,$attr->{'src'},'src');
 3041:             }
 3042: 	    if (lc($tagname) eq 'img') {
 3043: 		&add_filetype($allfiles,$attr->{'src'},'src');
 3044: 	    }
 3045: 	    if (lc($tagname) eq 'a') {
 3046: 		&add_filetype($allfiles,$attr->{'href'},'href');
 3047: 	    }
 3048:             if (lc($tagname) eq 'script') {
 3049:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 3050:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 3051:                 } else {
 3052:                     &add_filetype($allfiles,$attr->{'src'},'src');
 3053:                 }
 3054:             }
 3055:             if (lc($tagname) eq 'link') {
 3056:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 3057:                     &add_filetype($allfiles,$attr->{'href'},'href');
 3058:                 }
 3059:             }
 3060: 	    if (lc($tagname) eq 'object' ||
 3061: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 3062: 		foreach my $item (keys(%javafiles)) {
 3063: 		    $javafiles{$item} = '';
 3064: 		}
 3065: 	    }
 3066: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 3067: 		my $name = lc($attr->{'name'});
 3068: 		foreach my $item (keys(%javafiles)) {
 3069: 		    if ($name eq $item) {
 3070: 			$javafiles{$item} = $attr->{'value'};
 3071: 			last;
 3072: 		    }
 3073: 		}
 3074: 		foreach my $item (keys(%mediafiles)) {
 3075: 		    if ($name eq $item) {
 3076: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
 3077: 			last;
 3078: 		    }
 3079: 		}
 3080: 	    }
 3081: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 3082: 		foreach my $item (keys(%javafiles)) {
 3083: 		    if ($attr->{$item}) {
 3084: 			$javafiles{$item} = $attr->{$item};
 3085: 			last;
 3086: 		    }
 3087: 		}
 3088: 		foreach my $item (keys(%mediafiles)) {
 3089: 		    if ($attr->{$item}) {
 3090: 			&add_filetype($allfiles,$attr->{$item},$item);
 3091: 			last;
 3092: 		    }
 3093: 		}
 3094: 	    }
 3095: 	} elsif ($t->[0] eq 'E') {
 3096: 	    my ($tagname) = ($t->[1]);
 3097: 	    if ($javafiles{'codebase'} ne '') {
 3098: 		$javafiles{'codebase'} .= '/';
 3099: 	    }  
 3100: 	    if (lc($tagname) eq 'applet' ||
 3101: 		lc($tagname) eq 'object' ||
 3102: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 3103: 		) {
 3104: 		foreach my $item (keys(%javafiles)) {
 3105: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 3106: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 3107: 			&add_filetype($allfiles,$file,$item);
 3108: 		    }
 3109: 		}
 3110: 	    } 
 3111: 	    pop @state;
 3112: 	}
 3113:     }
 3114:     return 'ok';
 3115: }
 3116: 
 3117: sub add_filetype {
 3118:     my ($allfiles,$file,$type)=@_;
 3119:     if (exists($allfiles->{$file})) {
 3120: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 3121: 	    push(@{$allfiles->{$file}}, &escape($type));
 3122: 	}
 3123:     } else {
 3124: 	@{$allfiles->{$file}} = (&escape($type));
 3125:     }
 3126: }
 3127: 
 3128: sub removeuploadedurl {
 3129:     my ($url)=@_;	
 3130:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 3131:     return &removeuserfile($uname,$udom,$fname);
 3132: }
 3133: 
 3134: sub removeuserfile {
 3135:     my ($docuname,$docudom,$fname)=@_;
 3136:     my $home=&homeserver($docuname,$docudom);    
 3137:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 3138:     if ($result eq 'ok') {	
 3139:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 3140:             my $metafile = $fname.'.meta';
 3141:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 3142: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 3143:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 3144:             my $sqlresult = 
 3145:                 &update_portfolio_table($docuname,$docudom,$file,
 3146:                                         'portfolio_metadata',$group,
 3147:                                         'delete');
 3148:         }
 3149:     }
 3150:     return $result;
 3151: }
 3152: 
 3153: sub mkdiruserfile {
 3154:     my ($docuname,$docudom,$dir)=@_;
 3155:     my $home=&homeserver($docuname,$docudom);
 3156:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 3157: }
 3158: 
 3159: sub renameuserfile {
 3160:     my ($docuname,$docudom,$old,$new)=@_;
 3161:     my $home=&homeserver($docuname,$docudom);
 3162:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 3163:                         &escape("$old").':'.&escape("$new"),$home);
 3164:     if ($result eq 'ok') {
 3165:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 3166:             my $oldmeta = $old.'.meta';
 3167:             my $newmeta = $new.'.meta';
 3168:             my $metaresult = 
 3169:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 3170: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 3171:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 3172:             my $sqlresult = 
 3173:                 &update_portfolio_table($docuname,$docudom,$file,
 3174:                                         'portfolio_metadata',$group,
 3175:                                         'delete');
 3176:         }
 3177:     }
 3178:     return $result;
 3179: }
 3180: 
 3181: # ------------------------------------------------------------------------- Log
 3182: 
 3183: sub log {
 3184:     my ($dom,$nam,$hom,$what)=@_;
 3185:     return critical("log:$dom:$nam:$what",$hom);
 3186: }
 3187: 
 3188: # ------------------------------------------------------------------ Course Log
 3189: #
 3190: # This routine flushes several buffers of non-mission-critical nature
 3191: #
 3192: 
 3193: sub flushcourselogs {
 3194:     &logthis('Flushing log buffers');
 3195: #
 3196: # course logs
 3197: # This is a log of all transactions in a course, which can be used
 3198: # for data mining purposes
 3199: #
 3200: # It also collects the courseid database, which lists last transaction
 3201: # times and course titles for all courseids
 3202: #
 3203:     my %courseidbuffer=();
 3204:     foreach my $crsid (keys(%courselogs)) {
 3205:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 3206: 		          &escape($courselogs{$crsid}),
 3207: 		          $coursehombuf{$crsid}) eq 'ok') {
 3208: 	    delete $courselogs{$crsid};
 3209:         } else {
 3210:             &logthis('Failed to flush log buffer for '.$crsid);
 3211:             if (length($courselogs{$crsid})>40000) {
 3212:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 3213:                         " exceeded maximum size, deleting.</font>");
 3214:                delete $courselogs{$crsid};
 3215:             }
 3216:         }
 3217:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 3218:             'description' => $coursedescrbuf{$crsid},
 3219:             'inst_code'    => $courseinstcodebuf{$crsid},
 3220:             'type'        => $coursetypebuf{$crsid},
 3221:             'owner'       => $courseownerbuf{$crsid},
 3222:         };
 3223:     }
 3224: #
 3225: # Write course id database (reverse lookup) to homeserver of courses 
 3226: # Is used in pickcourse
 3227: #
 3228:     foreach my $crs_home (keys(%courseidbuffer)) {
 3229:         my $response = &courseidput(&host_domain($crs_home),
 3230:                                     $courseidbuffer{$crs_home},
 3231:                                     $crs_home,'timeonly');
 3232:     }
 3233: #
 3234: # File accesses
 3235: # Writes to the dynamic metadata of resources to get hit counts, etc.
 3236: #
 3237:     foreach my $entry (keys(%accesshash)) {
 3238:         if ($entry =~ /___count$/) {
 3239:             my ($dom,$name);
 3240:             ($dom,$name,undef)=
 3241: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 3242:             if (! defined($dom) || $dom eq '' || 
 3243:                 ! defined($name) || $name eq '') {
 3244:                 my $cid = $env{'request.course.id'};
 3245:                 $dom  = $env{'request.'.$cid.'.domain'};
 3246:                 $name = $env{'request.'.$cid.'.num'};
 3247:             }
 3248:             my $value = $accesshash{$entry};
 3249:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 3250:             my %temphash=($url => $value);
 3251:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 3252:             if ($result eq 'ok') {
 3253:                 delete $accesshash{$entry};
 3254:             } elsif ($result eq 'unknown_cmd') {
 3255:                 # Target server has old code running on it.
 3256:                 my %temphash=($entry => $value);
 3257:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 3258:                     delete $accesshash{$entry};
 3259:                 }
 3260:             }
 3261:         } else {
 3262:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 3263:             my %temphash=($entry => $accesshash{$entry});
 3264:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 3265:                 delete $accesshash{$entry};
 3266:             }
 3267:         }
 3268:     }
 3269: #
 3270: # Roles
 3271: # Reverse lookup of user roles for course faculty/staff and co-authorship
 3272: #
 3273:     foreach my $entry (keys(%userrolehash)) {
 3274:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 3275: 	    split(/\:/,$entry);
 3276:         if (&Apache::lonnet::put('nohist_userroles',
 3277:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 3278:                 $rudom,$runame) eq 'ok') {
 3279: 	    delete $userrolehash{$entry};
 3280:         }
 3281:     }
 3282: #
 3283: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 3284: #
 3285:     my %domrolebuffer = ();
 3286:     foreach my $entry (keys(%domainrolehash)) {
 3287:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 3288:         if ($domrolebuffer{$rudom}) {
 3289:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 3290:                       '='.&escape($domainrolehash{$entry});
 3291:         } else {
 3292:             $domrolebuffer{$rudom}.=&escape($entry).
 3293:                       '='.&escape($domainrolehash{$entry});
 3294:         }
 3295:         delete $domainrolehash{$entry};
 3296:     }
 3297:     foreach my $dom (keys(%domrolebuffer)) {
 3298: 	my %servers = &get_servers($dom,'library');
 3299: 	foreach my $tryserver (keys(%servers)) {
 3300: 	    unless (&reply('domroleput:'.$dom.':'.
 3301: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 3302: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 3303: 	    }
 3304:         }
 3305:     }
 3306:     $dumpcount++;
 3307: }
 3308: 
 3309: sub courselog {
 3310:     my $what=shift;
 3311:     $what=time.':'.$what;
 3312:     unless ($env{'request.course.id'}) { return ''; }
 3313:     $coursedombuf{$env{'request.course.id'}}=
 3314:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 3315:     $coursenumbuf{$env{'request.course.id'}}=
 3316:        $env{'course.'.$env{'request.course.id'}.'.num'};
 3317:     $coursehombuf{$env{'request.course.id'}}=
 3318:        $env{'course.'.$env{'request.course.id'}.'.home'};
 3319:     $coursedescrbuf{$env{'request.course.id'}}=
 3320:        $env{'course.'.$env{'request.course.id'}.'.description'};
 3321:     $courseinstcodebuf{$env{'request.course.id'}}=
 3322:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 3323:     $courseownerbuf{$env{'request.course.id'}}=
 3324:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 3325:     $coursetypebuf{$env{'request.course.id'}}=
 3326:        $env{'course.'.$env{'request.course.id'}.'.type'};
 3327:     if (defined $courselogs{$env{'request.course.id'}}) {
 3328: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 3329:     } else {
 3330: 	$courselogs{$env{'request.course.id'}}.=$what;
 3331:     }
 3332:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 3333: 	&flushcourselogs();
 3334:     }
 3335: }
 3336: 
 3337: sub courseacclog {
 3338:     my $fnsymb=shift;
 3339:     unless ($env{'request.course.id'}) { return ''; }
 3340:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 3341:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 3342:         $what.=':POST';
 3343:         # FIXME: Probably ought to escape things....
 3344: 	foreach my $key (keys(%env)) {
 3345:             if ($key=~/^form\.(.*)/) {
 3346:                 my $formitem = $1;
 3347:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 3348:                     $what.=':'.$formitem.'='.$env{$key};
 3349:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 3350:                     $what.=':'.$formitem.'='.$env{$key};
 3351:                 }
 3352:             }
 3353:         }
 3354:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 3355:         # FIXME: We should not be depending on a form parameter that someone
 3356:         # editing lonsearchcat.pm might change in the future.
 3357:         if ($env{'form.phase'} eq 'course_search') {
 3358:             $what.= ':POST';
 3359:             # FIXME: Probably ought to escape things....
 3360:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 3361:                                  'crsdiscuss') {
 3362:                 $what.=':'.$element.'='.$env{'form.'.$element};
 3363:             }
 3364:         }
 3365:     }
 3366:     &courselog($what);
 3367: }
 3368: 
 3369: sub countacc {
 3370:     my $url=&declutter(shift);
 3371:     return if (! defined($url) || $url eq '');
 3372:     unless ($env{'request.course.id'}) { return ''; }
 3373:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 3374:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 3375:     $accesshash{$key}++;
 3376: }
 3377: 
 3378: sub linklog {
 3379:     my ($from,$to)=@_;
 3380:     $from=&declutter($from);
 3381:     $to=&declutter($to);
 3382:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 3383:     $accesshash{$to.'___'.$from.'___goto'}=1;
 3384: }
 3385:   
 3386: sub userrolelog {
 3387:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 3388:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
 3389:         ($trole=~/^in/) || ($trole=~/^cc/) ||
 3390:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
 3391:         ($trole=~/^ta/) || ($trole=~/^co/)) {
 3392:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 3393:        $userrolehash
 3394:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 3395:                     =$tend.':'.$tstart;
 3396:     }
 3397:     if (($env{'request.role'} =~ /dc\./) &&
 3398: 	(($trole=~/^au/) || ($trole=~/^in/) ||
 3399: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
 3400: 	 ($trole=~/^cr/) || ($trole=~/^ta/) ||
 3401:          ($trole=~/^co/))) {
 3402:        $userrolehash
 3403:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 3404:                     =$tend.':'.$tstart;
 3405:     }
 3406:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
 3407:         ($trole=~/^li/) || ($trole=~/^li/) ||
 3408:         ($trole=~/^au/) || ($trole=~/^dg/) ||
 3409:         ($trole=~/^sc/)) {
 3410:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 3411:        $domainrolehash
 3412:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 3413:                     = $tend.':'.$tstart;
 3414:     }
 3415: }
 3416: 
 3417: sub courserolelog {
 3418:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 3419:     if (($trole eq 'cc') || ($trole eq 'in') ||
 3420:         ($trole eq 'ep') || ($trole eq 'ad') ||
 3421:         ($trole eq 'ta') || ($trole eq 'st') ||
 3422:         ($trole=~/^cr/) || ($trole eq 'gr') ||
 3423:         ($trole eq 'co')) {
 3424:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 3425:             my $cdom = $1;
 3426:             my $cnum = $2;
 3427:             my $sec = $3;
 3428:             my $namespace = 'rolelog';
 3429:             my %storehash = (
 3430:                                role    => $trole,
 3431:                                start   => $tstart,
 3432:                                end     => $tend,
 3433:                                selfenroll => $selfenroll,
 3434:                                context    => $context,
 3435:                             );
 3436:             if ($trole eq 'gr') {
 3437:                 $namespace = 'groupslog';
 3438:                 $storehash{'group'} = $sec;
 3439:             } else {
 3440:                 $storehash{'section'} = $sec;
 3441:             }
 3442:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
 3443:             if (($trole ne 'st') || ($sec ne '')) {
 3444:                 &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 3445:             }
 3446:         }
 3447:     }
 3448:     return;
 3449: }
 3450: 
 3451: sub get_course_adv_roles {
 3452:     my ($cid,$codes) = @_;
 3453:     $cid=$env{'request.course.id'} unless (defined($cid));
 3454:     my %coursehash=&coursedescription($cid);
 3455:     my $crstype = &Apache::loncommon::course_type($cid);
 3456:     my %nothide=();
 3457:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3458:         if ($user !~ /:/) {
 3459: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 3460:         } else {
 3461:             $nothide{$user}=1;
 3462:         }
 3463:     }
 3464:     my %returnhash=();
 3465:     my %dumphash=
 3466:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 3467:     my $now=time;
 3468:     my %privileged;
 3469:     foreach my $entry (keys(%dumphash)) {
 3470: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 3471:         if (($tstart) && ($tstart<0)) { next; }
 3472:         if (($tend) && ($tend<$now)) { next; }
 3473:         if (($tstart) && ($now<$tstart)) { next; }
 3474:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 3475: 	if ($username eq '' || $domain eq '') { next; }
 3476:         unless (ref($privileged{$domain}) eq 'HASH') {
 3477:             my %dompersonnel =
 3478:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
 3479:             $privileged{$domain} = {};
 3480:             foreach my $server (keys(%dompersonnel)) {
 3481:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 3482:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
 3483:                         my ($trole,$uname,$udom) = split(/:/,$user);
 3484:                         $privileged{$udom}{$uname} = 1;
 3485:                     }
 3486:                 }
 3487:             }
 3488:         }
 3489:         if ((exists($privileged{$domain}{$username})) && 
 3490:             (!$nothide{$username.':'.$domain})) { next; }
 3491: 	if ($role eq 'cr') { next; }
 3492:         if ($codes) {
 3493:             if ($section) { $role .= ':'.$section; }
 3494:             if ($returnhash{$role}) {
 3495:                 $returnhash{$role}.=','.$username.':'.$domain;
 3496:             } else {
 3497:                 $returnhash{$role}=$username.':'.$domain;
 3498:             }
 3499:         } else {
 3500:             my $key=&plaintext($role,$crstype);
 3501:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 3502:             if ($returnhash{$key}) {
 3503: 	        $returnhash{$key}.=','.$username.':'.$domain;
 3504:             } else {
 3505:                 $returnhash{$key}=$username.':'.$domain;
 3506:             }
 3507:         }
 3508:     }
 3509:     return %returnhash;
 3510: }
 3511: 
 3512: sub get_my_roles {
 3513:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 3514:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 3515:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 3516:     my (%dumphash,%nothide);
 3517:     if ($context eq 'userroles') {
 3518:         my $extra = &freeze_escape({'skipcheck' => 1});
 3519:         %dumphash = &dump('roles',$udom,$uname,'.',undef,$extra);
 3520:     } else {
 3521:         %dumphash=
 3522:             &dump('nohist_userroles',$udom,$uname);
 3523:         if ($hidepriv) {
 3524:             my %coursehash=&coursedescription($udom.'_'.$uname);
 3525:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3526:                 if ($user !~ /:/) {
 3527:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 3528:                 } else {
 3529:                     $nothide{$user} = 1;
 3530:                 }
 3531:             }
 3532:         }
 3533:     }
 3534:     my %returnhash=();
 3535:     my $now=time;
 3536:     my %privileged;
 3537:     foreach my $entry (keys(%dumphash)) {
 3538:         my ($role,$tend,$tstart);
 3539:         if ($context eq 'userroles') {
 3540: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 3541:         } else {
 3542:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 3543:         }
 3544:         if (($tstart) && ($tstart<0)) { next; }
 3545:         my $status = 'active';
 3546:         if (($tend) && ($tend<=$now)) {
 3547:             $status = 'previous';
 3548:         } 
 3549:         if (($tstart) && ($now<$tstart)) {
 3550:             $status = 'future';
 3551:         }
 3552:         if (ref($types) eq 'ARRAY') {
 3553:             if (!grep(/^\Q$status\E$/,@{$types})) {
 3554:                 next;
 3555:             } 
 3556:         } else {
 3557:             if ($status ne 'active') {
 3558:                 next;
 3559:             }
 3560:         }
 3561:         my ($rolecode,$username,$domain,$section,$area);
 3562:         if ($context eq 'userroles') {
 3563:             ($area,$rolecode) = split(/_/,$entry);
 3564:             (undef,$domain,$username,$section) = split(/\//,$area);
 3565:         } else {
 3566:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 3567:         }
 3568:         if (ref($roledoms) eq 'ARRAY') {
 3569:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 3570:                 next;
 3571:             }
 3572:         }
 3573:         if (ref($roles) eq 'ARRAY') {
 3574:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 3575:                 if ($role =~ /^cr\//) {
 3576:                     if (!grep(/^cr$/,@{$roles})) {
 3577:                         next;
 3578:                     }
 3579:                 } elsif ($role =~ /^gr\//) {
 3580:                     if (!grep(/^gr$/,@{$roles})) {
 3581:                         next;
 3582:                     }
 3583:                 } else {
 3584:                     next;
 3585:                 }
 3586:             }
 3587:         }
 3588:         if ($hidepriv) {
 3589:             if ($context eq 'userroles') {
 3590:                 if ((&privileged($username,$domain)) &&
 3591:                     (!$nothide{$username.':'.$domain})) {
 3592:                     next;
 3593:                 }
 3594:             } else {
 3595:                 unless (ref($privileged{$domain}) eq 'HASH') {
 3596:                     my %dompersonnel =
 3597:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
 3598:                     $privileged{$domain} = {};
 3599:                     if (keys(%dompersonnel)) {
 3600:                         foreach my $server (keys(%dompersonnel)) {
 3601:                             if (ref($dompersonnel{$server}) eq 'HASH') {
 3602:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
 3603:                                     my ($trole,$uname,$udom) = split(/:/,$user);
 3604:                                     $privileged{$udom}{$uname} = $trole;
 3605:                                 }
 3606:                             }
 3607:                         }
 3608:                     }
 3609:                 }
 3610:                 if (exists($privileged{$domain}{$username})) {
 3611:                     if (!$nothide{$username.':'.$domain}) {
 3612:                         next;
 3613:                     }
 3614:                 }
 3615:             }
 3616:         }
 3617:         if ($withsec) {
 3618:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 3619:                 $tstart.':'.$tend;
 3620:         } else {
 3621:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 3622:         }
 3623:     }
 3624:     return %returnhash;
 3625: }
 3626: 
 3627: # ----------------------------------------------------- Frontpage Announcements
 3628: #
 3629: #
 3630: 
 3631: sub postannounce {
 3632:     my ($server,$text)=@_;
 3633:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 3634:     unless ($text=~/\w/) { $text=''; }
 3635:     return &reply('setannounce:'.&escape($text),$server);
 3636: }
 3637: 
 3638: sub getannounce {
 3639: 
 3640:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 3641: 	my $announcement='';
 3642: 	while (my $line = <$fh>) { $announcement .= $line; }
 3643: 	close($fh);
 3644: 	if ($announcement=~/\w/) { 
 3645: 	    return 
 3646:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 3647:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 3648: 	} else {
 3649: 	    return '';
 3650: 	}
 3651:     } else {
 3652: 	return '';
 3653:     }
 3654: }
 3655: 
 3656: # ---------------------------------------------------------- Course ID routines
 3657: # Deal with domain's nohist_courseid.db files
 3658: #
 3659: 
 3660: sub courseidput {
 3661:     my ($domain,$storehash,$coursehome,$caller) = @_;
 3662:     return unless (ref($storehash) eq 'HASH');
 3663:     my $outcome;
 3664:     if ($caller eq 'timeonly') {
 3665:         my $cids = '';
 3666:         foreach my $item (keys(%$storehash)) {
 3667:             $cids.=&escape($item).'&';
 3668:         }
 3669:         $cids=~s/\&$//;
 3670:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 3671:                           $coursehome);       
 3672:     } else {
 3673:         my $items = '';
 3674:         foreach my $item (keys(%$storehash)) {
 3675:             $items.= &escape($item).'='.
 3676:                      &freeze_escape($$storehash{$item}).'&';
 3677:         }
 3678:         $items=~s/\&$//;
 3679:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 3680:                           $coursehome);
 3681:     }
 3682:     if ($outcome eq 'unknown_cmd') {
 3683:         my $what;
 3684:         foreach my $cid (keys(%$storehash)) {
 3685:             $what .= &escape($cid).'=';
 3686:             foreach my $item ('description','inst_code','owner','type') {
 3687:                 $what .= &escape($storehash->{$cid}{$item}).':';
 3688:             }
 3689:             $what =~ s/\:$/&/;
 3690:         }
 3691:         $what =~ s/\&$//;  
 3692:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 3693:     } else {
 3694:         return $outcome;
 3695:     }
 3696: }
 3697: 
 3698: sub courseiddump {
 3699:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 3700:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 3701:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 3702:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
 3703:     my $as_hash = 1;
 3704:     my %returnhash;
 3705:     if (!$domfilter) { $domfilter=''; }
 3706:     my %libserv = &all_library();
 3707:     foreach my $tryserver (keys(%libserv)) {
 3708:         if ( (  $hostidflag == 1 
 3709: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 3710: 	     || (!defined($hostidflag)) ) {
 3711: 
 3712: 	    if (($domfilter eq '') ||
 3713: 		(&host_domain($tryserver) eq $domfilter)) {
 3714:                 my $rep = 
 3715:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
 3716:                          $sincefilter.':'.&escape($descfilter).':'.
 3717:                          &escape($instcodefilter).':'.&escape($ownerfilter).
 3718:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
 3719:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
 3720:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
 3721:                          $showhidden.':'.$caller.':'.&escape($cloner).':'.
 3722:                          &escape($cc_clone).':'.$cloneonly.':'.
 3723:                          &escape($createdbefore).':'.&escape($createdafter).':'.
 3724:                          &escape($creationcontext).':'.$domcloner,
 3725:                          $tryserver);
 3726:                 my @pairs=split(/\&/,$rep);
 3727:                 foreach my $item (@pairs) {
 3728:                     my ($key,$value)=split(/\=/,$item,2);
 3729:                     $key = &unescape($key);
 3730:                     next if ($key =~ /^error: 2 /);
 3731:                     my $result = &thaw_unescape($value);
 3732:                     if (ref($result) eq 'HASH') {
 3733:                         $returnhash{$key}=$result;
 3734:                     } else {
 3735:                         my @responses = split(/:/,$value);
 3736:                         my @items = ('description','inst_code','owner','type');
 3737:                         for (my $i=0; $i<@responses; $i++) {
 3738:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 3739:                         }
 3740:                     }
 3741:                 }
 3742:             }
 3743:         }
 3744:     }
 3745:     return %returnhash;
 3746: }
 3747: 
 3748: sub courselastaccess {
 3749:     my ($cdom,$cnum,$hostidref) = @_;
 3750:     my %returnhash;
 3751:     if ($cdom && $cnum) {
 3752:         my $chome = &homeserver($cnum,$cdom);
 3753:         if ($chome ne 'no_host') {
 3754:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 3755:             &extract_lastaccess(\%returnhash,$rep);
 3756:         }
 3757:     } else {
 3758:         if (!$cdom) { $cdom=''; }
 3759:         my %libserv = &all_library();
 3760:         foreach my $tryserver (keys(%libserv)) {
 3761:             if (ref($hostidref) eq 'ARRAY') {
 3762:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 3763:             } 
 3764:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 3765:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 3766:                 &extract_lastaccess(\%returnhash,$rep);
 3767:             }
 3768:         }
 3769:     }
 3770:     return %returnhash;
 3771: }
 3772: 
 3773: sub extract_lastaccess {
 3774:     my ($returnhash,$rep) = @_;
 3775:     if (ref($returnhash) eq 'HASH') {
 3776:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 3777:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 3778:                  $rep eq '') {
 3779:             my @pairs=split(/\&/,$rep);
 3780:             foreach my $item (@pairs) {
 3781:                 my ($key,$value)=split(/\=/,$item,2);
 3782:                 $key = &unescape($key);
 3783:                 next if ($key =~ /^error: 2 /);
 3784:                 $returnhash->{$key} = &thaw_unescape($value);
 3785:             }
 3786:         }
 3787:     }
 3788:     return;
 3789: }
 3790: 
 3791: # ---------------------------------------------------------- DC e-mail
 3792: 
 3793: sub dcmailput {
 3794:     my ($domain,$msgid,$message,$server)=@_;
 3795:     my $status = &Apache::lonnet::critical(
 3796:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 3797:        &escape($message),$server);
 3798:     return $status;
 3799: }
 3800: 
 3801: sub dcmaildump {
 3802:     my ($dom,$startdate,$enddate,$senders) = @_;
 3803:     my %returnhash=();
 3804: 
 3805:     if (defined(&domain($dom,'primary'))) {
 3806:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 3807:                                                          &escape($enddate).':';
 3808: 	my @esc_senders=map { &escape($_)} @$senders;
 3809: 	$cmd.=&escape(join('&',@esc_senders));
 3810: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 3811:             my ($key,$value) = split(/\=/,$line,2);
 3812:             if (($key) && ($value)) {
 3813:                 $returnhash{&unescape($key)} = &unescape($value);
 3814:             }
 3815:         }
 3816:     }
 3817:     return %returnhash;
 3818: }
 3819: # ---------------------------------------------------------- Domain roles
 3820: 
 3821: sub get_domain_roles {
 3822:     my ($dom,$roles,$startdate,$enddate)=@_;
 3823:     if ((!defined($startdate)) || ($startdate eq '')) {
 3824:         $startdate = '.';
 3825:     }
 3826:     if ((!defined($enddate)) || ($enddate eq '')) {
 3827:         $enddate = '.';
 3828:     }
 3829:     my $rolelist;
 3830:     if (ref($roles) eq 'ARRAY') {
 3831:         $rolelist = join(':',@{$roles});
 3832:     }
 3833:     my %personnel = ();
 3834: 
 3835:     my %servers = &get_servers($dom,'library');
 3836:     foreach my $tryserver (keys(%servers)) {
 3837: 	%{$personnel{$tryserver}}=();
 3838: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 3839: 					    &escape($startdate).':'.
 3840: 					    &escape($enddate).':'.
 3841: 					    &escape($rolelist), $tryserver))) {
 3842: 	    my ($key,$value) = split(/\=/,$line,2);
 3843: 	    if (($key) && ($value)) {
 3844: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 3845: 	    }
 3846: 	}
 3847:     }
 3848:     return %personnel;
 3849: }
 3850: 
 3851: # ----------------------------------------------------------- Interval timing 
 3852: 
 3853: sub get_first_access {
 3854:     my ($type,$argsymb)=@_;
 3855:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 3856:     if ($argsymb) { $symb=$argsymb; }
 3857:     my ($map,$id,$res)=&decode_symb($symb);
 3858:     if ($type eq 'course') {
 3859: 	$res='course';
 3860:     } elsif ($type eq 'map') {
 3861: 	$res=&symbread($map);
 3862:     } else {
 3863: 	$res=$symb;
 3864:     }
 3865:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
 3866:     return $times{"$courseid\0$res"};
 3867: }
 3868: 
 3869: sub set_first_access {
 3870:     my ($type)=@_;
 3871:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 3872:     my ($map,$id,$res)=&decode_symb($symb);
 3873:     if ($type eq 'course') {
 3874: 	$res='course';
 3875:     } elsif ($type eq 'map') {
 3876: 	$res=&symbread($map);
 3877:     } else {
 3878: 	$res=$symb;
 3879:     }
 3880:     my $firstaccess=&get_first_access($type,$symb);
 3881:     if (!$firstaccess) {
 3882: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
 3883:     }
 3884:     return 'already_set';
 3885: }
 3886: 
 3887: # --------------------------------------------- Set Expire Date for Spreadsheet
 3888: 
 3889: sub expirespread {
 3890:     my ($uname,$udom,$stype,$usymb)=@_;
 3891:     my $cid=$env{'request.course.id'}; 
 3892:     if ($cid) {
 3893:        my $now=time;
 3894:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 3895:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 3896:                             $env{'course.'.$cid.'.num'}.
 3897: 	        	    ':nohist_expirationdates:'.
 3898:                             &escape($key).'='.$now,
 3899:                             $env{'course.'.$cid.'.home'})
 3900:     }
 3901:     return 'ok';
 3902: }
 3903: 
 3904: # ----------------------------------------------------- Devalidate Spreadsheets
 3905: 
 3906: sub devalidate {
 3907:     my ($symb,$uname,$udom)=@_;
 3908:     my $cid=$env{'request.course.id'}; 
 3909:     if ($cid) {
 3910:         # delete the stored spreadsheets for
 3911:         # - the student level sheet of this user in course's homespace
 3912:         # - the assessment level sheet for this resource 
 3913:         #   for this user in user's homespace
 3914: 	# - current conditional state info
 3915: 	my $key=$uname.':'.$udom.':';
 3916:         my $status=
 3917: 	    &del('nohist_calculatedsheets',
 3918: 		 [$key.'studentcalc:'],
 3919: 		 $env{'course.'.$cid.'.domain'},
 3920: 		 $env{'course.'.$cid.'.num'})
 3921: 		.' '.
 3922: 	    &del('nohist_calculatedsheets_'.$cid,
 3923: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 3924:         unless ($status eq 'ok ok') {
 3925:            &logthis('Could not devalidate spreadsheet '.
 3926:                     $uname.' at '.$udom.' for '.
 3927: 		    $symb.': '.$status);
 3928:         }
 3929: 	&delenv('user.state.'.$cid);
 3930:     }
 3931: }
 3932: 
 3933: sub get_scalar {
 3934:     my ($string,$end) = @_;
 3935:     my $value;
 3936:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 3937: 	$value = $1;
 3938:     } elsif ($$string =~ s/^([^&]*?)&//) {
 3939: 	$value = $1;
 3940:     }
 3941:     return &unescape($value);
 3942: }
 3943: 
 3944: sub array2str {
 3945:   my (@array) = @_;
 3946:   my $result=&arrayref2str(\@array);
 3947:   $result=~s/^__ARRAY_REF__//;
 3948:   $result=~s/__END_ARRAY_REF__$//;
 3949:   return $result;
 3950: }
 3951: 
 3952: sub arrayref2str {
 3953:   my ($arrayref) = @_;
 3954:   my $result='__ARRAY_REF__';
 3955:   foreach my $elem (@$arrayref) {
 3956:     if(ref($elem) eq 'ARRAY') {
 3957:       $result.=&arrayref2str($elem).'&';
 3958:     } elsif(ref($elem) eq 'HASH') {
 3959:       $result.=&hashref2str($elem).'&';
 3960:     } elsif(ref($elem)) {
 3961:       #print("Got a ref of ".(ref($elem))." skipping.");
 3962:     } else {
 3963:       $result.=&escape($elem).'&';
 3964:     }
 3965:   }
 3966:   $result=~s/\&$//;
 3967:   $result .= '__END_ARRAY_REF__';
 3968:   return $result;
 3969: }
 3970: 
 3971: sub hash2str {
 3972:   my (%hash) = @_;
 3973:   my $result=&hashref2str(\%hash);
 3974:   $result=~s/^__HASH_REF__//;
 3975:   $result=~s/__END_HASH_REF__$//;
 3976:   return $result;
 3977: }
 3978: 
 3979: sub hashref2str {
 3980:   my ($hashref)=@_;
 3981:   my $result='__HASH_REF__';
 3982:   foreach my $key (sort(keys(%$hashref))) {
 3983:     if (ref($key) eq 'ARRAY') {
 3984:       $result.=&arrayref2str($key).'=';
 3985:     } elsif (ref($key) eq 'HASH') {
 3986:       $result.=&hashref2str($key).'=';
 3987:     } elsif (ref($key)) {
 3988:       $result.='=';
 3989:       #print("Got a ref of ".(ref($key))." skipping.");
 3990:     } else {
 3991: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 3992:     }
 3993: 
 3994:     if(ref($hashref->{$key}) eq 'ARRAY') {
 3995:       $result.=&arrayref2str($hashref->{$key}).'&';
 3996:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 3997:       $result.=&hashref2str($hashref->{$key}).'&';
 3998:     } elsif(ref($hashref->{$key})) {
 3999:        $result.='&';
 4000:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 4001:     } else {
 4002:       $result.=&escape($hashref->{$key}).'&';
 4003:     }
 4004:   }
 4005:   $result=~s/\&$//;
 4006:   $result .= '__END_HASH_REF__';
 4007:   return $result;
 4008: }
 4009: 
 4010: sub str2hash {
 4011:     my ($string)=@_;
 4012:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 4013:     return %$hash;
 4014: }
 4015: 
 4016: sub str2hashref {
 4017:   my ($string) = @_;
 4018: 
 4019:   my %hash;
 4020: 
 4021:   if($string !~ /^__HASH_REF__/) {
 4022:       if (! ($string eq '' || !defined($string))) {
 4023: 	  $hash{'error'}='Not hash reference';
 4024:       }
 4025:       return (\%hash, $string);
 4026:   }
 4027: 
 4028:   $string =~ s/^__HASH_REF__//;
 4029: 
 4030:   while($string !~ /^__END_HASH_REF__/) {
 4031:       #key
 4032:       my $key='';
 4033:       if($string =~ /^__HASH_REF__/) {
 4034:           ($key, $string)=&str2hashref($string);
 4035:           if(defined($key->{'error'})) {
 4036:               $hash{'error'}='Bad data';
 4037:               return (\%hash, $string);
 4038:           }
 4039:       } elsif($string =~ /^__ARRAY_REF__/) {
 4040:           ($key, $string)=&str2arrayref($string);
 4041:           if($key->[0] eq 'Array reference error') {
 4042:               $hash{'error'}='Bad data';
 4043:               return (\%hash, $string);
 4044:           }
 4045:       } else {
 4046:           $string =~ s/^(.*?)=//;
 4047: 	  $key=&unescape($1);
 4048:       }
 4049:       $string =~ s/^=//;
 4050: 
 4051:       #value
 4052:       my $value='';
 4053:       if($string =~ /^__HASH_REF__/) {
 4054:           ($value, $string)=&str2hashref($string);
 4055:           if(defined($value->{'error'})) {
 4056:               $hash{'error'}='Bad data';
 4057:               return (\%hash, $string);
 4058:           }
 4059:       } elsif($string =~ /^__ARRAY_REF__/) {
 4060:           ($value, $string)=&str2arrayref($string);
 4061:           if($value->[0] eq 'Array reference error') {
 4062:               $hash{'error'}='Bad data';
 4063:               return (\%hash, $string);
 4064:           }
 4065:       } else {
 4066: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 4067:       }
 4068:       $string =~ s/^&//;
 4069: 
 4070:       $hash{$key}=$value;
 4071:   }
 4072: 
 4073:   $string =~ s/^__END_HASH_REF__//;
 4074: 
 4075:   return (\%hash, $string);
 4076: }
 4077: 
 4078: sub str2array {
 4079:     my ($string)=@_;
 4080:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 4081:     return @$array;
 4082: }
 4083: 
 4084: sub str2arrayref {
 4085:   my ($string) = @_;
 4086:   my @array;
 4087: 
 4088:   if($string !~ /^__ARRAY_REF__/) {
 4089:       if (! ($string eq '' || !defined($string))) {
 4090: 	  $array[0]='Array reference error';
 4091:       }
 4092:       return (\@array, $string);
 4093:   }
 4094: 
 4095:   $string =~ s/^__ARRAY_REF__//;
 4096: 
 4097:   while($string !~ /^__END_ARRAY_REF__/) {
 4098:       my $value='';
 4099:       if($string =~ /^__HASH_REF__/) {
 4100:           ($value, $string)=&str2hashref($string);
 4101:           if(defined($value->{'error'})) {
 4102:               $array[0] ='Array reference error';
 4103:               return (\@array, $string);
 4104:           }
 4105:       } elsif($string =~ /^__ARRAY_REF__/) {
 4106:           ($value, $string)=&str2arrayref($string);
 4107:           if($value->[0] eq 'Array reference error') {
 4108:               $array[0] ='Array reference error';
 4109:               return (\@array, $string);
 4110:           }
 4111:       } else {
 4112: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 4113:       }
 4114:       $string =~ s/^&//;
 4115: 
 4116:       push(@array, $value);
 4117:   }
 4118: 
 4119:   $string =~ s/^__END_ARRAY_REF__//;
 4120: 
 4121:   return (\@array, $string);
 4122: }
 4123: 
 4124: # -------------------------------------------------------------------Temp Store
 4125: 
 4126: sub tmpreset {
 4127:   my ($symb,$namespace,$domain,$stuname) = @_;
 4128:   if (!$symb) {
 4129:     $symb=&symbread();
 4130:     if (!$symb) { $symb= $env{'request.url'}; }
 4131:   }
 4132:   $symb=escape($symb);
 4133: 
 4134:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4135:   $namespace=~s/\//\_/g;
 4136:   $namespace=~s/\W//g;
 4137: 
 4138:   if (!$domain) { $domain=$env{'user.domain'}; }
 4139:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4140:   if ($domain eq 'public' && $stuname eq 'public') {
 4141:       $stuname=$ENV{'REMOTE_ADDR'};
 4142:   }
 4143:   my $path=LONCAPA::tempdir();
 4144:   my %hash;
 4145:   if (tie(%hash,'GDBM_File',
 4146: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4147: 	  &GDBM_WRCREAT(),0640)) {
 4148:     foreach my $key (keys(%hash)) {
 4149:       if ($key=~ /:$symb/) {
 4150: 	delete($hash{$key});
 4151:       }
 4152:     }
 4153:   }
 4154: }
 4155: 
 4156: sub tmpstore {
 4157:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4158: 
 4159:   if (!$symb) {
 4160:     $symb=&symbread();
 4161:     if (!$symb) { $symb= $env{'request.url'}; }
 4162:   }
 4163:   $symb=escape($symb);
 4164: 
 4165:   if (!$namespace) {
 4166:     # I don't think we would ever want to store this for a course.
 4167:     # it seems this will only be used if we don't have a course.
 4168:     #$namespace=$env{'request.course.id'};
 4169:     #if (!$namespace) {
 4170:       $namespace=$env{'request.state'};
 4171:     #}
 4172:   }
 4173:   $namespace=~s/\//\_/g;
 4174:   $namespace=~s/\W//g;
 4175:   if (!$domain) { $domain=$env{'user.domain'}; }
 4176:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4177:   if ($domain eq 'public' && $stuname eq 'public') {
 4178:       $stuname=$ENV{'REMOTE_ADDR'};
 4179:   }
 4180:   my $now=time;
 4181:   my %hash;
 4182:   my $path=LONCAPA::tempdir();
 4183:   if (tie(%hash,'GDBM_File',
 4184: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4185: 	  &GDBM_WRCREAT(),0640)) {
 4186:     $hash{"version:$symb"}++;
 4187:     my $version=$hash{"version:$symb"};
 4188:     my $allkeys=''; 
 4189:     foreach my $key (keys(%$storehash)) {
 4190:       $allkeys.=$key.':';
 4191:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 4192:     }
 4193:     $hash{"$version:$symb:timestamp"}=$now;
 4194:     $allkeys.='timestamp';
 4195:     $hash{"$version:keys:$symb"}=$allkeys;
 4196:     if (untie(%hash)) {
 4197:       return 'ok';
 4198:     } else {
 4199:       return "error:$!";
 4200:     }
 4201:   } else {
 4202:     return "error:$!";
 4203:   }
 4204: }
 4205: 
 4206: # -----------------------------------------------------------------Temp Restore
 4207: 
 4208: sub tmprestore {
 4209:   my ($symb,$namespace,$domain,$stuname) = @_;
 4210: 
 4211:   if (!$symb) {
 4212:     $symb=&symbread();
 4213:     if (!$symb) { $symb= $env{'request.url'}; }
 4214:   }
 4215:   $symb=escape($symb);
 4216: 
 4217:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4218: 
 4219:   if (!$domain) { $domain=$env{'user.domain'}; }
 4220:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4221:   if ($domain eq 'public' && $stuname eq 'public') {
 4222:       $stuname=$ENV{'REMOTE_ADDR'};
 4223:   }
 4224:   my %returnhash;
 4225:   $namespace=~s/\//\_/g;
 4226:   $namespace=~s/\W//g;
 4227:   my %hash;
 4228:   my $path=LONCAPA::tempdir();
 4229:   if (tie(%hash,'GDBM_File',
 4230: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4231: 	  &GDBM_READER(),0640)) {
 4232:     my $version=$hash{"version:$symb"};
 4233:     $returnhash{'version'}=$version;
 4234:     my $scope;
 4235:     for ($scope=1;$scope<=$version;$scope++) {
 4236:       my $vkeys=$hash{"$scope:keys:$symb"};
 4237:       my @keys=split(/:/,$vkeys);
 4238:       my $key;
 4239:       $returnhash{"$scope:keys"}=$vkeys;
 4240:       foreach $key (@keys) {
 4241: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4242: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4243:       }
 4244:     }
 4245:     if (!(untie(%hash))) {
 4246:       return "error:$!";
 4247:     }
 4248:   } else {
 4249:     return "error:$!";
 4250:   }
 4251:   return %returnhash;
 4252: }
 4253: 
 4254: # ----------------------------------------------------------------------- Store
 4255: 
 4256: sub store {
 4257:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4258:     my $home='';
 4259: 
 4260:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4261: 
 4262:     $symb=&symbclean($symb);
 4263:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 4264: 
 4265:     if (!$domain) { $domain=$env{'user.domain'}; }
 4266:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4267: 
 4268:     &devalidate($symb,$stuname,$domain);
 4269: 
 4270:     $symb=escape($symb);
 4271:     if (!$namespace) { 
 4272:        unless ($namespace=$env{'request.course.id'}) { 
 4273:           return ''; 
 4274:        } 
 4275:     }
 4276:     if (!$home) { $home=$env{'user.home'}; }
 4277: 
 4278:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 4279:     $$storehash{'host'}=$perlvar{'lonHostID'};
 4280: 
 4281:     my $namevalue='';
 4282:     foreach my $key (keys(%$storehash)) {
 4283:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4284:     }
 4285:     $namevalue=~s/\&$//;
 4286:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 4287:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 4288: }
 4289: 
 4290: # -------------------------------------------------------------- Critical Store
 4291: 
 4292: sub cstore {
 4293:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4294:     my $home='';
 4295: 
 4296:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4297: 
 4298:     $symb=&symbclean($symb);
 4299:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 4300: 
 4301:     if (!$domain) { $domain=$env{'user.domain'}; }
 4302:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4303: 
 4304:     &devalidate($symb,$stuname,$domain);
 4305: 
 4306:     $symb=escape($symb);
 4307:     if (!$namespace) { 
 4308:        unless ($namespace=$env{'request.course.id'}) { 
 4309:           return ''; 
 4310:        } 
 4311:     }
 4312:     if (!$home) { $home=$env{'user.home'}; }
 4313: 
 4314:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 4315:     $$storehash{'host'}=$perlvar{'lonHostID'};
 4316: 
 4317:     my $namevalue='';
 4318:     foreach my $key (keys(%$storehash)) {
 4319:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4320:     }
 4321:     $namevalue=~s/\&$//;
 4322:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 4323:     return critical
 4324:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 4325: }
 4326: 
 4327: # --------------------------------------------------------------------- Restore
 4328: 
 4329: sub restore {
 4330:     my ($symb,$namespace,$domain,$stuname) = @_;
 4331:     my $home='';
 4332: 
 4333:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4334: 
 4335:     if (!$symb) {
 4336:       unless ($symb=escape(&symbread())) { return ''; }
 4337:     } else {
 4338:       $symb=&escape(&symbclean($symb));
 4339:     }
 4340:     if (!$namespace) { 
 4341:        unless ($namespace=$env{'request.course.id'}) { 
 4342:           return ''; 
 4343:        } 
 4344:     }
 4345:     if (!$domain) { $domain=$env{'user.domain'}; }
 4346:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4347:     if (!$home) { $home=$env{'user.home'}; }
 4348:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 4349: 
 4350:     my %returnhash=();
 4351:     foreach my $line (split(/\&/,$answer)) {
 4352: 	my ($name,$value)=split(/\=/,$line);
 4353:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 4354:     }
 4355:     my $version;
 4356:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 4357:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 4358:           $returnhash{$item}=$returnhash{$version.':'.$item};
 4359:        }
 4360:     }
 4361:     return %returnhash;
 4362: }
 4363: 
 4364: # ---------------------------------------------------------- Course Description
 4365: #
 4366: #  
 4367: 
 4368: sub coursedescription {
 4369:     my ($courseid,$args)=@_;
 4370:     $courseid=~s/^\///;
 4371:     $courseid=~s/\_/\//g;
 4372:     my ($cdomain,$cnum)=split(/\//,$courseid);
 4373:     my $chome=&homeserver($cnum,$cdomain);
 4374:     my $normalid=$cdomain.'_'.$cnum;
 4375:     # need to always cache even if we get errors otherwise we keep 
 4376:     # trying and trying and trying to get the course description.
 4377:     my %envhash=();
 4378:     my %returnhash=();
 4379:     
 4380:     my $expiretime=600;
 4381:     if ($env{'request.course.id'} eq $normalid) {
 4382: 	$expiretime=120;
 4383:     }
 4384: 
 4385:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 4386:     if (!$args->{'freshen_cache'}
 4387: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 4388: 	foreach my $key (keys(%env)) {
 4389: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 4390: 	    my ($setting) = $1;
 4391: 	    $returnhash{$setting} = $env{$key};
 4392: 	}
 4393: 	return %returnhash;
 4394:     }
 4395: 
 4396:     # get the data again
 4397: 
 4398:     if (!$args->{'one_time'}) {
 4399: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 4400:     }
 4401: 
 4402:     if ($chome ne 'no_host') {
 4403:        %returnhash=&dump('environment',$cdomain,$cnum);
 4404:        if (!exists($returnhash{'con_lost'})) {
 4405: 	   my $username = $env{'user.name'}; # Defult username
 4406: 	   if(defined $args->{'user'}) {
 4407: 	       $username = $args->{'user'};
 4408: 	   }
 4409:            $returnhash{'home'}= $chome;
 4410: 	   $returnhash{'domain'} = $cdomain;
 4411: 	   $returnhash{'num'} = $cnum;
 4412:            if (!defined($returnhash{'type'})) {
 4413:                $returnhash{'type'} = 'Course';
 4414:            }
 4415:            while (my ($name,$value) = each %returnhash) {
 4416:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 4417:            }
 4418:            $returnhash{'url'}=&clutter($returnhash{'url'});
 4419:            $returnhash{'fn'}=LONCAPA::tempdir() .
 4420: 	       $username.'_'.$cdomain.'_'.$cnum;
 4421:            $envhash{'course.'.$normalid.'.home'}=$chome;
 4422:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 4423:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 4424:        }
 4425:     }
 4426:     if (!$args->{'one_time'}) {
 4427: 	&appenv(\%envhash);
 4428:     }
 4429:     return %returnhash;
 4430: }
 4431: 
 4432: sub update_released_required {
 4433:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 4434:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 4435:         $cid = $env{'request.course.id'};
 4436:         $cdom = $env{'course.'.$cid.'.domain'};
 4437:         $cnum = $env{'course.'.$cid.'.num'};
 4438:         $chome = $env{'course.'.$cid.'.home'};
 4439:     }
 4440:     if ($needsrelease) {
 4441:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 4442:         my $needsupdate;
 4443:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 4444:             $needsupdate = 1;
 4445:         } else {
 4446:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 4447:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 4448:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 4449:                 $needsupdate = 1;
 4450:             }
 4451:         }
 4452:         if ($needsupdate) {
 4453:             my %needshash = (
 4454:                              'internal.releaserequired' => $needsrelease,
 4455:                             );
 4456:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 4457:             if ($putresult eq 'ok') {
 4458:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 4459:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 4460:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 4461:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 4462:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 4463:                 }
 4464:             }
 4465:         }
 4466:     }
 4467:     return;
 4468: }
 4469: 
 4470: # -------------------------------------------------See if a user is privileged
 4471: 
 4472: sub privileged {
 4473:     my ($username,$domain)=@_;
 4474:     my $rolesdump=&reply("dump:$domain:$username:roles",
 4475: 			&homeserver($username,$domain));
 4476:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
 4477:         ($rolesdump =~ /^error:/)) {
 4478:         return 0;
 4479:     }
 4480:     my $now=time;
 4481:     if ($rolesdump ne '') {
 4482:         foreach my $entry (split(/&/,$rolesdump)) {
 4483: 	    if ($entry!~/^rolesdef_/) {
 4484: 		my ($area,$role)=split(/=/,$entry);
 4485: 		$area=~s/\_\w\w$//;
 4486: 		my ($trole,$tend,$tstart)=split(/_/,$role);
 4487: 		if (($trole eq 'dc') || ($trole eq 'su')) {
 4488: 		    my $active=1;
 4489: 		    if ($tend) {
 4490: 			if ($tend<$now) { $active=0; }
 4491: 		    }
 4492: 		    if ($tstart) {
 4493: 			if ($tstart>$now) { $active=0; }
 4494: 		    }
 4495: 		    if ($active) { return 1; }
 4496: 		}
 4497: 	    }
 4498: 	}
 4499:     }
 4500:     return 0;
 4501: }
 4502: 
 4503: # -------------------------------------------------------- Get user privileges
 4504: 
 4505: sub rolesinit {
 4506:     my ($domain,$username,$authhost)=@_;
 4507:     my $now=time;
 4508:     my %userroles = ('user.login.time' => $now);
 4509:     my $extra = &freeze_escape({'skipcheck' => 1});
 4510:     my $rolesdump=reply("dump:$domain:$username:roles:.::$extra",$authhost);
 4511:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
 4512:         ($rolesdump =~ /^error:/)) {
 4513:         return \%userroles;
 4514:     }
 4515:     my %allroles=();
 4516:     my %allgroups=();   
 4517: 
 4518:     if ($rolesdump ne '') {
 4519:         foreach my $entry (split(/&/,$rolesdump)) {
 4520: 	  if ($entry!~/^rolesdef_/) {
 4521:             my ($area,$role)=split(/=/,$entry);
 4522: 	    $area=~s/\_\w\w$//;
 4523:             my ($trole,$tend,$tstart,$group_privs);
 4524: 	    if ($role=~/^cr/) { 
 4525: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 4526: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
 4527: 		    ($tend,$tstart)=split('_',$trest);
 4528: 		} else {
 4529: 		    $trole=$role;
 4530: 		}
 4531:             } elsif ($role =~ m|^gr/|) {
 4532:                 ($trole,$tend,$tstart) = split(/_/,$role);
 4533:                 next if ($tstart eq '-1');
 4534:                 ($trole,$group_privs) = split(/\//,$trole);
 4535:                 $group_privs = &unescape($group_privs);
 4536: 	    } else {
 4537: 		($trole,$tend,$tstart)=split(/_/,$role);
 4538: 	    }
 4539: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 4540: 					 $username);
 4541: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 4542:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
 4543:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
 4544:             if (($area ne '') && ($trole ne '')) {
 4545: 		my $spec=$trole.'.'.$area;
 4546: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
 4547: 		if ($trole =~ /^cr\//) {
 4548:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 4549:                 } elsif ($trole eq 'gr') {
 4550:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 4551: 		} else {
 4552:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 4553: 		}
 4554:             }
 4555:           }
 4556:         }
 4557:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
 4558:         $userroles{'user.adv'}    = $adv;
 4559: 	$userroles{'user.author'} = $author;
 4560:         $env{'user.adv'}=$adv;
 4561:     }
 4562:     return \%userroles;  
 4563: }
 4564: 
 4565: sub set_arearole {
 4566:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
 4567: # log the associated role with the area
 4568:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 4569:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 4570: }
 4571: 
 4572: sub custom_roleprivs {
 4573:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 4574:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 4575:     my $homsvr=homeserver($rauthor,$rdomain);
 4576:     if (&hostname($homsvr) ne '') {
 4577:         my ($rdummy,$roledef)=
 4578:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 4579:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 4580:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 4581:             if (defined($syspriv)) {
 4582:                 if ($trest =~ /^$match_community$/) {
 4583:                     $syspriv =~ s/bre\&S//; 
 4584:                 }
 4585:                 $$allroles{'cm./'}.=':'.$syspriv;
 4586:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 4587:             }
 4588:             if ($tdomain ne '') {
 4589:                 if (defined($dompriv)) {
 4590:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 4591:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 4592:                 }
 4593:                 if (($trest ne '') && (defined($coursepriv))) {
 4594:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 4595:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 4596:                 }
 4597:             }
 4598:         }
 4599:     }
 4600: }
 4601: 
 4602: sub group_roleprivs {
 4603:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 4604:     my $access = 1;
 4605:     my $now = time;
 4606:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 4607:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 4608:     if ($access) {
 4609:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 4610:         $$allgroups{$course}{$group} .=':'.$group_privs;
 4611:     }
 4612: }
 4613: 
 4614: sub standard_roleprivs {
 4615:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 4616:     if (defined($pr{$trole.':s'})) {
 4617:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 4618:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 4619:     }
 4620:     if ($tdomain ne '') {
 4621:         if (defined($pr{$trole.':d'})) {
 4622:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 4623:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 4624:         }
 4625:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 4626:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 4627:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 4628:         }
 4629:     }
 4630: }
 4631: 
 4632: sub set_userprivs {
 4633:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 4634:     my $author=0;
 4635:     my $adv=0;
 4636:     my %grouproles = ();
 4637:     if (keys(%{$allgroups}) > 0) {
 4638:         my @groupkeys; 
 4639:         foreach my $role (keys(%{$allroles})) {
 4640:             push(@groupkeys,$role);
 4641:         }
 4642:         if (ref($groups_roles) eq 'HASH') {
 4643:             foreach my $key (keys(%{$groups_roles})) {
 4644:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 4645:                     push(@groupkeys,$key);
 4646:                 }
 4647:             }
 4648:         }
 4649:         if (@groupkeys > 0) {
 4650:             foreach my $role (@groupkeys) {
 4651:                 my ($trole,$area,$sec,$extendedarea);
 4652:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 4653:                     $trole = $1;
 4654:                     $area = $2;
 4655:                     $sec = $3;
 4656:                     $extendedarea = $area.$sec;
 4657:                     if (exists($$allgroups{$area})) {
 4658:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 4659:                             my $spec = $trole.'.'.$extendedarea;
 4660:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 4661:                                                 $$allgroups{$area}{$group};
 4662:                         }
 4663:                     }
 4664:                 }
 4665:             }
 4666:         }
 4667:     }
 4668:     foreach my $group (keys(%grouproles)) {
 4669:         $$allroles{$group} = $grouproles{$group};
 4670:     }
 4671:     foreach my $role (keys(%{$allroles})) {
 4672:         my %thesepriv;
 4673:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 4674:         foreach my $item (split(/:/,$$allroles{$role})) {
 4675:             if ($item ne '') {
 4676:                 my ($privilege,$restrictions)=split(/&/,$item);
 4677:                 if ($restrictions eq '') {
 4678:                     $thesepriv{$privilege}='F';
 4679:                 } elsif ($thesepriv{$privilege} ne 'F') {
 4680:                     $thesepriv{$privilege}.=$restrictions;
 4681:                 }
 4682:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 4683:             }
 4684:         }
 4685:         my $thesestr='';
 4686:         foreach my $priv (sort(keys(%thesepriv))) {
 4687: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 4688: 	}
 4689:         $userroles->{'user.priv.'.$role} = $thesestr;
 4690:     }
 4691:     return ($author,$adv);
 4692: }
 4693: 
 4694: sub role_status {
 4695:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 4696:     my @pwhere = ();
 4697:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 4698:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
 4699:         unless (!defined($$role) || $$role eq '') {
 4700:             $$where=join('.',@pwhere);
 4701:             $$trolecode=$$role.'.'.$$where;
 4702:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 4703:             $$tstatus='is';
 4704:             if ($$tstart && $$tstart>$update) {
 4705:                 $$tstatus='future';
 4706:                 if ($$tstart<$now) {
 4707:                     if ($$tstart && $$tstart>$refresh) {
 4708:                         if (($$where ne '') && ($$role ne '')) {
 4709:                             my (%allroles,%allgroups,$group_privs,
 4710:                                 %groups_roles,@rolecodes);
 4711:                             my %userroles = (
 4712:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 4713:                             );
 4714:                             @rolecodes = ('cm'); 
 4715:                             my $spec=$$role.'.'.$$where;
 4716:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 4717:                             if ($$role =~ /^cr\//) {
 4718:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 4719:                                 push(@rolecodes,'cr');
 4720:                             } elsif ($$role eq 'gr') {
 4721:                                 push(@rolecodes,$$role);
 4722:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 4723:                                                     $env{'user.name'});
 4724:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 4725:                                 (undef,my $group_privs) = split(/\//,$trole);
 4726:                                 $group_privs = &unescape($group_privs);
 4727:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 4728:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 4729:                                 &get_groups_roles($tdomain,$trest,
 4730:                                                   \%course_roles,\@rolecodes,
 4731:                                                   \%groups_roles);
 4732:                             } else {
 4733:                                 push(@rolecodes,$$role);
 4734:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 4735:                             }
 4736:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
 4737:                             &appenv(\%userroles,\@rolecodes);
 4738:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 4739:                         }
 4740:                     }
 4741:                     $$tstatus = 'is';
 4742:                 }
 4743:             }
 4744:             if ($$tend) {
 4745:                 if ($$tend<$update) {
 4746:                     $$tstatus='expired';
 4747:                 } elsif ($$tend<$now) {
 4748:                     $$tstatus='will_not';
 4749:                 }
 4750:             }
 4751:         }
 4752:     }
 4753: }
 4754: 
 4755: sub get_groups_roles {
 4756:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 4757:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 4758:                   (ref($rolecodes) eq 'ARRAY') && 
 4759:                   (ref($groups_roles) eq 'HASH')); 
 4760:     if (keys(%{$cdom_courseroles}) > 0) {
 4761:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 4762:         if ($cdom ne '' && $cnum ne '') {
 4763:             foreach my $key (keys(%{$cdom_courseroles})) {
 4764:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 4765:                     my $crsrole = $1;
 4766:                     my $crssec = $2;
 4767:                     if ($crsrole =~ /^cr/) {
 4768:                         unless (grep(/^cr$/,@{$rolecodes})) {
 4769:                             push(@{$rolecodes},'cr');
 4770:                         }
 4771:                     } else {
 4772:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 4773:                             push(@{$rolecodes},$crsrole);
 4774:                         }
 4775:                     }
 4776:                     my $rolekey = "$crsrole./$cdom/$cnum";
 4777:                     if ($crssec ne '') {
 4778:                         $rolekey .= "/$crssec";
 4779:                     }
 4780:                     $rolekey .= './';
 4781:                     $groups_roles->{$rolekey} = $rolecodes;
 4782:                 }
 4783:             }
 4784:         }
 4785:     }
 4786:     return;
 4787: }
 4788: 
 4789: sub delete_env_groupprivs {
 4790:     my ($where,$courseroles,$possroles) = @_;
 4791:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 4792:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 4793:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 4794:         %{$courseroles->{$udom}} =
 4795:             &get_my_roles('','','userroles',['active'],
 4796:                           $possroles,[$udom],1);
 4797:     }
 4798:     if (ref($courseroles->{$udom}) eq 'HASH') {
 4799:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 4800:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 4801:             my $area = '/'.$cdom.'/'.$cnum;
 4802:             my $privkey = "user.priv.$crsrole.$area";
 4803:             if ($crssec ne '') {
 4804:                 $privkey .= '/'.$crssec;
 4805:             }
 4806:             $privkey .= ".$area/$group";
 4807:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 4808:         }
 4809:     }
 4810:     return;
 4811: }
 4812: 
 4813: sub check_adhoc_privs {
 4814:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
 4815:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 4816:     if ($env{$cckey}) {
 4817:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 4818:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 4819:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 4820:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 4821:         }
 4822:     } else {
 4823:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 4824:     }
 4825: }
 4826: 
 4827: sub set_adhoc_privileges {
 4828: # role can be cc or ca
 4829:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
 4830:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 4831:     my $spec = $role.'.'.$area;
 4832:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 4833:                                   $env{'user.name'});
 4834:     my %ccrole = ();
 4835:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
 4836:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
 4837:     &appenv(\%userroles,[$role,'cm']);
 4838:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 4839:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
 4840:         &appenv( {'request.role'        => $spec,
 4841:                   'request.role.domain' => $dcdom,
 4842:                   'request.course.sec'  => ''
 4843:                  }
 4844:                );
 4845:         my $tadv=0;
 4846:         if (&allowed('adv') eq 'F') { $tadv=1; }
 4847:         &appenv({'request.role.adv'    => $tadv});
 4848:     }
 4849: }
 4850: 
 4851: # --------------------------------------------------------------- get interface
 4852: 
 4853: sub get {
 4854:    my ($namespace,$storearr,$udomain,$uname)=@_;
 4855:    my $items='';
 4856:    foreach my $item (@$storearr) {
 4857:        $items.=&escape($item).'&';
 4858:    }
 4859:    $items=~s/\&$//;
 4860:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4861:    if (!$uname) { $uname=$env{'user.name'}; }
 4862:    my $uhome=&homeserver($uname,$udomain);
 4863: 
 4864:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 4865:    my @pairs=split(/\&/,$rep);
 4866:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 4867:      return @pairs;
 4868:    }
 4869:    my %returnhash=();
 4870:    my $i=0;
 4871:    foreach my $item (@$storearr) {
 4872:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 4873:       $i++;
 4874:    }
 4875:    return %returnhash;
 4876: }
 4877: 
 4878: # --------------------------------------------------------------- del interface
 4879: 
 4880: sub del {
 4881:    my ($namespace,$storearr,$udomain,$uname)=@_;
 4882:    my $items='';
 4883:    foreach my $item (@$storearr) {
 4884:        $items.=&escape($item).'&';
 4885:    }
 4886: 
 4887:    $items=~s/\&$//;
 4888:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4889:    if (!$uname) { $uname=$env{'user.name'}; }
 4890:    my $uhome=&homeserver($uname,$udomain);
 4891:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 4892: }
 4893: 
 4894: # -------------------------------------------------------------- dump interface
 4895: 
 4896: sub dump {
 4897:     my ($namespace,$udomain,$uname,$regexp,$range,$extra)=@_;
 4898:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 4899:     if (!$uname) { $uname=$env{'user.name'}; }
 4900:     my $uhome=&homeserver($uname,$udomain);
 4901:     if ($regexp) {
 4902: 	$regexp=&escape($regexp);
 4903:     } else {
 4904: 	$regexp='.';
 4905:     }
 4906:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range:$extra",$uhome);
 4907:     my @pairs=split(/\&/,$rep);
 4908:     my %returnhash=();
 4909:     if (!($rep =~ /^error/ )) {
 4910: 	foreach my $item (@pairs) {
 4911: 	    my ($key,$value)=split(/=/,$item,2);
 4912: 	    $key = &unescape($key);
 4913: 	    next if ($key =~ /^error: 2 /);
 4914: 	    $returnhash{$key}=&thaw_unescape($value);
 4915: 	}
 4916:     }
 4917:     return %returnhash;
 4918: }
 4919: 
 4920: 
 4921: # --------------------------------------------------------- dumpstore interface
 4922: 
 4923: sub dumpstore {
 4924:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 4925:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4926:    if (!$uname) { $uname=$env{'user.name'}; }
 4927:    my $uhome=&homeserver($uname,$udomain);
 4928:    if ($regexp) {
 4929:        $regexp=&escape($regexp);
 4930:    } else {
 4931:        $regexp='.';
 4932:    }
 4933:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 4934:    my @pairs=split(/\&/,$rep);
 4935:    my %returnhash=();
 4936:    foreach my $item (@pairs) {
 4937:        my ($key,$value)=split(/=/,$item,2);
 4938:        next if ($key =~ /^error: 2 /);
 4939:        $returnhash{$key}=&thaw_unescape($value);
 4940:    }
 4941:    return %returnhash;
 4942: }
 4943: 
 4944: # -------------------------------------------------------------- keys interface
 4945: 
 4946: sub getkeys {
 4947:    my ($namespace,$udomain,$uname)=@_;
 4948:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4949:    if (!$uname) { $uname=$env{'user.name'}; }
 4950:    my $uhome=&homeserver($uname,$udomain);
 4951:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 4952:    my @keyarray=();
 4953:    foreach my $key (split(/\&/,$rep)) {
 4954:       next if ($key =~ /^error: 2 /);
 4955:       push(@keyarray,&unescape($key));
 4956:    }
 4957:    return @keyarray;
 4958: }
 4959: 
 4960: # --------------------------------------------------------------- currentdump
 4961: sub currentdump {
 4962:    my ($courseid,$sdom,$sname)=@_;
 4963:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 4964:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 4965:    $sname    = $env{'user.name'}         if (! defined($sname));
 4966:    my $uhome = &homeserver($sname,$sdom);
 4967:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 4968:    return if ($rep =~ /^(error:|no_such_host)/);
 4969:    #
 4970:    my %returnhash=();
 4971:    #
 4972:    if ($rep eq "unknown_cmd") { 
 4973:        # an old lond will not know currentdump
 4974:        # Do a dump and make it look like a currentdump
 4975:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 4976:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 4977:        my %hash = @tmp;
 4978:        @tmp=();
 4979:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 4980:    } else {
 4981:        my @pairs=split(/\&/,$rep);
 4982:        foreach my $pair (@pairs) {
 4983:            my ($key,$value)=split(/=/,$pair,2);
 4984:            my ($symb,$param) = split(/:/,$key);
 4985:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 4986:                                                         &thaw_unescape($value);
 4987:        }
 4988:    }
 4989:    return %returnhash;
 4990: }
 4991: 
 4992: sub convert_dump_to_currentdump{
 4993:     my %hash = %{shift()};
 4994:     my %returnhash;
 4995:     # Code ripped from lond, essentially.  The only difference
 4996:     # here is the unescaping done by lonnet::dump().  Conceivably
 4997:     # we might run in to problems with parameter names =~ /^v\./
 4998:     while (my ($key,$value) = each(%hash)) {
 4999:         my ($v,$symb,$param) = split(/:/,$key);
 5000: 	$symb  = &unescape($symb);
 5001: 	$param = &unescape($param);
 5002:         next if ($v eq 'version' || $symb eq 'keys');
 5003:         next if (exists($returnhash{$symb}) &&
 5004:                  exists($returnhash{$symb}->{$param}) &&
 5005:                  $returnhash{$symb}->{'v.'.$param} > $v);
 5006:         $returnhash{$symb}->{$param}=$value;
 5007:         $returnhash{$symb}->{'v.'.$param}=$v;
 5008:     }
 5009:     #
 5010:     # Remove all of the keys in the hashes which keep track of
 5011:     # the version of the parameter.
 5012:     while (my ($symb,$param_hash) = each(%returnhash)) {
 5013:         # use a foreach because we are going to delete from the hash.
 5014:         foreach my $key (keys(%$param_hash)) {
 5015:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 5016:         }
 5017:     }
 5018:     return \%returnhash;
 5019: }
 5020: 
 5021: # ------------------------------------------------------ critical inc interface
 5022: 
 5023: sub cinc {
 5024:     return &inc(@_,'critical');
 5025: }
 5026: 
 5027: # --------------------------------------------------------------- inc interface
 5028: 
 5029: sub inc {
 5030:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 5031:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5032:     if (!$uname) { $uname=$env{'user.name'}; }
 5033:     my $uhome=&homeserver($uname,$udomain);
 5034:     my $items='';
 5035:     if (! ref($store)) {
 5036:         # got a single value, so use that instead
 5037:         $items = &escape($store).'=&';
 5038:     } elsif (ref($store) eq 'SCALAR') {
 5039:         $items = &escape($$store).'=&';        
 5040:     } elsif (ref($store) eq 'ARRAY') {
 5041:         $items = join('=&',map {&escape($_);} @{$store});
 5042:     } elsif (ref($store) eq 'HASH') {
 5043:         while (my($key,$value) = each(%{$store})) {
 5044:             $items.= &escape($key).'='.&escape($value).'&';
 5045:         }
 5046:     }
 5047:     $items=~s/\&$//;
 5048:     if ($critical) {
 5049: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 5050:     } else {
 5051: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 5052:     }
 5053: }
 5054: 
 5055: # --------------------------------------------------------------- put interface
 5056: 
 5057: sub put {
 5058:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5059:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5060:    if (!$uname) { $uname=$env{'user.name'}; }
 5061:    my $uhome=&homeserver($uname,$udomain);
 5062:    my $items='';
 5063:    foreach my $item (keys(%$storehash)) {
 5064:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5065:    }
 5066:    $items=~s/\&$//;
 5067:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5068: }
 5069: 
 5070: # ------------------------------------------------------------ newput interface
 5071: 
 5072: sub newput {
 5073:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5074:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5075:    if (!$uname) { $uname=$env{'user.name'}; }
 5076:    my $uhome=&homeserver($uname,$udomain);
 5077:    my $items='';
 5078:    foreach my $key (keys(%$storehash)) {
 5079:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 5080:    }
 5081:    $items=~s/\&$//;
 5082:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 5083: }
 5084: 
 5085: # ---------------------------------------------------------  putstore interface
 5086: 
 5087: sub putstore {
 5088:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 5089:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5090:    if (!$uname) { $uname=$env{'user.name'}; }
 5091:    my $uhome=&homeserver($uname,$udomain);
 5092:    my $items='';
 5093:    foreach my $key (keys(%$storehash)) {
 5094:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 5095:    }
 5096:    $items=~s/\&$//;
 5097:    my $esc_symb=&escape($symb);
 5098:    my $esc_v=&escape($version);
 5099:    my $reply =
 5100:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 5101: 	      $uhome);
 5102:    if ($reply eq 'unknown_cmd') {
 5103:        # gfall back to way things use to be done
 5104:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 5105: 			    $uname);
 5106:    }
 5107:    return $reply;
 5108: }
 5109: 
 5110: sub old_putstore {
 5111:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 5112:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5113:     if (!$uname) { $uname=$env{'user.name'}; }
 5114:     my $uhome=&homeserver($uname,$udomain);
 5115:     my %newstorehash;
 5116:     foreach my $item (keys(%$storehash)) {
 5117: 	my $key = $version.':'.&escape($symb).':'.$item;
 5118: 	$newstorehash{$key} = $storehash->{$item};
 5119:     }
 5120:     my $items='';
 5121:     my %allitems = ();
 5122:     foreach my $item (keys(%newstorehash)) {
 5123: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 5124: 	    my $key = $1.':keys:'.$2;
 5125: 	    $allitems{$key} .= $3.':';
 5126: 	}
 5127: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 5128:     }
 5129:     foreach my $item (keys(%allitems)) {
 5130: 	$allitems{$item} =~ s/\:$//;
 5131: 	$items.= $item.'='.$allitems{$item}.'&';
 5132:     }
 5133:     $items=~s/\&$//;
 5134:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5135: }
 5136: 
 5137: # ------------------------------------------------------ critical put interface
 5138: 
 5139: sub cput {
 5140:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5141:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5142:    if (!$uname) { $uname=$env{'user.name'}; }
 5143:    my $uhome=&homeserver($uname,$udomain);
 5144:    my $items='';
 5145:    foreach my $item (keys(%$storehash)) {
 5146:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5147:    }
 5148:    $items=~s/\&$//;
 5149:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 5150: }
 5151: 
 5152: # -------------------------------------------------------------- eget interface
 5153: 
 5154: sub eget {
 5155:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5156:    my $items='';
 5157:    foreach my $item (@$storearr) {
 5158:        $items.=&escape($item).'&';
 5159:    }
 5160:    $items=~s/\&$//;
 5161:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5162:    if (!$uname) { $uname=$env{'user.name'}; }
 5163:    my $uhome=&homeserver($uname,$udomain);
 5164:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 5165:    my @pairs=split(/\&/,$rep);
 5166:    my %returnhash=();
 5167:    my $i=0;
 5168:    foreach my $item (@$storearr) {
 5169:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 5170:       $i++;
 5171:    }
 5172:    return %returnhash;
 5173: }
 5174: 
 5175: # ------------------------------------------------------------ tmpput interface
 5176: sub tmpput {
 5177:     my ($storehash,$server,$context)=@_;
 5178:     my $items='';
 5179:     foreach my $item (keys(%$storehash)) {
 5180: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5181:     }
 5182:     $items=~s/\&$//;
 5183:     if (defined($context)) {
 5184:         $items .= ':'.&escape($context);
 5185:     }
 5186:     return &reply("tmpput:$items",$server);
 5187: }
 5188: 
 5189: # ------------------------------------------------------------ tmpget interface
 5190: sub tmpget {
 5191:     my ($token,$server)=@_;
 5192:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 5193:     my $rep=&reply("tmpget:$token",$server);
 5194:     my %returnhash;
 5195:     foreach my $item (split(/\&/,$rep)) {
 5196: 	my ($key,$value)=split(/=/,$item);
 5197:         next if ($key =~ /^error: 2 /);
 5198: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 5199:     }
 5200:     return %returnhash;
 5201: }
 5202: 
 5203: # ------------------------------------------------------------ tmpdel interface
 5204: sub tmpdel {
 5205:     my ($token,$server)=@_;
 5206:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 5207:     return &reply("tmpdel:$token",$server);
 5208: }
 5209: 
 5210: # -------------------------------------------------- portfolio access checking
 5211: 
 5212: sub portfolio_access {
 5213:     my ($requrl) = @_;
 5214:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 5215:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 5216:     if ($result) {
 5217:         my %setters;
 5218:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 5219:             my ($startblock,$endblock) =
 5220:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 5221:             if ($startblock && $endblock) {
 5222:                 return 'B';
 5223:             }
 5224:         } else {
 5225:             my ($startblock,$endblock) =
 5226:                 &Apache::loncommon::blockcheck(\%setters,'port');
 5227:             if ($startblock && $endblock) {
 5228:                 return 'B';
 5229:             }
 5230:         }
 5231:     }
 5232:     if ($result eq 'ok') {
 5233:        return 'F';
 5234:     } elsif ($result =~ /^[^:]+:guest_/) {
 5235:        return 'A';
 5236:     }
 5237:     return '';
 5238: }
 5239: 
 5240: sub get_portfolio_access {
 5241:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 5242: 
 5243:     if (!ref($access_hash)) {
 5244: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 5245: 	my %access_controls = &get_access_controls($current_perms,$group,
 5246: 						   $file_name);
 5247: 	$access_hash = $access_controls{$file_name};
 5248:     }
 5249: 
 5250:     my ($public,$guest,@domains,@users,@courses,@groups);
 5251:     my $now = time;
 5252:     if (ref($access_hash) eq 'HASH') {
 5253:         foreach my $key (keys(%{$access_hash})) {
 5254:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 5255:             if ($start > $now) {
 5256:                 next;
 5257:             }
 5258:             if ($end && $end<$now) {
 5259:                 next;
 5260:             }
 5261:             if ($scope eq 'public') {
 5262:                 $public = $key;
 5263:                 last;
 5264:             } elsif ($scope eq 'guest') {
 5265:                 $guest = $key;
 5266:             } elsif ($scope eq 'domains') {
 5267:                 push(@domains,$key);
 5268:             } elsif ($scope eq 'users') {
 5269:                 push(@users,$key);
 5270:             } elsif ($scope eq 'course') {
 5271:                 push(@courses,$key);
 5272:             } elsif ($scope eq 'group') {
 5273:                 push(@groups,$key);
 5274:             }
 5275:         }
 5276:         if ($public) {
 5277:             return 'ok';
 5278:         }
 5279:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 5280:             if ($guest) {
 5281:                 return $guest;
 5282:             }
 5283:         } else {
 5284:             if (@domains > 0) {
 5285:                 foreach my $domkey (@domains) {
 5286:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 5287:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 5288:                             return 'ok';
 5289:                         }
 5290:                     }
 5291:                 }
 5292:             }
 5293:             if (@users > 0) {
 5294:                 foreach my $userkey (@users) {
 5295:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 5296:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 5297:                             if (ref($item) eq 'HASH') {
 5298:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 5299:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 5300:                                     return 'ok';
 5301:                                 }
 5302:                             }
 5303:                         }
 5304:                     } 
 5305:                 }
 5306:             }
 5307:             my %roleshash;
 5308:             my @courses_and_groups = @courses;
 5309:             push(@courses_and_groups,@groups); 
 5310:             if (@courses_and_groups > 0) {
 5311:                 my (%allgroups,%allroles); 
 5312:                 my ($start,$end,$role,$sec,$group);
 5313:                 foreach my $envkey (%env) {
 5314:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 5315:                         my $cid = $2.'_'.$3; 
 5316:                         if ($1 eq 'gr') {
 5317:                             $group = $4;
 5318:                             $allgroups{$cid}{$group} = $env{$envkey};
 5319:                         } else {
 5320:                             if ($4 eq '') {
 5321:                                 $sec = 'none';
 5322:                             } else {
 5323:                                 $sec = $4;
 5324:                             }
 5325:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 5326:                         }
 5327:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 5328:                         my $cid = $2.'_'.$3;
 5329:                         if ($4 eq '') {
 5330:                             $sec = 'none';
 5331:                         } else {
 5332:                             $sec = $4;
 5333:                         }
 5334:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 5335:                     }
 5336:                 }
 5337:                 if (keys(%allroles) == 0) {
 5338:                     return;
 5339:                 }
 5340:                 foreach my $key (@courses_and_groups) {
 5341:                     my %content = %{$$access_hash{$key}};
 5342:                     my $cnum = $content{'number'};
 5343:                     my $cdom = $content{'domain'};
 5344:                     my $cid = $cdom.'_'.$cnum;
 5345:                     if (!exists($allroles{$cid})) {
 5346:                         next;
 5347:                     }    
 5348:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 5349:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 5350:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 5351:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 5352:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 5353:                         foreach my $role (keys(%{$allroles{$cid}})) {
 5354:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 5355:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 5356:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 5357:                                         if (grep/^all$/,@sections) {
 5358:                                             return 'ok';
 5359:                                         } else {
 5360:                                             if (grep/^$sec$/,@sections) {
 5361:                                                 return 'ok';
 5362:                                             }
 5363:                                         }
 5364:                                     }
 5365:                                 }
 5366:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 5367:                                     if (grep/^none$/,@groups) {
 5368:                                         return 'ok';
 5369:                                     }
 5370:                                 } else {
 5371:                                     if (grep/^all$/,@groups) {
 5372:                                         return 'ok';
 5373:                                     } 
 5374:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 5375:                                         if (grep/^$group$/,@groups) {
 5376:                                             return 'ok';
 5377:                                         }
 5378:                                     }
 5379:                                 } 
 5380:                             }
 5381:                         }
 5382:                     }
 5383:                 }
 5384:             }
 5385:             if ($guest) {
 5386:                 return $guest;
 5387:             }
 5388:         }
 5389:     }
 5390:     return;
 5391: }
 5392: 
 5393: sub course_group_datechecker {
 5394:     my ($dates,$now,$status) = @_;
 5395:     my ($start,$end) = split(/\./,$dates);
 5396:     if (!$start && !$end) {
 5397:         return 'ok';
 5398:     }
 5399:     if (grep/^active$/,@{$status}) {
 5400:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 5401:             return 'ok';
 5402:         }
 5403:     }
 5404:     if (grep/^previous$/,@{$status}) {
 5405:         if ($end > $now ) {
 5406:             return 'ok';
 5407:         }
 5408:     }
 5409:     if (grep/^future$/,@{$status}) {
 5410:         if ($start > $now) {
 5411:             return 'ok';
 5412:         }
 5413:     }
 5414:     return; 
 5415: }
 5416: 
 5417: sub parse_portfolio_url {
 5418:     my ($url) = @_;
 5419: 
 5420:     my ($type,$udom,$unum,$group,$file_name);
 5421:     
 5422:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 5423: 	$type = 1;
 5424:         $udom = $1;
 5425:         $unum = $2;
 5426:         $file_name = $3;
 5427:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 5428: 	$type = 2;
 5429:         $udom = $1;
 5430:         $unum = $2;
 5431:         $group = $3;
 5432:         $file_name = $3.'/'.$4;
 5433:     }
 5434:     if (wantarray) {
 5435: 	return ($type,$udom,$unum,$file_name,$group);
 5436:     }
 5437:     return $type;
 5438: }
 5439: 
 5440: sub is_portfolio_url {
 5441:     my ($url) = @_;
 5442:     return scalar(&parse_portfolio_url($url));
 5443: }
 5444: 
 5445: sub is_portfolio_file {
 5446:     my ($file) = @_;
 5447:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 5448:         return 1;
 5449:     }
 5450:     return;
 5451: }
 5452: 
 5453: sub usertools_access {
 5454:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 5455:     my ($access,%tools);
 5456:     if ($context eq '') {
 5457:         $context = 'tools';
 5458:     }
 5459:     if ($context eq 'requestcourses') {
 5460:         %tools = (
 5461:                       official   => 1,
 5462:                       unofficial => 1,
 5463:                       community  => 1,
 5464:                  );
 5465:     } else {
 5466:         %tools = (
 5467:                       aboutme   => 1,
 5468:                       blog      => 1,
 5469:                       portfolio => 1,
 5470:                  );
 5471:     }
 5472:     return if (!defined($tools{$tool}));
 5473: 
 5474:     if ((!defined($udom)) || (!defined($uname))) {
 5475:         $udom = $env{'user.domain'};
 5476:         $uname = $env{'user.name'};
 5477:     }
 5478: 
 5479:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 5480:         if ($action ne 'reload') {
 5481:             if ($context eq 'requestcourses') {
 5482:                 return $env{'environment.canrequest.'.$tool};
 5483:             } else {
 5484:                 return $env{'environment.availabletools.'.$tool};
 5485:             }
 5486:         }
 5487:     }
 5488: 
 5489:     my ($toolstatus,$inststatus);
 5490: 
 5491:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 5492:          ($action ne 'reload')) {
 5493:         $toolstatus = $env{'environment.'.$context.'.'.$tool};
 5494:         $inststatus = $env{'environment.inststatus'};
 5495:     } else {
 5496:         if (ref($userenvref) eq 'HASH') {
 5497:             $toolstatus = $userenvref->{$context.'.'.$tool};
 5498:             $inststatus = $userenvref->{'inststatus'};
 5499:         } else {
 5500:             my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
 5501:             $toolstatus = $userenv{$context.'.'.$tool};
 5502:             $inststatus = $userenv{'inststatus'};
 5503:         }
 5504:     }
 5505: 
 5506:     if ($toolstatus ne '') {
 5507:         if ($toolstatus) {
 5508:             $access = 1;
 5509:         } else {
 5510:             $access = 0;
 5511:         }
 5512:         return $access;
 5513:     }
 5514: 
 5515:     my ($is_adv,%domdef);
 5516:     if (ref($is_advref) eq 'HASH') {
 5517:         $is_adv = $is_advref->{'is_adv'};
 5518:     } else {
 5519:         $is_adv = &is_advanced_user($udom,$uname);
 5520:     }
 5521:     if (ref($domdefref) eq 'HASH') {
 5522:         %domdef = %{$domdefref};
 5523:     } else {
 5524:         %domdef = &get_domain_defaults($udom);
 5525:     }
 5526:     if (ref($domdef{$tool}) eq 'HASH') {
 5527:         if ($is_adv) {
 5528:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 5529:                 if ($domdef{$tool}{'_LC_adv'}) { 
 5530:                     $access = 1;
 5531:                 } else {
 5532:                     $access = 0;
 5533:                 }
 5534:                 return $access;
 5535:             }
 5536:         }
 5537:         if ($inststatus ne '') {
 5538:             my ($hasaccess,$hasnoaccess);
 5539:             foreach my $affiliation (split(/:/,$inststatus)) {
 5540:                 if ($domdef{$tool}{$affiliation} ne '') { 
 5541:                     if ($domdef{$tool}{$affiliation}) {
 5542:                         $hasaccess = 1;
 5543:                     } else {
 5544:                         $hasnoaccess = 1;
 5545:                     }
 5546:                 }
 5547:             }
 5548:             if ($hasaccess || $hasnoaccess) {
 5549:                 if ($hasaccess) {
 5550:                     $access = 1;
 5551:                 } elsif ($hasnoaccess) {
 5552:                     $access = 0; 
 5553:                 }
 5554:                 return $access;
 5555:             }
 5556:         } else {
 5557:             if ($domdef{$tool}{'default'} ne '') {
 5558:                 if ($domdef{$tool}{'default'}) {
 5559:                     $access = 1;
 5560:                 } elsif ($domdef{$tool}{'default'} == 0) {
 5561:                     $access = 0;
 5562:                 }
 5563:                 return $access;
 5564:             }
 5565:         }
 5566:     } else {
 5567:         if ($context eq 'tools') {
 5568:             $access = 1;
 5569:         } else {
 5570:             $access = 0;
 5571:         }
 5572:         return $access;
 5573:     }
 5574: }
 5575: 
 5576: sub is_course_owner {
 5577:     my ($cdom,$cnum,$udom,$uname) = @_;
 5578:     if (($udom eq '') || ($uname eq '')) {
 5579:         $udom = $env{'user.domain'};
 5580:         $uname = $env{'user.name'};
 5581:     }
 5582:     unless (($udom eq '') || ($uname eq '')) {
 5583:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 5584:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 5585:                 return 1;
 5586:             } else {
 5587:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 5588:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 5589:                     return 1;
 5590:                 }
 5591:             }
 5592:         }
 5593:     }
 5594:     return;
 5595: }
 5596: 
 5597: sub is_advanced_user {
 5598:     my ($udom,$uname) = @_;
 5599:     if ($udom ne '' && $uname ne '') {
 5600:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 5601:             if (wantarray) {
 5602:                 return ($env{'user.adv'},$env{'user.author'});
 5603:             } else {
 5604:                 return $env{'user.adv'};
 5605:             }
 5606:         }
 5607:     }
 5608:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 5609:     my %allroles;
 5610:     my ($is_adv,$is_author);
 5611:     foreach my $role (keys(%roleshash)) {
 5612:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 5613:         my $area = '/'.$tdomain.'/'.$trest;
 5614:         if ($sec ne '') {
 5615:             $area .= '/'.$sec;
 5616:         }
 5617:         if (($area ne '') && ($trole ne '')) {
 5618:             my $spec=$trole.'.'.$area;
 5619:             if ($trole =~ /^cr\//) {
 5620:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 5621:             } elsif ($trole ne 'gr') {
 5622:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 5623:             }
 5624:             if ($trole eq 'au') {
 5625:                 $is_author = 1;
 5626:             }
 5627:         }
 5628:     }
 5629:     foreach my $role (keys(%allroles)) {
 5630:         last if ($is_adv);
 5631:         foreach my $item (split(/:/,$allroles{$role})) {
 5632:             if ($item ne '') {
 5633:                 my ($privilege,$restrictions)=split(/&/,$item);
 5634:                 if ($privilege eq 'adv') {
 5635:                     $is_adv = 1;
 5636:                     last;
 5637:                 }
 5638:             }
 5639:         }
 5640:     }
 5641:     if (wantarray) {
 5642:         return ($is_adv,$is_author);
 5643:     }
 5644:     return $is_adv;
 5645: }
 5646: 
 5647: sub check_can_request {
 5648:     my ($dom,$can_request,$request_domains) = @_;
 5649:     my $canreq = 0;
 5650:     my ($types,$typename) = &Apache::loncommon::course_types();
 5651:     my @options = ('approval','validate','autolimit');
 5652:     my $optregex = join('|',@options);
 5653:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 5654:         foreach my $type (@{$types}) {
 5655:             if (&usertools_access($env{'user.name'},
 5656:                                   $env{'user.domain'},
 5657:                                   $type,undef,'requestcourses')) {
 5658:                 $canreq ++;
 5659:                 if (ref($request_domains) eq 'HASH') {
 5660:                     push(@{$request_domains->{$type}},$env{'user.domain'});
 5661:                 }
 5662:                 if ($dom eq $env{'user.domain'}) {
 5663:                     $can_request->{$type} = 1;
 5664:                 }
 5665:             }
 5666:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
 5667:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 5668:                 if (@curr > 0) {
 5669:                     foreach my $item (@curr) {
 5670:                         if (ref($request_domains) eq 'HASH') {
 5671:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 5672:                             if ($otherdom ne '') {
 5673:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 5674:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 5675:                                         push(@{$request_domains->{$type}},$otherdom);
 5676:                                     }
 5677:                                 } else {
 5678:                                     push(@{$request_domains->{$type}},$otherdom);
 5679:                                 }
 5680:                             }
 5681:                         }
 5682:                     }
 5683:                     unless($dom eq $env{'user.domain'}) {
 5684:                         $canreq ++;
 5685:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 5686:                             $can_request->{$type} = 1;
 5687:                         }
 5688:                     }
 5689:                 }
 5690:             }
 5691:         }
 5692:     }
 5693:     return $canreq;
 5694: }
 5695: 
 5696: # ---------------------------------------------- Custom access rule evaluation
 5697: 
 5698: sub customaccess {
 5699:     my ($priv,$uri)=@_;
 5700:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 5701:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 5702:     $udom = &LONCAPA::clean_domain($udom);
 5703:     $ucrs = &LONCAPA::clean_username($ucrs);
 5704:     my $access=0;
 5705:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 5706: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 5707: 	if ($type eq 'user') {
 5708: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 5709: 		my ($tdom,$tuname)=split(m{/},$scope);
 5710: 		if ($tdom) {
 5711: 		    if ($tdom ne $env{'user.domain'}) { next; }
 5712: 		}
 5713: 		if ($tuname) {
 5714: 		    if ($tuname ne $env{'user.name'}) { next; }
 5715: 		}
 5716: 		$access=($effect eq 'allow');
 5717: 		last;
 5718: 	    }
 5719: 	} else {
 5720: 	    if ($role) {
 5721: 		if ($role ne $urole) { next; }
 5722: 	    }
 5723: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 5724: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 5725: 		if ($tdom) {
 5726: 		    if ($tdom ne $udom) { next; }
 5727: 		}
 5728: 		if ($tcrs) {
 5729: 		    if ($tcrs ne $ucrs) { next; }
 5730: 		}
 5731: 		if ($tsec) {
 5732: 		    if ($tsec ne $usec) { next; }
 5733: 		}
 5734: 		$access=($effect eq 'allow');
 5735: 		last;
 5736: 	    }
 5737: 	    if ($realm eq '' && $role eq '') {
 5738: 		$access=($effect eq 'allow');
 5739: 	    }
 5740: 	}
 5741:     }
 5742:     return $access;
 5743: }
 5744: 
 5745: # ------------------------------------------------- Check for a user privilege
 5746: 
 5747: sub allowed {
 5748:     my ($priv,$uri,$symb,$role)=@_;
 5749:     my $ver_orguri=$uri;
 5750:     $uri=&deversion($uri);
 5751:     my $orguri=$uri;
 5752:     $uri=&declutter($uri);
 5753: 
 5754:     if ($priv eq 'evb') {
 5755: # Evade communication block restrictions for specified role in a course
 5756:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 5757:             return $1;
 5758:         } else {
 5759:             return;
 5760:         }
 5761:     }
 5762: 
 5763:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 5764: # Free bre access to adm and meta resources
 5765:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 5766: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 5767: 	&& ($priv eq 'bre')) {
 5768: 	return 'F';
 5769:     }
 5770: 
 5771: # Free bre access to user's own portfolio contents
 5772:     my ($space,$domain,$name,@dir)=split('/',$uri);
 5773:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 5774: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 5775:         my %setters;
 5776:         my ($startblock,$endblock) = 
 5777:             &Apache::loncommon::blockcheck(\%setters,'port');
 5778:         if ($startblock && $endblock) {
 5779:             return 'B';
 5780:         } else {
 5781:             return 'F';
 5782:         }
 5783:     }
 5784: 
 5785: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 5786:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 5787:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 5788:         if (exists($env{'request.course.id'})) {
 5789:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5790:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5791:             if (($domain eq $cdom) && ($name eq $cnum)) {
 5792:                 my $courseprivid=$env{'request.course.id'};
 5793:                 $courseprivid=~s/\_/\//;
 5794:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 5795:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 5796:                     return $1; 
 5797:                 } else {
 5798:                     if ($env{'request.course.sec'}) {
 5799:                         $courseprivid.='/'.$env{'request.course.sec'};
 5800:                     }
 5801:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 5802:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 5803:                         return $2;
 5804:                     }
 5805:                 }
 5806:             }
 5807:         }
 5808:     }
 5809: 
 5810: # Free bre to public access
 5811: 
 5812:     if ($priv eq 'bre') {
 5813:         my $copyright=&metadata($uri,'copyright');
 5814: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 5815:            return 'F'; 
 5816:         }
 5817:         if ($copyright eq 'priv') {
 5818:             $uri=~/([^\/]+)\/([^\/]+)\//;
 5819: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 5820: 		return '';
 5821:             }
 5822:         }
 5823:         if ($copyright eq 'domain') {
 5824:             $uri=~/([^\/]+)\/([^\/]+)\//;
 5825: 	    unless (($env{'user.domain'} eq $1) ||
 5826:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 5827: 		return '';
 5828:             }
 5829:         }
 5830:         if ($env{'request.role'}=~ /li\.\//) {
 5831:             # Library role, so allow browsing of resources in this domain.
 5832:             return 'F';
 5833:         }
 5834:         if ($copyright eq 'custom') {
 5835: 	    unless (&customaccess($priv,$uri)) { return ''; }
 5836:         }
 5837:     }
 5838:     # Domain coordinator is trying to create a course
 5839:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 5840:         # uri is the requested domain in this case.
 5841:         # comparison to 'request.role.domain' shows if the user has selected
 5842:         # a role of dc for the domain in question.
 5843:         return 'F' if ($uri eq $env{'request.role.domain'});
 5844:     }
 5845: 
 5846:     my $thisallowed='';
 5847:     my $statecond=0;
 5848:     my $courseprivid='';
 5849: 
 5850:     my $ownaccess;
 5851:     # Community Coordinator or Assistant Co-author browsing resource space.
 5852:     if (($priv eq 'bro') && ($env{'user.author'})) {
 5853:         if ($uri eq '') {
 5854:             $ownaccess = 1;
 5855:         } else {
 5856:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 5857:                 my $udom = $env{'user.domain'};
 5858:                 my $uname = $env{'user.name'};
 5859:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 5860:                     $ownaccess = 1;
 5861:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 5862:                     unless ($uri =~ m{\.\./}) {
 5863:                         $ownaccess = 1;
 5864:                     }
 5865:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 5866:                     my $now = time;
 5867:                     if ($uri =~ m{^([^/]+)/?$}) {
 5868:                         my $adom = $1;
 5869:                         foreach my $key (keys(%env)) {
 5870:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 5871:                                 my ($start,$end) = split('.',$env{$key});
 5872:                                 if (($now >= $start) && (!$end || $end < $now)) {
 5873:                                     $ownaccess = 1;
 5874:                                     last;
 5875:                                 }
 5876:                             }
 5877:                         }
 5878:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 5879:                         my $adom = $1;
 5880:                         my $aname = $2;
 5881:                         foreach my $role ('ca','aa') { 
 5882:                             if ($env{"user.role.$role./$adom/$aname"}) {
 5883:                                 my ($start,$end) =
 5884:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 5885:                                 if (($now >= $start) && (!$end || $end < $now)) {
 5886:                                     $ownaccess = 1;
 5887:                                     last;
 5888:                                 }
 5889:                             }
 5890:                         }
 5891:                     }
 5892:                 }
 5893:             }
 5894:         }
 5895:     }
 5896: 
 5897: # Course
 5898: 
 5899:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 5900:         unless (($priv eq 'bro') && (!$ownaccess)) {
 5901:             $thisallowed.=$1;
 5902:         }
 5903:     }
 5904: 
 5905: # Domain
 5906: 
 5907:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 5908:        =~/\Q$priv\E\&([^\:]*)/) {
 5909:         unless (($priv eq 'bro') && (!$ownaccess)) {
 5910:             $thisallowed.=$1;
 5911:         }
 5912:     }
 5913: 
 5914: # User who is not author or co-author might still be able to edit
 5915: # resource of an author in the domain (e.g., if Domain Coordinator).
 5916:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 5917:         (&allowed('mdc',$env{'request.course.id'}))) {
 5918:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 5919:             $thisallowed.=$1;
 5920:         }
 5921:     }
 5922: 
 5923: # Course: uri itself is a course
 5924:     my $courseuri=$uri;
 5925:     $courseuri=~s/\_(\d)/\/$1/;
 5926:     $courseuri=~s/^([^\/])/\/$1/;
 5927: 
 5928:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 5929:        =~/\Q$priv\E\&([^\:]*)/) {
 5930:         unless (($priv eq 'bro') && (!$ownaccess)) {
 5931:             $thisallowed.=$1;
 5932:         }
 5933:     }
 5934: 
 5935: # URI is an uploaded document for this course, default permissions don't matter
 5936: # not allowing 'edit' access (editupload) to uploaded course docs
 5937:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 5938: 	$thisallowed='';
 5939:         my ($match)=&is_on_map($uri);
 5940:         if ($match) {
 5941:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 5942:                   =~/\Q$priv\E\&([^\:]*)/) {
 5943:                 $thisallowed.=$1;
 5944:             }
 5945:         } else {
 5946:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 5947:             if ($refuri) {
 5948:                 if ($refuri =~ m|^/adm/|) {
 5949:                     $thisallowed='F';
 5950:                 } else {
 5951:                     $refuri=&declutter($refuri);
 5952:                     my ($match) = &is_on_map($refuri);
 5953:                     if ($match) {
 5954:                         $thisallowed='F';
 5955:                     }
 5956:                 }
 5957:             }
 5958:         }
 5959:     }
 5960: 
 5961:     if ($priv eq 'bre'
 5962: 	&& $thisallowed ne 'F' 
 5963: 	&& $thisallowed ne '2'
 5964: 	&& &is_portfolio_url($uri)) {
 5965: 	$thisallowed = &portfolio_access($uri);
 5966:     }
 5967:     
 5968: # Full access at system, domain or course-wide level? Exit.
 5969:     if ($thisallowed=~/F/) {
 5970: 	return 'F';
 5971:     }
 5972: 
 5973: # If this is generating or modifying users, exit with special codes
 5974: 
 5975:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 5976: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 5977: 	    my ($audom,$auname)=split('/',$uri);
 5978: # no author name given, so this just checks on the general right to make a co-author in this domain
 5979: 	    unless ($auname) { return $thisallowed; }
 5980: # an author name is given, so we are about to actually make a co-author for a certain account
 5981: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 5982: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 5983: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 5984: 	}
 5985: 	return $thisallowed;
 5986:     }
 5987: #
 5988: # Gathered so far: system, domain and course wide privileges
 5989: #
 5990: # Course: See if uri or referer is an individual resource that is part of 
 5991: # the course
 5992: 
 5993:     if ($env{'request.course.id'}) {
 5994: 
 5995:        $courseprivid=$env{'request.course.id'};
 5996:        if ($env{'request.course.sec'}) {
 5997:           $courseprivid.='/'.$env{'request.course.sec'};
 5998:        }
 5999:        $courseprivid=~s/\_/\//;
 6000:        my $checkreferer=1;
 6001:        my ($match,$cond)=&is_on_map($uri);
 6002:        if ($match) {
 6003:            $statecond=$cond;
 6004:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 6005:                =~/\Q$priv\E\&([^\:]*)/) {
 6006:                $thisallowed.=$1;
 6007:                $checkreferer=0;
 6008:            }
 6009:        }
 6010:        
 6011:        if ($checkreferer) {
 6012: 	  my $refuri=$env{'httpref.'.$orguri};
 6013:             unless ($refuri) {
 6014:                 foreach my $key (keys(%env)) {
 6015: 		    if ($key=~/^httpref\..*\*/) {
 6016: 			my $pattern=$key;
 6017:                         $pattern=~s/^httpref\.\/res\///;
 6018:                         $pattern=~s/\*/\[\^\/\]\+/g;
 6019:                         $pattern=~s/\//\\\//g;
 6020:                         if ($orguri=~/$pattern/) {
 6021: 			    $refuri=$env{$key};
 6022:                         }
 6023:                     }
 6024:                 }
 6025:             }
 6026: 
 6027:          if ($refuri) { 
 6028: 	  $refuri=&declutter($refuri);
 6029:           my ($match,$cond)=&is_on_map($refuri);
 6030:             if ($match) {
 6031:               my $refstatecond=$cond;
 6032:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 6033:                   =~/\Q$priv\E\&([^\:]*)/) {
 6034:                   $thisallowed.=$1;
 6035:                   $uri=$refuri;
 6036:                   $statecond=$refstatecond;
 6037:               }
 6038:           }
 6039:         }
 6040:        }
 6041:    }
 6042: 
 6043: #
 6044: # Gathered now: all privileges that could apply, and condition number
 6045: # 
 6046: #
 6047: # Full or no access?
 6048: #
 6049: 
 6050:     if ($thisallowed=~/F/) {
 6051: 	return 'F';
 6052:     }
 6053: 
 6054:     unless ($thisallowed) {
 6055:         return '';
 6056:     }
 6057: 
 6058: # Restrictions exist, deal with them
 6059: #
 6060: #   C:according to course preferences
 6061: #   R:according to resource settings
 6062: #   L:unless locked
 6063: #   X:according to user session state
 6064: #
 6065: 
 6066: # Possibly locked functionality, check all courses
 6067: # Locks might take effect only after 10 minutes cache expiration for other
 6068: # courses, and 2 minutes for current course
 6069: 
 6070:     my $envkey;
 6071:     if ($thisallowed=~/L/) {
 6072:         foreach $envkey (keys(%env)) {
 6073:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 6074:                my $courseid=$2;
 6075:                my $roleid=$1.'.'.$2;
 6076:                $courseid=~s/^\///;
 6077:                my $expiretime=600;
 6078:                if ($env{'request.role'} eq $roleid) {
 6079: 		  $expiretime=120;
 6080:                }
 6081: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 6082:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 6083:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 6084: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 6085:                }
 6086:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 6087:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 6088: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 6089:                        &log($env{'user.domain'},$env{'user.name'},
 6090:                             $env{'user.home'},
 6091:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 6092:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 6093:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 6094: 		       return '';
 6095:                    }
 6096:                }
 6097:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 6098:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 6099: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 6100:                        &log($env{'user.domain'},$env{'user.name'},
 6101:                             $env{'user.home'},
 6102:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 6103:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 6104:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 6105: 		       return '';
 6106:                    }
 6107:                }
 6108: 	   }
 6109:        }
 6110:     }
 6111:    
 6112: #
 6113: # Rest of the restrictions depend on selected course
 6114: #
 6115: 
 6116:     unless ($env{'request.course.id'}) {
 6117: 	if ($thisallowed eq 'A') {
 6118: 	    return 'A';
 6119:         } elsif ($thisallowed eq 'B') {
 6120:             return 'B';
 6121: 	} else {
 6122: 	    return '1';
 6123: 	}
 6124:     }
 6125: 
 6126: #
 6127: # Now user is definitely in a course
 6128: #
 6129: 
 6130: 
 6131: # Course preferences
 6132: 
 6133:    if ($thisallowed=~/C/) {
 6134:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 6135:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 6136:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 6137: 	   =~/\Q$rolecode\E/) {
 6138: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6139: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 6140: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 6141: 			$env{'request.course.id'});
 6142: 	   }
 6143:            return '';
 6144:        }
 6145: 
 6146:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 6147: 	   =~/\Q$unamedom\E/) {
 6148: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6149: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 6150: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 6151: 			$env{'request.course.id'});
 6152: 	   }
 6153:            return '';
 6154:        }
 6155:    }
 6156: 
 6157: # Resource preferences
 6158: 
 6159:    if ($thisallowed=~/R/) {
 6160:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 6161:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 6162: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6163: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 6164: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 6165: 	   }
 6166: 	   return '';
 6167:        }
 6168:    }
 6169: 
 6170: # Restricted by state or randomout?
 6171: 
 6172:    if ($thisallowed=~/X/) {
 6173:       if ($env{'acc.randomout'}) {
 6174: 	 if (!$symb) { $symb=&symbread($uri,1); }
 6175:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 6176:             return ''; 
 6177:          }
 6178:       }
 6179:       if (&condval($statecond)) {
 6180: 	 return '2';
 6181:       } else {
 6182:          return '';
 6183:       }
 6184:    }
 6185: 
 6186:     if ($thisallowed eq 'A') {
 6187: 	return 'A';
 6188:     } elsif ($thisallowed eq 'B') {
 6189:         return 'B';
 6190:     }
 6191:    return 'F';
 6192: }
 6193: #
 6194: #   Removes the versino from a URI and
 6195: #   splits it in to its filename and path to the filename.
 6196: #   Seems like File::Basename could have done this more clearly.
 6197: #   Parameters:
 6198: #      $uri   - input URI
 6199: #   Returns:
 6200: #     Two element list consisting of 
 6201: #     $pathname  - the URI up to and excluding the trailing /
 6202: #     $filename  - The part of the URI following the last /
 6203: #  NOTE:
 6204: #    Another realization of this is simply:
 6205: #    use File::Basename;
 6206: #    ...
 6207: #    $uri = shift;
 6208: #    $filename = basename($uri);
 6209: #    $path     = dirname($uri);
 6210: #    return ($filename, $path);
 6211: #
 6212: #     The implementation below is probably faster however.
 6213: #
 6214: sub split_uri_for_cond {
 6215:     my $uri=&deversion(&declutter(shift));
 6216:     my @uriparts=split(/\//,$uri);
 6217:     my $filename=pop(@uriparts);
 6218:     my $pathname=join('/',@uriparts);
 6219:     return ($pathname,$filename);
 6220: }
 6221: # --------------------------------------------------- Is a resource on the map?
 6222: 
 6223: sub is_on_map {
 6224:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 6225:     #Trying to find the conditional for the file
 6226:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 6227: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 6228:     if ($match) {
 6229: 	return (1,$1);
 6230:     } else {
 6231: 	return (0,0);
 6232:     }
 6233: }
 6234: 
 6235: # --------------------------------------------------------- Get symb from alias
 6236: 
 6237: sub get_symb_from_alias {
 6238:     my $symb=shift;
 6239:     my ($map,$resid,$url)=&decode_symb($symb);
 6240: # Already is a symb
 6241:     if ($url) { return $symb; }
 6242: # Must be an alias
 6243:     my $aliassymb='';
 6244:     my %bighash;
 6245:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6246:                             &GDBM_READER(),0640)) {
 6247:         my $rid=$bighash{'mapalias_'.$symb};
 6248: 	if ($rid) {
 6249: 	    my ($mapid,$resid)=split(/\./,$rid);
 6250: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 6251: 				    $resid,$bighash{'src_'.$rid});
 6252: 	}
 6253:         untie %bighash;
 6254:     }
 6255:     return $aliassymb;
 6256: }
 6257: 
 6258: # ----------------------------------------------------------------- Define Role
 6259: 
 6260: sub definerole {
 6261:   if (allowed('mcr','/')) {
 6262:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 6263:     foreach my $role (split(':',$sysrole)) {
 6264: 	my ($crole,$cqual)=split(/\&/,$role);
 6265:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 6266:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 6267: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 6268:                return "refused:s:$crole&$cqual"; 
 6269:             }
 6270:         }
 6271:     }
 6272:     foreach my $role (split(':',$domrole)) {
 6273: 	my ($crole,$cqual)=split(/\&/,$role);
 6274:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 6275:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 6276: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 6277:                return "refused:d:$crole&$cqual"; 
 6278:             }
 6279:         }
 6280:     }
 6281:     foreach my $role (split(':',$courole)) {
 6282: 	my ($crole,$cqual)=split(/\&/,$role);
 6283:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 6284:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 6285: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 6286:                return "refused:c:$crole&$cqual"; 
 6287:             }
 6288:         }
 6289:     }
 6290:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 6291:                 "$env{'user.domain'}:$env{'user.name'}:".
 6292: 	        "rolesdef_$rolename=".
 6293:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 6294:     return reply($command,$env{'user.home'});
 6295:   } else {
 6296:     return 'refused';
 6297:   }
 6298: }
 6299: 
 6300: # ---------------- Make a metadata query against the network of library servers
 6301: 
 6302: sub metadata_query {
 6303:     my ($query,$custom,$customshow,$server_array)=@_;
 6304:     my %rhash;
 6305:     my %libserv = &all_library();
 6306:     my @server_list = (defined($server_array) ? @$server_array
 6307:                                               : keys(%libserv) );
 6308:     for my $server (@server_list) {
 6309: 	unless ($custom or $customshow) {
 6310: 	    my $reply=&reply("querysend:".&escape($query),$server);
 6311: 	    $rhash{$server}=$reply;
 6312: 	}
 6313: 	else {
 6314: 	    my $reply=&reply("querysend:".&escape($query).':'.
 6315: 			     &escape($custom).':'.&escape($customshow),
 6316: 			     $server);
 6317: 	    $rhash{$server}=$reply;
 6318: 	}
 6319:     }
 6320:     return \%rhash;
 6321: }
 6322: 
 6323: # ----------------------------------------- Send log queries and wait for reply
 6324: 
 6325: sub log_query {
 6326:     my ($uname,$udom,$query,%filters)=@_;
 6327:     my $uhome=&homeserver($uname,$udom);
 6328:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 6329:     my $uhost=&hostname($uhome);
 6330:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 6331:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 6332:                        $uhome);
 6333:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 6334:     return get_query_reply($queryid);
 6335: }
 6336: 
 6337: # -------------------------- Update MySQL table for portfolio file
 6338: 
 6339: sub update_portfolio_table {
 6340:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 6341:     if ($group ne '') {
 6342:         $file_name =~s /^\Q$group\E//;
 6343:     }
 6344:     my $homeserver = &homeserver($uname,$udom);
 6345:     my $queryid=
 6346:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 6347:                ':'.&escape($file_name).':'.$action,$homeserver);
 6348:     my $reply = &get_query_reply($queryid);
 6349:     return $reply;
 6350: }
 6351: 
 6352: # -------------------------- Update MySQL allusers table
 6353: 
 6354: sub update_allusers_table {
 6355:     my ($uname,$udom,$names) = @_;
 6356:     my $homeserver = &homeserver($uname,$udom);
 6357:     my $queryid=
 6358:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 6359:                'lastname='.&escape($names->{'lastname'}).'%%'.
 6360:                'firstname='.&escape($names->{'firstname'}).'%%'.
 6361:                'middlename='.&escape($names->{'middlename'}).'%%'.
 6362:                'generation='.&escape($names->{'generation'}).'%%'.
 6363:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 6364:                'id='.&escape($names->{'id'}),$homeserver);
 6365:     return;
 6366: }
 6367: 
 6368: # ------- Request retrieval of institutional classlists for course(s)
 6369: 
 6370: sub fetch_enrollment_query {
 6371:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 6372:     my $homeserver;
 6373:     my $maxtries = 1;
 6374:     if ($context eq 'automated') {
 6375:         $homeserver = $perlvar{'lonHostID'};
 6376:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 6377:     } else {
 6378:         $homeserver = &homeserver($cnum,$dom);
 6379:     }
 6380:     my $host=&hostname($homeserver);
 6381:     my $cmd = '';
 6382:     foreach my $affiliate (keys(%{$affiliatesref})) {
 6383:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 6384:     }
 6385:     $cmd =~ s/%%$//;
 6386:     $cmd = &escape($cmd);
 6387:     my $query = 'fetchenrollment';
 6388:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 6389:     unless ($queryid=~/^\Q$host\E\_/) { 
 6390:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 6391:         return 'error: '.$queryid;
 6392:     }
 6393:     my $reply = &get_query_reply($queryid);
 6394:     my $tries = 1;
 6395:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 6396:         $reply = &get_query_reply($queryid);
 6397:         $tries ++;
 6398:     }
 6399:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 6400:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 6401:     } else {
 6402:         my @responses = split(/:/,$reply);
 6403:         if ($homeserver eq $perlvar{'lonHostID'}) {
 6404:             foreach my $line (@responses) {
 6405:                 my ($key,$value) = split(/=/,$line,2);
 6406:                 $$replyref{$key} = $value;
 6407:             }
 6408:         } else {
 6409:             my $pathname = LONCAPA::tempdir();
 6410:             foreach my $line (@responses) {
 6411:                 my ($key,$value) = split(/=/,$line);
 6412:                 $$replyref{$key} = $value;
 6413:                 if ($value > 0) {
 6414:                     foreach my $item (@{$$affiliatesref{$key}}) {
 6415:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 6416:                         my $destname = $pathname.'/'.$filename;
 6417:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 6418:                         if ($xml_classlist =~ /^error/) {
 6419:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 6420:                         } else {
 6421:                             if ( open(FILE,">$destname") ) {
 6422:                                 print FILE &unescape($xml_classlist);
 6423:                                 close(FILE);
 6424:                             } else {
 6425:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 6426:                             }
 6427:                         }
 6428:                     }
 6429:                 }
 6430:             }
 6431:         }
 6432:         return 'ok';
 6433:     }
 6434:     return 'error';
 6435: }
 6436: 
 6437: sub get_query_reply {
 6438:     my $queryid=shift;
 6439:     my $replyfile=LONCAPA::tempdir().$queryid;
 6440:     my $reply='';
 6441:     for (1..100) {
 6442: 	sleep 2;
 6443:         if (-e $replyfile.'.end') {
 6444: 	    if (open(my $fh,$replyfile)) {
 6445: 		$reply = join('',<$fh>);
 6446: 		close($fh);
 6447: 	   } else { return 'error: reply_file_error'; }
 6448:            return &unescape($reply);
 6449: 	}
 6450:     }
 6451:     return 'timeout:'.$queryid;
 6452: }
 6453: 
 6454: sub courselog_query {
 6455: #
 6456: # possible filters:
 6457: # url: url or symb
 6458: # username
 6459: # domain
 6460: # action: view, submit, grade
 6461: # start: timestamp
 6462: # end: timestamp
 6463: #
 6464:     my (%filters)=@_;
 6465:     unless ($env{'request.course.id'}) { return 'no_course'; }
 6466:     if ($filters{'url'}) {
 6467: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 6468:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 6469:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 6470:     }
 6471:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6472:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6473:     return &log_query($cname,$cdom,'courselog',%filters);
 6474: }
 6475: 
 6476: sub userlog_query {
 6477: #
 6478: # possible filters:
 6479: # action: log check role
 6480: # start: timestamp
 6481: # end: timestamp
 6482: #
 6483:     my ($uname,$udom,%filters)=@_;
 6484:     return &log_query($uname,$udom,'userlog',%filters);
 6485: }
 6486: 
 6487: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 6488: 
 6489: sub auto_run {
 6490:     my ($cnum,$cdom) = @_;
 6491:     my $response = 0;
 6492:     my $settings;
 6493:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 6494:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 6495:         $settings = $domconfig{'autoenroll'};
 6496:         if ($settings->{'run'} eq '1') {
 6497:             $response = 1;
 6498:         }
 6499:     } else {
 6500:         my $homeserver;
 6501:         if (&is_course($cdom,$cnum)) {
 6502:             $homeserver = &homeserver($cnum,$cdom);
 6503:         } else {
 6504:             $homeserver = &domain($cdom,'primary');
 6505:         }
 6506:         if ($homeserver ne 'no_host') {
 6507:             $response = &reply('autorun:'.$cdom,$homeserver);
 6508:         }
 6509:     }
 6510:     return $response;
 6511: }
 6512: 
 6513: sub auto_get_sections {
 6514:     my ($cnum,$cdom,$inst_coursecode) = @_;
 6515:     my $homeserver;
 6516:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 6517:         $homeserver = &homeserver($cnum,$cdom);
 6518:     }
 6519:     if (!defined($homeserver)) { 
 6520:         if ($cdom =~ /^$match_domain$/) {
 6521:             $homeserver = &domain($cdom,'primary');
 6522:         }
 6523:     }
 6524:     my @secs;
 6525:     if (defined($homeserver)) {
 6526:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 6527:         unless ($response eq 'refused') {
 6528:             @secs = split(/:/,$response);
 6529:         }
 6530:     }
 6531:     return @secs;
 6532: }
 6533: 
 6534: sub auto_new_course {
 6535:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 6536:     my $homeserver = &homeserver($cnum,$cdom);
 6537:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 6538:     return $response;
 6539: }
 6540: 
 6541: sub auto_validate_courseID {
 6542:     my ($cnum,$cdom,$inst_course_id) = @_;
 6543:     my $homeserver = &homeserver($cnum,$cdom);
 6544:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 6545:     return $response;
 6546: }
 6547: 
 6548: sub auto_validate_instcode {
 6549:     my ($cnum,$cdom,$instcode,$owner) = @_;
 6550:     my ($homeserver,$response);
 6551:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 6552:         $homeserver = &homeserver($cnum,$cdom);
 6553:     }
 6554:     if (!defined($homeserver)) {
 6555:         if ($cdom =~ /^$match_domain$/) {
 6556:             $homeserver = &domain($cdom,'primary');
 6557:         }
 6558:     }
 6559:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 6560:                         &escape($instcode).':'.&escape($owner),$homeserver));
 6561:     my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
 6562:     return ($outcome,$description);
 6563: }
 6564: 
 6565: sub auto_create_password {
 6566:     my ($cnum,$cdom,$authparam,$udom) = @_;
 6567:     my ($homeserver,$response);
 6568:     my $create_passwd = 0;
 6569:     my $authchk = '';
 6570:     if ($udom =~ /^$match_domain$/) {
 6571:         $homeserver = &domain($udom,'primary');
 6572:     }
 6573:     if ($homeserver eq '') {
 6574:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 6575:             $homeserver = &homeserver($cnum,$cdom);
 6576:         }
 6577:     }
 6578:     if ($homeserver eq '') {
 6579:         $authchk = 'nodomain';
 6580:     } else {
 6581:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 6582:         if ($response eq 'refused') {
 6583:             $authchk = 'refused';
 6584:         } else {
 6585:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 6586:         }
 6587:     }
 6588:     return ($authparam,$create_passwd,$authchk);
 6589: }
 6590: 
 6591: sub auto_photo_permission {
 6592:     my ($cnum,$cdom,$students) = @_;
 6593:     my $homeserver = &homeserver($cnum,$cdom);
 6594:     my ($outcome,$perm_reqd,$conditions) = 
 6595: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 6596:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 6597: 	return (undef,undef);
 6598:     }
 6599:     return ($outcome,$perm_reqd,$conditions);
 6600: }
 6601: 
 6602: sub auto_checkphotos {
 6603:     my ($uname,$udom,$pid) = @_;
 6604:     my $homeserver = &homeserver($uname,$udom);
 6605:     my ($result,$resulttype);
 6606:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 6607: 				   &escape($uname).':'.&escape($pid),
 6608: 				   $homeserver));
 6609:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 6610: 	return (undef,undef);
 6611:     }
 6612:     if ($outcome) {
 6613:         ($result,$resulttype) = split(/:/,$outcome);
 6614:     } 
 6615:     return ($result,$resulttype);
 6616: }
 6617: 
 6618: sub auto_photochoice {
 6619:     my ($cnum,$cdom) = @_;
 6620:     my $homeserver = &homeserver($cnum,$cdom);
 6621:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 6622: 						       &escape($cdom),
 6623: 						       $homeserver)));
 6624:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 6625: 	return (undef,undef);
 6626:     }
 6627:     return ($update,$comment);
 6628: }
 6629: 
 6630: sub auto_photoupdate {
 6631:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 6632:     my $homeserver = &homeserver($cnum,$dom);
 6633:     my $host=&hostname($homeserver);
 6634:     my $cmd = '';
 6635:     my $maxtries = 1;
 6636:     foreach my $affiliate (keys(%{$affiliatesref})) {
 6637:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 6638:     }
 6639:     $cmd =~ s/%%$//;
 6640:     $cmd = &escape($cmd);
 6641:     my $query = 'institutionalphotos';
 6642:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 6643:     unless ($queryid=~/^\Q$host\E\_/) {
 6644:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 6645:         return 'error: '.$queryid;
 6646:     }
 6647:     my $reply = &get_query_reply($queryid);
 6648:     my $tries = 1;
 6649:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 6650:         $reply = &get_query_reply($queryid);
 6651:         $tries ++;
 6652:     }
 6653:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 6654:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 6655:     } else {
 6656:         my @responses = split(/:/,$reply);
 6657:         my $outcome = shift(@responses); 
 6658:         foreach my $item (@responses) {
 6659:             my ($key,$value) = split(/=/,$item);
 6660:             $$photo{$key} = $value;
 6661:         }
 6662:         return $outcome;
 6663:     }
 6664:     return 'error';
 6665: }
 6666: 
 6667: sub auto_instcode_format {
 6668:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 6669: 	$cat_order) = @_;
 6670:     my $courses = '';
 6671:     my @homeservers;
 6672:     if ($caller eq 'global') {
 6673: 	my %servers = &get_servers($codedom,'library');
 6674: 	foreach my $tryserver (keys(%servers)) {
 6675: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 6676: 		push(@homeservers,$tryserver);
 6677: 	    }
 6678:         }
 6679:     } elsif ($caller eq 'requests') {
 6680:         if ($codedom =~ /^$match_domain$/) {
 6681:             my $chome = &domain($codedom,'primary');
 6682:             unless ($chome eq 'no_host') {
 6683:                 push(@homeservers,$chome);
 6684:             }
 6685:         }
 6686:     } else {
 6687:         push(@homeservers,&homeserver($caller,$codedom));
 6688:     }
 6689:     foreach my $code (keys(%{$instcodes})) {
 6690:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 6691:     }
 6692:     chop($courses);
 6693:     my $ok_response = 0;
 6694:     my $response;
 6695:     while (@homeservers > 0 && $ok_response == 0) {
 6696:         my $server = shift(@homeservers); 
 6697:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 6698:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 6699:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 6700: 		split(/:/,$response);
 6701:             %{$codes} = (%{$codes},&str2hash($codes_str));
 6702:             push(@{$codetitles},&str2array($codetitles_str));
 6703:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 6704:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 6705:             $ok_response = 1;
 6706:         }
 6707:     }
 6708:     if ($ok_response) {
 6709:         return 'ok';
 6710:     } else {
 6711:         return $response;
 6712:     }
 6713: }
 6714: 
 6715: sub auto_instcode_defaults {
 6716:     my ($domain,$returnhash,$code_order) = @_;
 6717:     my @homeservers;
 6718: 
 6719:     my %servers = &get_servers($domain,'library');
 6720:     foreach my $tryserver (keys(%servers)) {
 6721: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 6722: 	    push(@homeservers,$tryserver);
 6723: 	}
 6724:     }
 6725: 
 6726:     my $response;
 6727:     foreach my $server (@homeservers) {
 6728:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 6729:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 6730: 	
 6731: 	foreach my $pair (split(/\&/,$response)) {
 6732: 	    my ($name,$value)=split(/\=/,$pair);
 6733: 	    if ($name eq 'code_order') {
 6734: 		@{$code_order} = split(/\&/,&unescape($value));
 6735: 	    } else {
 6736: 		$returnhash->{&unescape($name)}=&unescape($value);
 6737: 	    }
 6738: 	}
 6739: 	return 'ok';
 6740:     }
 6741: 
 6742:     return $response;
 6743: }
 6744: 
 6745: sub auto_possible_instcodes {
 6746:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 6747:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 6748:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 6749:         return;
 6750:     }
 6751:     my (@homeservers,$uhome);
 6752:     if (defined(&domain($domain,'primary'))) {
 6753:         $uhome=&domain($domain,'primary');
 6754:         push(@homeservers,&domain($domain,'primary'));
 6755:     } else {
 6756:         my %servers = &get_servers($domain,'library');
 6757:         foreach my $tryserver (keys(%servers)) {
 6758:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 6759:                 push(@homeservers,$tryserver);
 6760:             }
 6761:         }
 6762:     }
 6763:     my $response;
 6764:     foreach my $server (@homeservers) {
 6765:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 6766:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 6767:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 6768:             split(':',$response);
 6769:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 6770:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 6771:         foreach my $item (split('&',$cat_title)) {   
 6772:             my ($name,$value)=split('=',$item);
 6773:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 6774:         }
 6775:         foreach my $item (split('&',$cat_order)) {
 6776:             my ($name,$value)=split('=',$item);
 6777:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 6778:         }
 6779:         return 'ok';
 6780:     }
 6781:     return $response;
 6782: }
 6783: 
 6784: sub auto_courserequest_checks {
 6785:     my ($dom) = @_;
 6786:     my ($homeserver,%validations);
 6787:     if ($dom =~ /^$match_domain$/) {
 6788:         $homeserver = &domain($dom,'primary');
 6789:     }
 6790:     unless ($homeserver eq 'no_host') {
 6791:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 6792:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 6793:             my @items = split(/&/,$response);
 6794:             foreach my $item (@items) {
 6795:                 my ($key,$value) = split('=',$item);
 6796:                 $validations{&unescape($key)} = &thaw_unescape($value);
 6797:             }
 6798:         }
 6799:     }
 6800:     return %validations; 
 6801: }
 6802: 
 6803: sub auto_courserequest_validation {
 6804:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
 6805:     my ($homeserver,$response);
 6806:     if ($dom =~ /^$match_domain$/) {
 6807:         $homeserver = &domain($dom,'primary');
 6808:     }
 6809:     unless ($homeserver eq 'no_host') {  
 6810:           
 6811:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 6812:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 6813:                                     ':'.&escape($instcode).':'.&escape($instseclist),
 6814:                                     $homeserver));
 6815:     }
 6816:     return $response;
 6817: }
 6818: 
 6819: sub auto_validate_class_sec {
 6820:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 6821:     my $homeserver = &homeserver($cnum,$cdom);
 6822:     my $ownerlist;
 6823:     if (ref($owners) eq 'ARRAY') {
 6824:         $ownerlist = join(',',@{$owners});
 6825:     } else {
 6826:         $ownerlist = $owners;
 6827:     }
 6828:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 6829:                         &escape($ownerlist).':'.$cdom,$homeserver);
 6830:     return $response;
 6831: }
 6832: 
 6833: # ------------------------------------------------------- Course Group routines
 6834: 
 6835: sub get_coursegroups {
 6836:     my ($cdom,$cnum,$group,$namespace) = @_;
 6837:     return(&dump($namespace,$cdom,$cnum,$group));
 6838: }
 6839: 
 6840: sub modify_coursegroup {
 6841:     my ($cdom,$cnum,$groupsettings) = @_;
 6842:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 6843: }
 6844: 
 6845: sub toggle_coursegroup_status {
 6846:     my ($cdom,$cnum,$group,$action) = @_;
 6847:     my ($from_namespace,$to_namespace);
 6848:     if ($action eq 'delete') {
 6849:         $from_namespace = 'coursegroups';
 6850:         $to_namespace = 'deleted_groups';
 6851:     } else {
 6852:         $from_namespace = 'deleted_groups';
 6853:         $to_namespace = 'coursegroups';
 6854:     }
 6855:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 6856:     if (my $tmp = &error(%curr_group)) {
 6857:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 6858:         return ('read error',$tmp);
 6859:     } else {
 6860:         my %savedsettings = %curr_group; 
 6861:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 6862:         my $deloutcome;
 6863:         if ($result eq 'ok') {
 6864:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 6865:         } else {
 6866:             return ('write error',$result);
 6867:         }
 6868:         if ($deloutcome eq 'ok') {
 6869:             return 'ok';
 6870:         } else {
 6871:             return ('delete error',$deloutcome);
 6872:         }
 6873:     }
 6874: }
 6875: 
 6876: sub modify_group_roles {
 6877:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 6878:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 6879:     my $role = 'gr/'.&escape($userprivs);
 6880:     my ($uname,$udom) = split(/:/,$user);
 6881:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 6882:     if ($result eq 'ok') {
 6883:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 6884:     }
 6885:     return $result;
 6886: }
 6887: 
 6888: sub modify_coursegroup_membership {
 6889:     my ($cdom,$cnum,$membership) = @_;
 6890:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 6891:     return $result;
 6892: }
 6893: 
 6894: sub get_active_groups {
 6895:     my ($udom,$uname,$cdom,$cnum) = @_;
 6896:     my $now = time;
 6897:     my %groups = ();
 6898:     foreach my $key (keys(%env)) {
 6899:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 6900:             my ($start,$end) = split(/\./,$env{$key});
 6901:             if (($end!=0) && ($end<$now)) { next; }
 6902:             if (($start!=0) && ($start>$now)) { next; }
 6903:             if ($1 eq $cdom && $2 eq $cnum) {
 6904:                 $groups{$3} = $env{$key} ;
 6905:             }
 6906:         }
 6907:     }
 6908:     return %groups;
 6909: }
 6910: 
 6911: sub get_group_membership {
 6912:     my ($cdom,$cnum,$group) = @_;
 6913:     return(&dump('groupmembership',$cdom,$cnum,$group));
 6914: }
 6915: 
 6916: sub get_users_groups {
 6917:     my ($udom,$uname,$courseid) = @_;
 6918:     my @usersgroups;
 6919:     my $cachetime=1800;
 6920: 
 6921:     my $hashid="$udom:$uname:$courseid";
 6922:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 6923:     if (defined($cached)) {
 6924:         @usersgroups = split(/:/,$grouplist);
 6925:     } else {  
 6926:         $grouplist = '';
 6927:         my $courseurl = &courseid_to_courseurl($courseid);
 6928:         my $extra = &freeze_escape({'skipcheck' => 1});
 6929:         my %roleshash = &dump('roles',$udom,$uname,$courseurl,undef,$extra);
 6930:         my $access_end = $env{'course.'.$courseid.
 6931:                               '.default_enrollment_end_date'};
 6932:         my $now = time;
 6933:         foreach my $key (keys(%roleshash)) {
 6934:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 6935:                 my $group = $1;
 6936:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 6937:                     my $start = $2;
 6938:                     my $end = $1;
 6939:                     if ($start == -1) { next; } # deleted from group
 6940:                     if (($start!=0) && ($start>$now)) { next; }
 6941:                     if (($end!=0) && ($end<$now)) {
 6942:                         if ($access_end && $access_end < $now) {
 6943:                             if ($access_end - $end < 86400) {
 6944:                                 push(@usersgroups,$group);
 6945:                             }
 6946:                         }
 6947:                         next;
 6948:                     }
 6949:                     push(@usersgroups,$group);
 6950:                 }
 6951:             }
 6952:         }
 6953:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 6954:         $grouplist = join(':',@usersgroups);
 6955:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 6956:     }
 6957:     return @usersgroups;
 6958: }
 6959: 
 6960: sub devalidate_getgroups_cache {
 6961:     my ($udom,$uname,$cdom,$cnum)=@_;
 6962:     my $courseid = $cdom.'_'.$cnum;
 6963: 
 6964:     my $hashid="$udom:$uname:$courseid";
 6965:     &devalidate_cache_new('getgroups',$hashid);
 6966: }
 6967: 
 6968: # ------------------------------------------------------------------ Plain Text
 6969: 
 6970: sub plaintext {
 6971:     my ($short,$type,$cid,$forcedefault) = @_;
 6972:     if ($short =~ m{^cr/}) {
 6973: 	return (split('/',$short))[-1];
 6974:     }
 6975:     if (!defined($cid)) {
 6976:         $cid = $env{'request.course.id'};
 6977:     }
 6978:     my %rolenames = (
 6979:                       Course    => 'std',
 6980:                       Community => 'alt1',
 6981:                     );
 6982:     if ($cid ne '') {
 6983:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 6984:             unless ($forcedefault) {
 6985:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 6986:                 &Apache::lonlocal::mt_escape(\$roletext);
 6987:                 return &Apache::lonlocal::mt($roletext);
 6988:             }
 6989:         }
 6990:     }
 6991:     if ((defined($type)) && (defined($rolenames{$type})) &&
 6992:         (defined($rolenames{$type})) && 
 6993:         (defined($prp{$short}{$rolenames{$type}}))) {
 6994:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 6995:     } elsif ($cid ne '') {
 6996:         my $crstype = $env{'course.'.$cid.'.type'};
 6997:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
 6998:             (defined($prp{$short}{$rolenames{$crstype}}))) {
 6999:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
 7000:         }
 7001:     }
 7002:     return &Apache::lonlocal::mt($prp{$short}{'std'});
 7003: }
 7004: 
 7005: # ----------------------------------------------------------------- Assign Role
 7006: 
 7007: sub assignrole {
 7008:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 7009:         $context)=@_;
 7010:     my $mrole;
 7011:     if ($role =~ /^cr\//) {
 7012:         my $cwosec=$url;
 7013:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 7014: 	unless (&allowed('ccr',$cwosec)) {
 7015:            my $refused = 1;
 7016:            if ($context eq 'requestcourses') {
 7017:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 7018:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
 7019:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
 7020:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 7021:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 7022:                            if ($crsenv{'internal.courseowner'} eq
 7023:                                $env{'user.name'}.':'.$env{'user.domain'}) {
 7024:                                $refused = '';
 7025:                            }
 7026:                        }
 7027:                    }
 7028:                }
 7029:            }
 7030:            if ($refused) {
 7031:                &logthis('Refused custom assignrole: '.
 7032:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
 7033:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
 7034:                return 'refused';
 7035:            }
 7036:         }
 7037:         $mrole='cr';
 7038:     } elsif ($role =~ /^gr\//) {
 7039:         my $cwogrp=$url;
 7040:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 7041:         unless (&allowed('mdg',$cwogrp)) {
 7042:             &logthis('Refused group assignrole: '.
 7043:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 7044:                     $env{'user.name'}.' at '.$env{'user.domain'});
 7045:             return 'refused';
 7046:         }
 7047:         $mrole='gr';
 7048:     } else {
 7049:         my $cwosec=$url;
 7050:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 7051:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 7052:             my $refused;
 7053:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 7054:                 if (!(&allowed('c'.$role,$url))) {
 7055:                     $refused = 1;
 7056:                 }
 7057:             } else {
 7058:                 $refused = 1;
 7059:             }
 7060:             if ($refused) {
 7061:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 7062:                 if (!$selfenroll && $context eq 'course') {
 7063:                     my %crsenv;
 7064:                     if ($role eq 'cc' || $role eq 'co') {
 7065:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 7066:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
 7067:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
 7068:                                 if ($crsenv{'internal.courseowner'} eq 
 7069:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 7070:                                     $refused = '';
 7071:                                 }
 7072:                             }
 7073:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
 7074:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
 7075:                                 if ($crsenv{'internal.courseowner'} eq 
 7076:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 7077:                                     $refused = '';
 7078:                                 }
 7079:                             }
 7080:                         }
 7081:                     }
 7082:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7083:                     $refused = '';
 7084:                 } elsif ($context eq 'requestcourses') {
 7085:                     my @possroles = ('st','ta','ep','in','cc','co');
 7086:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
 7087:                         my $wrongcc;
 7088:                         if ($cnum =~ /^$match_community$/) {
 7089:                             $wrongcc = 1 if ($role eq 'cc');
 7090:                         } else {
 7091:                             $wrongcc = 1 if ($role eq 'co');
 7092:                         }
 7093:                         unless ($wrongcc) {
 7094:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 7095:                             if ($crsenv{'internal.courseowner'} eq 
 7096:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
 7097:                                 $refused = '';
 7098:                             }
 7099:                         }
 7100:                     }
 7101:                 }
 7102:                 if ($refused) {
 7103:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 7104:                              ' '.$role.' '.$end.' '.$start.' by '.
 7105: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 7106:                     return 'refused';
 7107:                 }
 7108:             }
 7109:         } elsif ($role eq 'au') {
 7110:             if ($url ne '/'.$udom.'/') {
 7111:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
 7112:                          ' to assign author role for '.$uname.':'.$udom.
 7113:                          ' in domain: '.$url.' refused (wrong domain).');
 7114:                 return 'refused';
 7115:             }
 7116:         }
 7117:         $mrole=$role;
 7118:     }
 7119:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 7120:                 "$udom:$uname:$url".'_'."$mrole=$role";
 7121:     if ($end) { $command.='_'.$end; }
 7122:     if ($start) {
 7123: 	if ($end) { 
 7124:            $command.='_'.$start; 
 7125:         } else {
 7126:            $command.='_0_'.$start;
 7127:         }
 7128:     }
 7129:     my $origstart = $start;
 7130:     my $origend = $end;
 7131:     my $delflag;
 7132: # actually delete
 7133:     if ($deleteflag) {
 7134: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 7135: # modify command to delete the role
 7136:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 7137:                 "$udom:$uname:$url".'_'."$mrole";
 7138: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 7139: # set start and finish to negative values for userrolelog
 7140:            $start=-1;
 7141:            $end=-1;
 7142:            $delflag = 1;
 7143:         }
 7144:     }
 7145: # send command
 7146:     my $answer=&reply($command,&homeserver($uname,$udom));
 7147: # log new user role if status is ok
 7148:     if ($answer eq 'ok') {
 7149: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 7150: # for course roles, perform group memberships changes triggered by role change.
 7151:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
 7152:         unless ($role =~ /^gr/) {
 7153:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 7154:                                              $origstart,$selfenroll,$context);
 7155:         }
 7156:         if ($role eq 'cc') {
 7157:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
 7158:         }
 7159:     }
 7160:     return $answer;
 7161: }
 7162: 
 7163: sub autoupdate_coowners {
 7164:     my ($url,$end,$start,$uname,$udom) = @_;
 7165:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
 7166:     if (($cdom ne '') && ($cnum ne '')) {
 7167:         my $now = time;
 7168:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
 7169:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
 7170:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
 7171:             my $instcode = $coursehash{'internal.coursecode'};
 7172:             if ($instcode ne '') {
 7173:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
 7174:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
 7175:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
 7176:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
 7177:                         if ($result eq 'valid') {
 7178:                             if ($coursehash{'internal.co-owners'}) {
 7179:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 7180:                                     push(@newcoowners,$coowner);
 7181:                                 }
 7182:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
 7183:                                     push(@newcoowners,$uname.':'.$udom);
 7184:                                 }
 7185:                                 @newcoowners = sort(@newcoowners);
 7186:                             } else {
 7187:                                 push(@newcoowners,$uname.':'.$udom);
 7188:                             }
 7189:                         } else {
 7190:                             if ($coursehash{'internal.co-owners'}) {
 7191:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 7192:                                     unless ($coowner eq $uname.':'.$udom) {
 7193:                                         push(@newcoowners,$coowner);
 7194:                                     }
 7195:                                 }
 7196:                                 unless (@newcoowners > 0) {
 7197:                                     $delcoowners = 1;
 7198:                                     $coowners = '';
 7199:                                 }
 7200:                             }
 7201:                         }
 7202:                         if (@newcoowners || $delcoowners) {
 7203:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
 7204:                                             $delcoowners,@newcoowners);
 7205:                         }
 7206:                     }
 7207:                 }
 7208:             }
 7209:         }
 7210:     }
 7211: }
 7212: 
 7213: sub store_coowners {
 7214:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
 7215:     my $cid = $cdom.'_'.$cnum;
 7216:     my ($coowners,$delresult,$putresult);
 7217:     if (@newcoowners) {
 7218:         $coowners = join(',',@newcoowners);
 7219:         my %coownershash = (
 7220:                             'internal.co-owners' => $coowners,
 7221:                            );
 7222:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
 7223:         if ($putresult eq 'ok') {
 7224:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
 7225:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
 7226:             }
 7227:         }
 7228:     }
 7229:     if ($delcoowners) {
 7230:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
 7231:         if ($delresult eq 'ok') {
 7232:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
 7233:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
 7234:             }
 7235:         }
 7236:     }
 7237:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
 7238:         my %crsinfo =
 7239:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 7240:         if (ref($crsinfo{$cid}) eq 'HASH') {
 7241:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
 7242:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
 7243:         }
 7244:     }
 7245: }
 7246: 
 7247: # -------------------------------------------------- Modify user authentication
 7248: # Overrides without validation
 7249: 
 7250: sub modifyuserauth {
 7251:     my ($udom,$uname,$umode,$upass)=@_;
 7252:     my $uhome=&homeserver($uname,$udom);
 7253:     unless (&allowed('mau',$udom)) { return 'refused'; }
 7254:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 7255:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 7256:              ' in domain '.$env{'request.role.domain'});  
 7257:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 7258: 		     &escape($upass),$uhome);
 7259:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 7260:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 7261:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 7262:     &log($udom,,$uname,$uhome,
 7263:         'Authentication changed by '.$env{'user.domain'}.', '.
 7264:                                      $env{'user.name'}.', '.$umode.
 7265:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 7266:     unless ($reply eq 'ok') {
 7267:         &logthis('Authentication mode error: '.$reply);
 7268: 	return 'error: '.$reply;
 7269:     }   
 7270:     return 'ok';
 7271: }
 7272: 
 7273: # --------------------------------------------------------------- Modify a user
 7274: 
 7275: sub modifyuser {
 7276:     my ($udom,    $uname, $uid,
 7277:         $umode,   $upass, $first,
 7278:         $middle,  $last,  $gene,
 7279:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
 7280:     $udom= &LONCAPA::clean_domain($udom);
 7281:     $uname=&LONCAPA::clean_username($uname);
 7282:     my $showcandelete = 'none';
 7283:     if (ref($candelete) eq 'ARRAY') {
 7284:         if (@{$candelete} > 0) {
 7285:             $showcandelete = join(', ',@{$candelete});
 7286:         }
 7287:     }
 7288:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 7289:              $umode.', '.$first.', '.$middle.', '.
 7290: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
 7291:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 7292:                                      ' desiredhome not specified'). 
 7293:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 7294:              ' in domain '.$env{'request.role.domain'});
 7295:     my $uhome=&homeserver($uname,$udom,'true');
 7296:     my $newuser;
 7297:     if ($uhome eq 'no_host') {
 7298:         $newuser = 1;
 7299:     }
 7300: # ----------------------------------------------------------------- Create User
 7301:     if (($uhome eq 'no_host') && 
 7302: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 7303:         my $unhome='';
 7304:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 7305:             $unhome = $desiredhome;
 7306: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 7307: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 7308:         } else { # load balancing routine for determining $unhome
 7309:             my $loadm=10000000;
 7310: 	    my %servers = &get_servers($udom,'library');
 7311: 	    foreach my $tryserver (keys(%servers)) {
 7312: 		my $answer=reply('load',$tryserver);
 7313: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 7314: 		    $loadm=$answer;
 7315: 		    $unhome=$tryserver;
 7316: 		}
 7317: 	    }
 7318:         }
 7319:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 7320: 	    return 'error: unable to find a home server for '.$uname.
 7321:                    ' in domain '.$udom;
 7322:         }
 7323:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 7324:                          &escape($upass),$unhome);
 7325: 	unless ($reply eq 'ok') {
 7326:             return 'error: '.$reply;
 7327:         }   
 7328:         $uhome=&homeserver($uname,$udom,'true');
 7329:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 7330: 	    return 'error: unable verify users home machine.';
 7331:         }
 7332:     }   # End of creation of new user
 7333: # ---------------------------------------------------------------------- Add ID
 7334:     if ($uid) {
 7335:        $uid=~tr/A-Z/a-z/;
 7336:        my %uidhash=&idrget($udom,$uname);
 7337:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 7338:          && (!$forceid)) {
 7339: 	  unless ($uid eq $uidhash{$uname}) {
 7340: 	      return 'error: user id "'.$uid.'" does not match '.
 7341:                   'current user id "'.$uidhash{$uname}.'".';
 7342:           }
 7343:        } else {
 7344: 	  &idput($udom,($uname => $uid));
 7345:        }
 7346:     }
 7347: # -------------------------------------------------------------- Add names, etc
 7348:     my @tmp=&get('environment',
 7349: 		   ['firstname','middlename','lastname','generation','id',
 7350:                     'permanentemail','inststatus'],
 7351: 		   $udom,$uname);
 7352:     my (%names,%oldnames);
 7353:     if ($tmp[0] =~ m/^error:.*/) { 
 7354:         %names=(); 
 7355:     } else {
 7356:         %names = @tmp;
 7357:         %oldnames = %names;
 7358:     }
 7359: #
 7360: # If name, email and/or uid are blank (e.g., because an uploaded file
 7361: # of users did not contain them), do not overwrite existing values
 7362: # unless field is in $candelete array ref.  
 7363: #
 7364: 
 7365:     my @fields = ('firstname','middlename','lastname','generation',
 7366:                   'permanentemail','id');
 7367:     my %newvalues;
 7368:     if (ref($candelete) eq 'ARRAY') {
 7369:         foreach my $field (@fields) {
 7370:             if (grep(/^\Q$field\E$/,@{$candelete})) {
 7371:                 if ($field eq 'firstname') {
 7372:                     $names{$field} = $first;
 7373:                 } elsif ($field eq 'middlename') {
 7374:                     $names{$field} = $middle;
 7375:                 } elsif ($field eq 'lastname') {
 7376:                     $names{$field} = $last;
 7377:                 } elsif ($field eq 'generation') { 
 7378:                     $names{$field} = $gene;
 7379:                 } elsif ($field eq 'permanentemail') {
 7380:                     $names{$field} = $email;
 7381:                 } elsif ($field eq 'id') {
 7382:                     $names{$field}  = $uid;
 7383:                 }
 7384:             }
 7385:         }
 7386:     }
 7387:     if ($first)  { $names{'firstname'}  = $first; }
 7388:     if (defined($middle)) { $names{'middlename'} = $middle; }
 7389:     if ($last)   { $names{'lastname'}   = $last; }
 7390:     if (defined($gene))   { $names{'generation'} = $gene; }
 7391:     if ($email) {
 7392:        $email=~s/[^\w\@\.\-\,]//gs;
 7393:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 7394:     }
 7395:     if ($uid) { $names{'id'}  = $uid; }
 7396:     if (defined($inststatus)) {
 7397:         $names{'inststatus'} = '';
 7398:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
 7399:         if (ref($usertypes) eq 'HASH') {
 7400:             my @okstatuses; 
 7401:             foreach my $item (split(/:/,$inststatus)) {
 7402:                 if (defined($usertypes->{$item})) {
 7403:                     push(@okstatuses,$item);  
 7404:                 }
 7405:             }
 7406:             if (@okstatuses) {
 7407:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
 7408:             }
 7409:         }
 7410:     }
 7411:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
 7412:                  $umode.', '.$first.', '.$middle.', '.
 7413:                  $last.', '.$gene.', '.$email.', '.$inststatus;
 7414:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 7415:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 7416:     } else {
 7417:         $logmsg .= ' during self creation';
 7418:     }
 7419:     my $changed;
 7420:     if ($newuser) {
 7421:         $changed = 1;
 7422:     } else {
 7423:         foreach my $field (@fields) {
 7424:             if ($names{$field} ne $oldnames{$field}) {
 7425:                 $changed = 1;
 7426:                 last;
 7427:             }
 7428:         }
 7429:     }
 7430:     unless ($changed) {
 7431:         $logmsg = 'No changes in user information needed for: '.$logmsg;
 7432:         &logthis($logmsg);
 7433:         return 'ok';
 7434:     }
 7435:     my $reply = &put('environment', \%names, $udom,$uname);
 7436:     if ($reply ne 'ok') { 
 7437:         return 'error: '.$reply;
 7438:     }
 7439:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
 7440:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
 7441:     }
 7442:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 7443:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 7444:     $logmsg = 'Success modifying user '.$logmsg;
 7445:     &logthis($logmsg);
 7446:     return 'ok';
 7447: }
 7448: 
 7449: # -------------------------------------------------------------- Modify student
 7450: 
 7451: sub modifystudent {
 7452:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 7453:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 7454:         $selfenroll,$context,$inststatus)=@_;
 7455:     if (!$cid) {
 7456: 	unless ($cid=$env{'request.course.id'}) {
 7457: 	    return 'not_in_class';
 7458: 	}
 7459:     }
 7460: # --------------------------------------------------------------- Make the user
 7461:     my $reply=&modifyuser
 7462: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 7463:          $desiredhome,$email,$inststatus);
 7464:     unless ($reply eq 'ok') { return $reply; }
 7465:     # This will cause &modify_student_enrollment to get the uid from the
 7466:     # students environment
 7467:     $uid = undef if (!$forceid);
 7468:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 7469: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
 7470:     return $reply;
 7471: }
 7472: 
 7473: sub modify_student_enrollment {
 7474:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
 7475:     my ($cdom,$cnum,$chome);
 7476:     if (!$cid) {
 7477: 	unless ($cid=$env{'request.course.id'}) {
 7478: 	    return 'not_in_class';
 7479: 	}
 7480: 	$cdom=$env{'course.'.$cid.'.domain'};
 7481: 	$cnum=$env{'course.'.$cid.'.num'};
 7482:     } else {
 7483: 	($cdom,$cnum)=split(/_/,$cid);
 7484:     }
 7485:     $chome=$env{'course.'.$cid.'.home'};
 7486:     if (!$chome) {
 7487: 	$chome=&homeserver($cnum,$cdom);
 7488:     }
 7489:     if (!$chome) { return 'unknown_course'; }
 7490:     # Make sure the user exists
 7491:     my $uhome=&homeserver($uname,$udom);
 7492:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 7493: 	return 'error: no such user';
 7494:     }
 7495:     # Get student data if we were not given enough information
 7496:     if (!defined($first)  || $first  eq '' || 
 7497:         !defined($last)   || $last   eq '' || 
 7498:         !defined($uid)    || $uid    eq '' || 
 7499:         !defined($middle) || $middle eq '' || 
 7500:         !defined($gene)   || $gene   eq '') {
 7501:         # They did not supply us with enough data to enroll the student, so
 7502:         # we need to pick up more information.
 7503:         my %tmp = &get('environment',
 7504:                        ['firstname','middlename','lastname', 'generation','id']
 7505:                        ,$udom,$uname);
 7506: 
 7507:         #foreach my $key (keys(%tmp)) {
 7508:         #    &logthis("key $key = ".$tmp{$key});
 7509:         #}
 7510:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 7511:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 7512:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 7513:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 7514:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 7515:     }
 7516:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 7517:     my $reply=cput('classlist',
 7518: 		   {"$uname:$udom" => 
 7519: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
 7520: 		   $cdom,$cnum);
 7521:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
 7522: 	return 'error: '.$reply;
 7523:     } else {
 7524: 	&devalidate_getsection_cache($udom,$uname,$cid);
 7525:     }
 7526:     # Add student role to user
 7527:     my $uurl='/'.$cid;
 7528:     $uurl=~s/\_/\//g;
 7529:     if ($usec) {
 7530: 	$uurl.='/'.$usec;
 7531:     }
 7532:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
 7533: }
 7534: 
 7535: sub format_name {
 7536:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 7537:     my $name;
 7538:     if ($first ne 'lastname') {
 7539: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 7540:     } else {
 7541: 	if ($lastname=~/\S/) {
 7542: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 7543: 	    $name=~s/\s+,/,/;
 7544: 	} else {
 7545: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 7546: 	}
 7547:     }
 7548:     $name=~s/^\s+//;
 7549:     $name=~s/\s+$//;
 7550:     $name=~s/\s+/ /g;
 7551:     return $name;
 7552: }
 7553: 
 7554: # ------------------------------------------------- Write to course preferences
 7555: 
 7556: sub writecoursepref {
 7557:     my ($courseid,%prefs)=@_;
 7558:     $courseid=~s/^\///;
 7559:     $courseid=~s/\_/\//g;
 7560:     my ($cdomain,$cnum)=split(/\//,$courseid);
 7561:     my $chome=homeserver($cnum,$cdomain);
 7562:     if (($chome eq '') || ($chome eq 'no_host')) { 
 7563: 	return 'error: no such course';
 7564:     }
 7565:     my $cstring='';
 7566:     foreach my $pref (keys(%prefs)) {
 7567: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 7568:     }
 7569:     $cstring=~s/\&$//;
 7570:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 7571: }
 7572: 
 7573: # ---------------------------------------------------------- Make/modify course
 7574: 
 7575: sub createcourse {
 7576:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 7577:         $course_owner,$crstype,$cnum,$context,$category)=@_;
 7578:     $url=&declutter($url);
 7579:     my $cid='';
 7580:     if ($context eq 'requestcourses') {
 7581:         my $can_create = 0;
 7582:         my ($ownername,$ownerdom) = split(':',$course_owner);
 7583:         if ($udom eq $ownerdom) {
 7584:             if (&usertools_access($ownername,$ownerdom,$category,undef,
 7585:                                   $context)) {
 7586:                 $can_create = 1;
 7587:             }
 7588:         } else {
 7589:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
 7590:                                            $category);
 7591:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
 7592:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
 7593:                 if (@curr > 0) {
 7594:                     my @options = qw(approval validate autolimit);
 7595:                     my $optregex = join('|',@options);
 7596:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
 7597:                         $can_create = 1;
 7598:                     }
 7599:                 }
 7600:             }
 7601:         }
 7602:         if ($can_create) {
 7603:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
 7604:                 unless (&allowed('ccc',$udom)) {
 7605:                     return 'refused'; 
 7606:                 }
 7607:             }
 7608:         } else {
 7609:             return 'refused';
 7610:         }
 7611:     } elsif (!&allowed('ccc',$udom)) {
 7612:         return 'refused';
 7613:     }
 7614: # --------------------------------------------------------------- Get Unique ID
 7615:     my $uname;
 7616:     if ($cnum =~ /^$match_courseid$/) {
 7617:         my $chome=&homeserver($cnum,$udom,'true');
 7618:         if (($chome eq '') || ($chome eq 'no_host')) {
 7619:             $uname = $cnum;
 7620:         } else {
 7621:             $uname = &generate_coursenum($udom,$crstype);
 7622:         }
 7623:     } else {
 7624:         $uname = &generate_coursenum($udom,$crstype);
 7625:     }
 7626:     return $uname if ($uname =~ /^error/);
 7627: # -------------------------------------------------- Check supplied server name
 7628:     if (!defined($course_server)) {
 7629:         if (defined(&domain($udom,'primary'))) {
 7630:             $course_server = &domain($udom,'primary');
 7631:         } else {
 7632:             $course_server = $env{'user.home'}; 
 7633:         }
 7634:     }
 7635:     my %host_servers =
 7636:         &Apache::lonnet::get_servers($udom,'library');
 7637:     unless ($host_servers{$course_server}) {
 7638:         return 'error: invalid home server for course: '.$course_server;
 7639:     }
 7640: # ------------------------------------------------------------- Make the course
 7641:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 7642:                       $course_server);
 7643:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 7644:     my $uhome=&homeserver($uname,$udom,'true');
 7645:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 7646: 	return 'error: no such course';
 7647:     }
 7648: # ----------------------------------------------------------------- Course made
 7649: # log existence
 7650:     my $now = time;
 7651:     my $newcourse = {
 7652:                     $udom.'_'.$uname => {
 7653:                                      description => $description,
 7654:                                      inst_code   => $inst_code,
 7655:                                      owner       => $course_owner,
 7656:                                      type        => $crstype,
 7657:                                      creator     => $env{'user.name'}.':'.
 7658:                                                     $env{'user.domain'},
 7659:                                      created     => $now,
 7660:                                      context     => $context,
 7661:                                                 },
 7662:                     };
 7663:     &courseidput($udom,$newcourse,$uhome,'notime');
 7664: # set toplevel url
 7665:     my $topurl=$url;
 7666:     unless ($nonstandard) {
 7667: # ------------------------------------------ For standard courses, make top url
 7668:         my $mapurl=&clutter($url);
 7669:         if ($mapurl eq '/res/') { $mapurl=''; }
 7670:         $env{'form.initmap'}=(<<ENDINITMAP);
 7671: <map>
 7672: <resource id="1" type="start"></resource>
 7673: <resource id="2" src="$mapurl"></resource>
 7674: <resource id="3" type="finish"></resource>
 7675: <link index="1" from="1" to="2"></link>
 7676: <link index="2" from="2" to="3"></link>
 7677: </map>
 7678: ENDINITMAP
 7679:         $topurl=&declutter(
 7680:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 7681:                           );
 7682:     }
 7683: # ----------------------------------------------------------- Write preferences
 7684:     &writecoursepref($udom.'_'.$uname,
 7685:                      ('description'              => $description,
 7686:                       'url'                      => $topurl,
 7687:                       'internal.creator'         => $env{'user.name'}.':'.
 7688:                                                     $env{'user.domain'},
 7689:                       'internal.created'         => $now,
 7690:                       'internal.creationcontext' => $context)
 7691:                     );
 7692:     return '/'.$udom.'/'.$uname;
 7693: }
 7694: 
 7695: # ------------------------------------------------------------------- Create ID
 7696: sub generate_coursenum {
 7697:     my ($udom,$crstype) = @_;
 7698:     my $domdesc = &domain($udom);
 7699:     return 'error: invalid domain' if ($domdesc eq '');
 7700:     my $first;
 7701:     if ($crstype eq 'Community') {
 7702:         $first = '0';
 7703:     } else {
 7704:         $first = int(1+rand(9)); 
 7705:     } 
 7706:     my $uname=$first.
 7707:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 7708:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
 7709:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 7710: # ----------------------------------------------- Make sure that does not exist
 7711:     my $uhome=&homeserver($uname,$udom,'true');
 7712:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
 7713:         if ($crstype eq 'Community') {
 7714:             $first = '0';
 7715:         } else {
 7716:             $first = int(1+rand(9));
 7717:         }
 7718:         $uname=$first.
 7719:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 7720:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
 7721:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 7722:         $uhome=&homeserver($uname,$udom,'true');
 7723:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
 7724:             return 'error: unable to generate unique course-ID';
 7725:         }
 7726:     }
 7727:     return $uname;
 7728: }
 7729: 
 7730: sub is_course {
 7731:     my ($cdom,$cnum) = @_;
 7732:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
 7733: 				undef,'.');
 7734:     if (exists($courses{$cdom.'_'.$cnum})) {
 7735:         return 1;
 7736:     }
 7737:     return 0;
 7738: }
 7739: 
 7740: sub store_userdata {
 7741:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
 7742:     my $result;
 7743:     if ($datakey ne '') {
 7744:         if (ref($storehash) eq 'HASH') {
 7745:             if ($udom eq '' || $uname eq '') {
 7746:                 $udom = $env{'user.domain'};
 7747:                 $uname = $env{'user.name'};
 7748:             }
 7749:             my $uhome=&homeserver($uname,$udom);
 7750:             if (($uhome eq '') || ($uhome eq 'no_host')) {
 7751:                 $result = 'error: no_host';
 7752:             } else {
 7753:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
 7754:                 $storehash->{'host'} = $perlvar{'lonHostID'};
 7755: 
 7756:                 my $namevalue='';
 7757:                 foreach my $key (keys(%{$storehash})) {
 7758:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 7759:                 }
 7760:                 $namevalue=~s/\&$//;
 7761:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
 7762:                                   $namevalue,$uhome);
 7763:             }
 7764:         } else {
 7765:             $result = 'error: data to store was not a hash reference'; 
 7766:         }
 7767:     } else {
 7768:         $result= 'error: invalid requestkey'; 
 7769:     }
 7770:     return $result;
 7771: }
 7772: 
 7773: # ---------------------------------------------------------- Assign Custom Role
 7774: 
 7775: sub assigncustomrole {
 7776:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
 7777:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 7778:                        $end,$start,$deleteflag,$selfenroll,$context);
 7779: }
 7780: 
 7781: # ----------------------------------------------------------------- Revoke Role
 7782: 
 7783: sub revokerole {
 7784:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
 7785:     my $now=time;
 7786:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
 7787: }
 7788: 
 7789: # ---------------------------------------------------------- Revoke Custom Role
 7790: 
 7791: sub revokecustomrole {
 7792:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
 7793:     my $now=time;
 7794:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 7795:            $deleteflag,$selfenroll,$context);
 7796: }
 7797: 
 7798: # ------------------------------------------------------------ Disk usage
 7799: sub diskusage {
 7800:     my ($udom,$uname,$directorypath,$getpropath)=@_;
 7801:     $directorypath =~ s/\/$//;
 7802:     my $listing=&reply('du2:'.&escape($directorypath).':'
 7803:                        .&escape($getpropath).':'.&escape($uname).':'
 7804:                        .&escape($udom),homeserver($uname,$udom));
 7805:     if ($listing eq 'unknown_cmd') {
 7806:         if ($getpropath) {
 7807:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
 7808:         }
 7809:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
 7810:     }
 7811:     return $listing;
 7812: }
 7813: 
 7814: sub is_locked {
 7815:     my ($file_name, $domain, $user, $which) = @_;
 7816:     my @check;
 7817:     my $is_locked;
 7818:     push (@check,$file_name);
 7819:     my %locked = &get('file_permissions',\@check,
 7820: 		      $env{'user.domain'},$env{'user.name'});
 7821:     my ($tmp)=keys(%locked);
 7822:     if ($tmp=~/^error:/) { undef(%locked); }
 7823:     
 7824:     if (ref($locked{$file_name}) eq 'ARRAY') {
 7825:         $is_locked = 'false';
 7826:         foreach my $entry (@{$locked{$file_name}}) {
 7827:            if (ref($entry) eq 'ARRAY') {
 7828:                $is_locked = 'true';
 7829:                if (ref($which) eq 'ARRAY') {
 7830:                    push(@{$which},$entry);
 7831:                } else {
 7832:                    last;
 7833:                }
 7834:            }
 7835:        }
 7836:     } else {
 7837:         $is_locked = 'false';
 7838:     }
 7839:     return $is_locked;
 7840: }
 7841: 
 7842: sub declutter_portfile {
 7843:     my ($file) = @_;
 7844:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 7845:     return $file;
 7846: }
 7847: 
 7848: # ------------------------------------------------------------- Mark as Read Only
 7849: 
 7850: sub mark_as_readonly {
 7851:     my ($domain,$user,$files,$what) = @_;
 7852:     my %current_permissions = &dump('file_permissions',$domain,$user);
 7853:     my ($tmp)=keys(%current_permissions);
 7854:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 7855:     foreach my $file (@{$files}) {
 7856: 	$file = &declutter_portfile($file);
 7857:         push(@{$current_permissions{$file}},$what);
 7858:     }
 7859:     &put('file_permissions',\%current_permissions,$domain,$user);
 7860:     return;
 7861: }
 7862: 
 7863: # ------------------------------------------------------------Save Selected Files
 7864: 
 7865: sub save_selected_files {
 7866:     my ($user, $path, @files) = @_;
 7867:     my $filename = $user."savedfiles";
 7868:     my @other_files = &files_not_in_path($user, $path);
 7869:     open (OUT, '>'.$tmpdir.$filename);
 7870:     foreach my $file (@files) {
 7871:         print (OUT $env{'form.currentpath'}.$file."\n");
 7872:     }
 7873:     foreach my $file (@other_files) {
 7874:         print (OUT $file."\n");
 7875:     }
 7876:     close (OUT);
 7877:     return 'ok';
 7878: }
 7879: 
 7880: sub clear_selected_files {
 7881:     my ($user) = @_;
 7882:     my $filename = $user."savedfiles";
 7883:     open (OUT, '>'.LONCAPA::tempdir().$filename);
 7884:     print (OUT undef);
 7885:     close (OUT);
 7886:     return ("ok");    
 7887: }
 7888: 
 7889: sub files_in_path {
 7890:     my ($user, $path) = @_;
 7891:     my $filename = $user."savedfiles";
 7892:     my %return_files;
 7893:     open (IN, '<'.LONCAPA::tempdir().$filename);
 7894:     while (my $line_in = <IN>) {
 7895:         chomp ($line_in);
 7896:         my @paths_and_file = split (m!/!, $line_in);
 7897:         my $file_part = pop (@paths_and_file);
 7898:         my $path_part = join ('/', @paths_and_file);
 7899:         $path_part.='/';
 7900:         my $path_and_file = $path_part.$file_part;
 7901:         if ($path_part eq $path) {
 7902:             $return_files{$file_part}= 'selected';
 7903:         }
 7904:     }
 7905:     close (IN);
 7906:     return (\%return_files);
 7907: }
 7908: 
 7909: # called in portfolio select mode, to show files selected NOT in current directory
 7910: sub files_not_in_path {
 7911:     my ($user, $path) = @_;
 7912:     my $filename = $user."savedfiles";
 7913:     my @return_files;
 7914:     my $path_part;
 7915:     open(IN, '<'.LONCAPA::.$filename);
 7916:     while (my $line = <IN>) {
 7917:         #ok, I know it's clunky, but I want it to work
 7918:         my @paths_and_file = split(m|/|, $line);
 7919:         my $file_part = pop(@paths_and_file);
 7920:         chomp($file_part);
 7921:         my $path_part = join('/', @paths_and_file);
 7922:         $path_part .= '/';
 7923:         my $path_and_file = $path_part.$file_part;
 7924:         if ($path_part ne $path) {
 7925:             push(@return_files, ($path_and_file));
 7926:         }
 7927:     }
 7928:     close(OUT);
 7929:     return (@return_files);
 7930: }
 7931: 
 7932: #----------------------------------------------Get portfolio file permissions
 7933: 
 7934: sub get_portfile_permissions {
 7935:     my ($domain,$user) = @_;
 7936:     my %current_permissions = &dump('file_permissions',$domain,$user);
 7937:     my ($tmp)=keys(%current_permissions);
 7938:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 7939:     return \%current_permissions;
 7940: }
 7941: 
 7942: #---------------------------------------------Get portfolio file access controls
 7943: 
 7944: sub get_access_controls {
 7945:     my ($current_permissions,$group,$file) = @_;
 7946:     my %access;
 7947:     my $real_file = $file;
 7948:     $file =~ s/\.meta$//;
 7949:     if (defined($file)) {
 7950:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 7951:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 7952:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 7953:             }
 7954:         }
 7955:     } else {
 7956:         foreach my $key (keys(%{$current_permissions})) {
 7957:             if ($key =~ /\0accesscontrol$/) {
 7958:                 if (defined($group)) {
 7959:                     if ($key !~ m-^\Q$group\E/-) {
 7960:                         next;
 7961:                     }
 7962:                 }
 7963:                 my ($fullpath) = split(/\0/,$key);
 7964:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 7965:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 7966:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 7967:                     }
 7968:                 }
 7969:             }
 7970:         }
 7971:     }
 7972:     return %access;
 7973: }
 7974: 
 7975: sub modify_access_controls {
 7976:     my ($file_name,$changes,$domain,$user)=@_;
 7977:     my ($outcome,$deloutcome);
 7978:     my %store_permissions;
 7979:     my %new_values;
 7980:     my %new_control;
 7981:     my %translation;
 7982:     my @deletions = ();
 7983:     my $now = time;
 7984:     if (exists($$changes{'activate'})) {
 7985:         if (ref($$changes{'activate'}) eq 'HASH') {
 7986:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 7987:             my $numnew = scalar(@newitems);
 7988:             for (my $i=0; $i<$numnew; $i++) {
 7989:                 my $newkey = $newitems[$i];
 7990:                 my $newid = &Apache::loncommon::get_cgi_id();
 7991:                 if ($newkey =~ /^\d+:/) { 
 7992:                     $newkey =~ s/^(\d+)/$newid/;
 7993:                     $translation{$1} = $newid;
 7994:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 7995:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 7996:                     $translation{$1} = $newid;
 7997:                 }
 7998:                 $new_values{$file_name."\0".$newkey} = 
 7999:                                           $$changes{'activate'}{$newitems[$i]};
 8000:                 $new_control{$newkey} = $now;
 8001:             }
 8002:         }
 8003:     }
 8004:     my %todelete;
 8005:     my %changed_items;
 8006:     foreach my $action ('delete','update') {
 8007:         if (exists($$changes{$action})) {
 8008:             if (ref($$changes{$action}) eq 'HASH') {
 8009:                 foreach my $key (keys(%{$$changes{$action}})) {
 8010:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 8011:                     if ($action eq 'delete') { 
 8012:                         $todelete{$itemnum} = 1;
 8013:                     } else {
 8014:                         $changed_items{$itemnum} = $key;
 8015:                     }
 8016:                 }
 8017:             }
 8018:         }
 8019:     }
 8020:     # get lock on access controls for file.
 8021:     my $lockhash = {
 8022:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 8023:                                                        ':'.$env{'user.domain'},
 8024:                    }; 
 8025:     my $tries = 0;
 8026:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 8027:    
 8028:     while (($gotlock ne 'ok') && $tries <3) {
 8029:         $tries ++;
 8030:         sleep 1;
 8031:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 8032:     }
 8033:     if ($gotlock eq 'ok') {
 8034:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 8035:         my ($tmp)=keys(%curr_permissions);
 8036:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 8037:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 8038:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 8039:             if (ref($curr_controls) eq 'HASH') {
 8040:                 foreach my $control_item (keys(%{$curr_controls})) {
 8041:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 8042:                     if (defined($todelete{$itemnum})) {
 8043:                         push(@deletions,$file_name."\0".$control_item);
 8044:                     } else {
 8045:                         if (defined($changed_items{$itemnum})) {
 8046:                             $new_control{$changed_items{$itemnum}} = $now;
 8047:                             push(@deletions,$file_name."\0".$control_item);
 8048:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 8049:                         } else {
 8050:                             $new_control{$control_item} = $$curr_controls{$control_item};
 8051:                         }
 8052:                     }
 8053:                 }
 8054:             }
 8055:         }
 8056:         my ($group);
 8057:         if (&is_course($domain,$user)) {
 8058:             ($group,my $file) = split(/\//,$file_name,2);
 8059:         }
 8060:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 8061:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 8062:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 8063:         #  remove lock
 8064:         my @del_lock = ($file_name."\0".'locked_access_records');
 8065:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 8066:         my $sqlresult =
 8067:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
 8068:                                     $group);
 8069:     } else {
 8070:         $outcome = "error: could not obtain lockfile\n";  
 8071:     }
 8072:     return ($outcome,$deloutcome,\%new_values,\%translation);
 8073: }
 8074: 
 8075: sub make_public_indefinitely {
 8076:     my ($requrl) = @_;
 8077:     my $now = time;
 8078:     my $action = 'activate';
 8079:     my $aclnum = 0;
 8080:     if (&is_portfolio_url($requrl)) {
 8081:         my (undef,$udom,$unum,$file_name,$group) =
 8082:             &parse_portfolio_url($requrl);
 8083:         my $current_perms = &get_portfile_permissions($udom,$unum);
 8084:         my %access_controls = &get_access_controls($current_perms,
 8085:                                                    $group,$file_name);
 8086:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 8087:             my ($num,$scope,$end,$start) = 
 8088:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 8089:             if ($scope eq 'public') {
 8090:                 if ($start <= $now && $end == 0) {
 8091:                     $action = 'none';
 8092:                 } else {
 8093:                     $action = 'update';
 8094:                     $aclnum = $num;
 8095:                 }
 8096:                 last;
 8097:             }
 8098:         }
 8099:         if ($action eq 'none') {
 8100:              return 'ok';
 8101:         } else {
 8102:             my %changes;
 8103:             my $newend = 0;
 8104:             my $newstart = $now;
 8105:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 8106:             $changes{$action}{$newkey} = {
 8107:                 type => 'public',
 8108:                 time => {
 8109:                     start => $newstart,
 8110:                     end   => $newend,
 8111:                 },
 8112:             };
 8113:             my ($outcome,$deloutcome,$new_values,$translation) =
 8114:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 8115:             return $outcome;
 8116:         }
 8117:     } else {
 8118:         return 'invalid';
 8119:     }
 8120: }
 8121: 
 8122: #------------------------------------------------------Get Marked as Read Only
 8123: 
 8124: sub get_marked_as_readonly {
 8125:     my ($domain,$user,$what,$group) = @_;
 8126:     my $current_permissions = &get_portfile_permissions($domain,$user);
 8127:     my @readonly_files;
 8128:     my $cmp1=$what;
 8129:     if (ref($what)) { $cmp1=join('',@{$what}) };
 8130:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 8131:         if (defined($group)) {
 8132:             if ($file_name !~ m-^\Q$group\E/-) {
 8133:                 next;
 8134:             }
 8135:         }
 8136:         if (ref($value) eq "ARRAY"){
 8137:             foreach my $stored_what (@{$value}) {
 8138:                 my $cmp2=$stored_what;
 8139:                 if (ref($stored_what) eq 'ARRAY') {
 8140:                     $cmp2=join('',@{$stored_what});
 8141:                 }
 8142:                 if ($cmp1 eq $cmp2) {
 8143:                     push(@readonly_files, $file_name);
 8144:                     last;
 8145:                 } elsif (!defined($what)) {
 8146:                     push(@readonly_files, $file_name);
 8147:                     last;
 8148:                 }
 8149:             }
 8150:         }
 8151:     }
 8152:     return @readonly_files;
 8153: }
 8154: #-----------------------------------------------------------Get Marked as Read Only Hash
 8155: 
 8156: sub get_marked_as_readonly_hash {
 8157:     my ($current_permissions,$group,$what) = @_;
 8158:     my %readonly_files;
 8159:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 8160:         if (defined($group)) {
 8161:             if ($file_name !~ m-^\Q$group\E/-) {
 8162:                 next;
 8163:             }
 8164:         }
 8165:         if (ref($value) eq "ARRAY"){
 8166:             foreach my $stored_what (@{$value}) {
 8167:                 if (ref($stored_what) eq 'ARRAY') {
 8168:                     foreach my $lock_descriptor(@{$stored_what}) {
 8169:                         if ($lock_descriptor eq 'graded') {
 8170:                             $readonly_files{$file_name} = 'graded';
 8171:                         } elsif ($lock_descriptor eq 'handback') {
 8172:                             $readonly_files{$file_name} = 'handback';
 8173:                         } else {
 8174:                             if (!exists($readonly_files{$file_name})) {
 8175:                                 $readonly_files{$file_name} = 'locked';
 8176:                             }
 8177:                         }
 8178:                     }
 8179:                 } 
 8180:             }
 8181:         } 
 8182:     }
 8183:     return %readonly_files;
 8184: }
 8185: # ------------------------------------------------------------ Unmark as Read Only
 8186: 
 8187: sub unmark_as_readonly {
 8188:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 8189:     # for portfolio submissions, $what contains [$symb,$crsid] 
 8190:     my ($domain,$user,$what,$file_name,$group) = @_;
 8191:     $file_name = &declutter_portfile($file_name);
 8192:     my $symb_crs = $what;
 8193:     if (ref($what)) { $symb_crs=join('',@$what); }
 8194:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 8195:     my ($tmp)=keys(%current_permissions);
 8196:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 8197:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 8198:     foreach my $file (@readonly_files) {
 8199: 	my $clean_file = &declutter_portfile($file);
 8200: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 8201: 	my $current_locks = $current_permissions{$file};
 8202:         my @new_locks;
 8203:         my @del_keys;
 8204:         if (ref($current_locks) eq "ARRAY"){
 8205:             foreach my $locker (@{$current_locks}) {
 8206:                 my $compare=$locker;
 8207:                 if (ref($locker) eq 'ARRAY') {
 8208:                     $compare=join('',@{$locker});
 8209:                     if ($compare ne $symb_crs) {
 8210:                         push(@new_locks, $locker);
 8211:                     }
 8212:                 }
 8213:             }
 8214:             if (scalar(@new_locks) > 0) {
 8215:                 $current_permissions{$file} = \@new_locks;
 8216:             } else {
 8217:                 push(@del_keys, $file);
 8218:                 &del('file_permissions',\@del_keys, $domain, $user);
 8219:                 delete($current_permissions{$file});
 8220:             }
 8221:         }
 8222:     }
 8223:     &put('file_permissions',\%current_permissions,$domain,$user);
 8224:     return;
 8225: }
 8226: 
 8227: # ------------------------------------------------------------ Directory lister
 8228: 
 8229: sub dirlist {
 8230:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
 8231:     $uri=~s/^\///;
 8232:     $uri=~s/\/$//;
 8233:     my ($udom, $uname);
 8234:     if ($getuserdir) {
 8235:         $udom = $userdomain;
 8236:         $uname = $username;
 8237:     } else {
 8238:         (undef,$udom,$uname)=split(/\//,$uri);
 8239:         if(defined($userdomain)) {
 8240:             $udom = $userdomain;
 8241:         }
 8242:         if(defined($username)) {
 8243:             $uname = $username;
 8244:         }
 8245:     }
 8246:     my ($dirRoot,$listing,@listing_results);
 8247: 
 8248:     $dirRoot = $perlvar{'lonDocRoot'};
 8249:     if (defined($getpropath)) {
 8250:         $dirRoot = &propath($udom,$uname);
 8251:         $dirRoot =~ s/\/$//;
 8252:     } elsif (defined($getuserdir)) {
 8253:         my $subdir=$uname.'__';
 8254:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 8255:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
 8256:                    ."/$udom/$subdir/$uname";
 8257:     } elsif (defined($alternateRoot)) {
 8258:         $dirRoot = $alternateRoot;
 8259:     }
 8260: 
 8261:     if($udom) {
 8262:         if($uname) {
 8263:             my $uhome = &homeserver($uname,$udom);
 8264:             if ($uhome eq 'no_host') {
 8265:                 return ([],'no_host');
 8266:             }
 8267:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
 8268:                               .$getuserdir.':'.&escape($dirRoot)
 8269:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
 8270:             if ($listing eq 'unknown_cmd') {
 8271:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
 8272:             } else {
 8273:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 8274:             }
 8275:             if ($listing eq 'unknown_cmd') {
 8276:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
 8277:                 @listing_results = split(/:/,$listing);
 8278:             } else {
 8279:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 8280:             }
 8281:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
 8282:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
 8283:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 8284:                 return ([],$listing);
 8285:             } else {
 8286:                 return (\@listing_results);
 8287:             }
 8288:         } elsif(!$alternateRoot) {
 8289:             my (%allusers,%listerror);
 8290: 	    my %servers = &get_servers($udom,'library');
 8291:  	    foreach my $tryserver (keys(%servers)) {
 8292:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
 8293:                                   &escape($udom),$tryserver);
 8294:                 if ($listing eq 'unknown_cmd') {
 8295: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 8296: 				      $udom, $tryserver);
 8297:                 } else {
 8298:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
 8299:                 }
 8300: 		if ($listing eq 'unknown_cmd') {
 8301: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 8302: 				      $udom, $tryserver);
 8303: 		    @listing_results = split(/:/,$listing);
 8304: 		} else {
 8305: 		    @listing_results =
 8306: 			map { &unescape($_); } split(/:/,$listing);
 8307: 		}
 8308:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
 8309:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
 8310:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 8311:                     $listerror{$tryserver} = $listing;
 8312:                 } else {
 8313: 		    foreach my $line (@listing_results) {
 8314: 			my ($entry) = split(/&/,$line,2);
 8315: 			$allusers{$entry} = 1;
 8316: 		    }
 8317: 		}
 8318:             }
 8319:             my @alluserslist=();
 8320:             foreach my $user (sort(keys(%allusers))) {
 8321:                 push(@alluserslist,$user.'&user');
 8322:             }
 8323:             return (\@alluserslist);
 8324:         } else {
 8325:             return ([],'missing username');
 8326:         }
 8327:     } elsif(!defined($getpropath)) {
 8328:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
 8329:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
 8330:         return (\@all_domains);
 8331:     } else {
 8332:         return ([],'missing domain');
 8333:     }
 8334: }
 8335: 
 8336: # --------------------------------------------- GetFileTimestamp
 8337: # This function utilizes dirlist and returns the date stamp for
 8338: # when it was last modified.  It will also return an error of -1
 8339: # if an error occurs
 8340: 
 8341: sub GetFileTimestamp {
 8342:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
 8343:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 8344:     $studentName   = &LONCAPA::clean_username($studentName);
 8345:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
 8346:                                     undef,$getuserdir);
 8347:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 8348:         return -1;
 8349:     }
 8350:     if (ref($fileref) eq 'ARRAY') {
 8351:         my @stats = split('&',$fileref->[0]);
 8352:         # @stats contains first the filename, then the stat output
 8353:         return $stats[10]; # so this is 10 instead of 9.
 8354:     } else {
 8355:         return -1;
 8356:     }
 8357: }
 8358: 
 8359: sub stat_file {
 8360:     my ($uri) = @_;
 8361:     $uri = &clutter_with_no_wrapper($uri);
 8362: 
 8363:     my ($udom,$uname,$file);
 8364:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 8365: 	($udom,$uname,$file) =
 8366: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 8367: 	$file = 'userfiles/'.$file;
 8368:     }
 8369:     if ($uri =~ m-^/res/-) {
 8370: 	($udom,$uname) = 
 8371: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 8372: 	$file = $uri;
 8373:     }
 8374: 
 8375:     if (!$udom || !$uname || !$file) {
 8376: 	# unable to handle the uri
 8377: 	return ();
 8378:     }
 8379:     my $getpropath;
 8380:     if ($file =~ /^userfiles\//) {
 8381:         $getpropath = 1;
 8382:     }
 8383:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
 8384:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 8385:         return ();
 8386:     } else {
 8387:         if (ref($listref) eq 'ARRAY') {
 8388:             my @stats = split('&',$listref->[0]);
 8389: 	    shift(@stats); #filename is first
 8390: 	    return @stats;
 8391:         }
 8392:     }
 8393:     return ();
 8394: }
 8395: 
 8396: # -------------------------------------------------------- Value of a Condition
 8397: 
 8398: # gets the value of a specific preevaluated condition
 8399: #    stored in the string  $env{user.state.<cid>}
 8400: # or looks up a condition reference in the bighash and if if hasn't
 8401: # already been evaluated recurses into docondval to get the value of
 8402: # the condition, then memoizing it to 
 8403: #   $env{user.state.<cid>.<condition>}
 8404: sub directcondval {
 8405:     my $number=shift;
 8406:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 8407: 	&Apache::lonuserstate::evalstate();
 8408:     }
 8409:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 8410: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 8411:     } elsif ($number =~ /^_/) {
 8412: 	my $sub_condition;
 8413: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8414: 		&GDBM_READER(),0640)) {
 8415: 	    $sub_condition=$bighash{'conditions'.$number};
 8416: 	    untie(%bighash);
 8417: 	}
 8418: 	my $value = &docondval($sub_condition);
 8419: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
 8420: 	return $value;
 8421:     }
 8422:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 8423:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 8424:     } else {
 8425:        return 2;
 8426:     }
 8427: }
 8428: 
 8429: # get the collection of conditions for this resource
 8430: sub condval {
 8431:     my $condidx=shift;
 8432:     my $allpathcond='';
 8433:     foreach my $cond (split(/\|/,$condidx)) {
 8434: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 8435: 	    $allpathcond.=
 8436: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 8437: 	}
 8438:     }
 8439:     $allpathcond=~s/\|$//;
 8440:     return &docondval($allpathcond);
 8441: }
 8442: 
 8443: #evaluates an expression of conditions
 8444: sub docondval {
 8445:     my ($allpathcond) = @_;
 8446:     my $result=0;
 8447:     if ($env{'request.course.id'}
 8448: 	&& defined($allpathcond)) {
 8449: 	my $operand='|';
 8450: 	my @stack;
 8451: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 8452: 	    if ($chunk eq '(') {
 8453: 		push @stack,($operand,$result);
 8454: 	    } elsif ($chunk eq ')') {
 8455: 		my $before=pop @stack;
 8456: 		if (pop @stack eq '&') {
 8457: 		    $result=$result>$before?$before:$result;
 8458: 		} else {
 8459: 		    $result=$result>$before?$result:$before;
 8460: 		}
 8461: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 8462: 		$operand=$chunk;
 8463: 	    } else {
 8464: 		my $new=directcondval($chunk);
 8465: 		if ($operand eq '&') {
 8466: 		    $result=$result>$new?$new:$result;
 8467: 		} else {
 8468: 		    $result=$result>$new?$result:$new;
 8469: 		}
 8470: 	    }
 8471: 	}
 8472:     }
 8473:     return $result;
 8474: }
 8475: 
 8476: # ---------------------------------------------------- Devalidate courseresdata
 8477: 
 8478: sub devalidatecourseresdata {
 8479:     my ($coursenum,$coursedomain)=@_;
 8480:     my $hashid=$coursenum.':'.$coursedomain;
 8481:     &devalidate_cache_new('courseres',$hashid);
 8482: }
 8483: 
 8484: 
 8485: # --------------------------------------------------- Course Resourcedata Query
 8486: #
 8487: #  Parameters:
 8488: #      $coursenum    - Number of the course.
 8489: #      $coursedomain - Domain at which the course was created.
 8490: #  Returns:
 8491: #     A hash of the course parameters along (I think) with timestamps
 8492: #     and version info.
 8493: 
 8494: sub get_courseresdata {
 8495:     my ($coursenum,$coursedomain)=@_;
 8496:     my $coursehom=&homeserver($coursenum,$coursedomain);
 8497:     my $hashid=$coursenum.':'.$coursedomain;
 8498:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 8499:     my %dumpreply;
 8500:     unless (defined($cached)) {
 8501: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 8502: 	$result=\%dumpreply;
 8503: 	my ($tmp) = keys(%dumpreply);
 8504: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 8505: 	    &do_cache_new('courseres',$hashid,$result,600);
 8506: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 8507: 	    return $tmp;
 8508: 	} elsif ($tmp =~ /^(error)/) {
 8509: 	    $result=undef;
 8510: 	    &do_cache_new('courseres',$hashid,$result,600);
 8511: 	}
 8512:     }
 8513:     return $result;
 8514: }
 8515: 
 8516: sub devalidateuserresdata {
 8517:     my ($uname,$udom)=@_;
 8518:     my $hashid="$udom:$uname";
 8519:     &devalidate_cache_new('userres',$hashid);
 8520: }
 8521: 
 8522: sub get_userresdata {
 8523:     my ($uname,$udom)=@_;
 8524:     #most student don\'t have any data set, check if there is some data
 8525:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 8526: 
 8527:     my $hashid="$udom:$uname";
 8528:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 8529:     if (!defined($cached)) {
 8530: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 8531: 	$result=\%resourcedata;
 8532: 	&do_cache_new('userres',$hashid,$result,600);
 8533:     }
 8534:     my ($tmp)=keys(%$result);
 8535:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 8536: 	return $result;
 8537:     }
 8538:     #error 2 occurs when the .db doesn't exist
 8539:     if ($tmp!~/error: 2 /) {
 8540: 	&logthis("<font color=\"blue\">WARNING:".
 8541: 		 " Trying to get resource data for ".
 8542: 		 $uname." at ".$udom.": ".
 8543: 		 $tmp."</font>");
 8544:     } elsif ($tmp=~/error: 2 /) {
 8545: 	#&EXT_cache_set($udom,$uname);
 8546: 	&do_cache_new('userres',$hashid,undef,600);
 8547: 	undef($tmp); # not really an error so don't send it back
 8548:     }
 8549:     return $tmp;
 8550: }
 8551: #----------------------------------------------- resdata - return resource data
 8552: #  Purpose:
 8553: #    Return resource data for either users or for a course.
 8554: #  Parameters:
 8555: #     $name      - Course/user name.
 8556: #     $domain    - Name of the domain the user/course is registered on.
 8557: #     $type      - Type of thing $name is (must be 'course' or 'user'
 8558: #     @which     - Array of names of resources desired.
 8559: #  Returns:
 8560: #     The value of the first reasource in @which that is found in the
 8561: #     resource hash.
 8562: #  Exceptional Conditions:
 8563: #     If the $type passed in is not valid (not the string 'course' or 
 8564: #     'user', an undefined  reference is returned.
 8565: #     If none of the resources are found, an undef is returned
 8566: sub resdata {
 8567:     my ($name,$domain,$type,@which)=@_;
 8568:     my $result;
 8569:     if ($type eq 'course') {
 8570: 	$result=&get_courseresdata($name,$domain);
 8571:     } elsif ($type eq 'user') {
 8572: 	$result=&get_userresdata($name,$domain);
 8573:     }
 8574:     if (!ref($result)) { return $result; }    
 8575:     foreach my $item (@which) {
 8576: 	if (defined($result->{$item->[0]})) {
 8577: 	    return [$result->{$item->[0]},$item->[1]];
 8578: 	}
 8579:     }
 8580:     return undef;
 8581: }
 8582: 
 8583: #
 8584: # EXT resource caching routines
 8585: #
 8586: 
 8587: sub clear_EXT_cache_status {
 8588:     &delenv('cache.EXT.');
 8589: }
 8590: 
 8591: sub EXT_cache_status {
 8592:     my ($target_domain,$target_user) = @_;
 8593:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 8594:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 8595:         # We know already the user has no data
 8596:         return 1;
 8597:     } else {
 8598:         return 0;
 8599:     }
 8600: }
 8601: 
 8602: sub EXT_cache_set {
 8603:     my ($target_domain,$target_user) = @_;
 8604:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 8605:     #&appenv({$cachename => time});
 8606: }
 8607: 
 8608: # --------------------------------------------------------- Value of a Variable
 8609: sub EXT {
 8610: 
 8611:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
 8612:     unless ($varname) { return ''; }
 8613:     #get real user name/domain, courseid and symb
 8614:     my $courseid;
 8615:     my $publicuser;
 8616:     if ($symbparm) {
 8617: 	$symbparm=&get_symb_from_alias($symbparm);
 8618:     }
 8619:     if (!($uname && $udom)) {
 8620:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 8621:       if (!$symbparm) {	$symbparm=$cursymb; }
 8622:     } else {
 8623: 	$courseid=$env{'request.course.id'};
 8624:     }
 8625:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 8626:     my $rest;
 8627:     if (defined($therest[0])) {
 8628:        $rest=join('.',@therest);
 8629:     } else {
 8630:        $rest='';
 8631:     }
 8632: 
 8633:     my $qualifierrest=$qualifier;
 8634:     if ($rest) { $qualifierrest.='.'.$rest; }
 8635:     my $spacequalifierrest=$space;
 8636:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 8637:     if ($realm eq 'user') {
 8638: # --------------------------------------------------------------- user.resource
 8639: 	if ($space eq 'resource') {
 8640: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 8641: 		  || defined($Apache::lonhomework::parsing_a_task))
 8642: 		 &&
 8643: 		 ($symbparm eq &symbread()) ) {	
 8644: 		# if we are in the middle of processing the resource the
 8645: 		# get the value we are planning on committing
 8646:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 8647:                     return $Apache::lonhomework::results{$qualifierrest};
 8648:                 } else {
 8649:                     return $Apache::lonhomework::history{$qualifierrest};
 8650:                 }
 8651: 	    } else {
 8652: 		my %restored;
 8653: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 8654: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 8655: 		} else {
 8656: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 8657: 		}
 8658: 		return $restored{$qualifierrest};
 8659: 	    }
 8660: # ----------------------------------------------------------------- user.access
 8661:         } elsif ($space eq 'access') {
 8662: 	    # FIXME - not supporting calls for a specific user
 8663:             return &allowed($qualifier,$rest);
 8664: # ------------------------------------------ user.preferences, user.environment
 8665:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 8666: 	    if (($uname eq $env{'user.name'}) &&
 8667: 		($udom eq $env{'user.domain'})) {
 8668: 		return $env{join('.',('environment',$qualifierrest))};
 8669: 	    } else {
 8670: 		my %returnhash;
 8671: 		if (!$publicuser) {
 8672: 		    %returnhash=&userenvironment($udom,$uname,
 8673: 						 $qualifierrest);
 8674: 		}
 8675: 		return $returnhash{$qualifierrest};
 8676: 	    }
 8677: # ----------------------------------------------------------------- user.course
 8678:         } elsif ($space eq 'course') {
 8679: 	    # FIXME - not supporting calls for a specific user
 8680:             return $env{join('.',('request.course',$qualifier))};
 8681: # ------------------------------------------------------------------- user.role
 8682:         } elsif ($space eq 'role') {
 8683: 	    # FIXME - not supporting calls for a specific user
 8684:             my ($role,$where)=split(/\./,$env{'request.role'});
 8685:             if ($qualifier eq 'value') {
 8686: 		return $role;
 8687:             } elsif ($qualifier eq 'extent') {
 8688:                 return $where;
 8689:             }
 8690: # ----------------------------------------------------------------- user.domain
 8691:         } elsif ($space eq 'domain') {
 8692:             return $udom;
 8693: # ------------------------------------------------------------------- user.name
 8694:         } elsif ($space eq 'name') {
 8695:             return $uname;
 8696: # ---------------------------------------------------- Any other user namespace
 8697:         } else {
 8698: 	    my %reply;
 8699: 	    if (!$publicuser) {
 8700: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 8701: 	    }
 8702: 	    return $reply{$qualifierrest};
 8703:         }
 8704:     } elsif ($realm eq 'query') {
 8705: # ---------------------------------------------- pull stuff out of query string
 8706:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 8707: 						[$spacequalifierrest]);
 8708: 	return $env{'form.'.$spacequalifierrest}; 
 8709:    } elsif ($realm eq 'request') {
 8710: # ------------------------------------------------------------- request.browser
 8711:         if ($space eq 'browser') {
 8712:             return $env{'browser.'.$qualifier};
 8713: # ------------------------------------------------------------ request.filename
 8714:         } else {
 8715:             return $env{'request.'.$spacequalifierrest};
 8716:         }
 8717:     } elsif ($realm eq 'course') {
 8718: # ---------------------------------------------------------- course.description
 8719:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 8720:     } elsif ($realm eq 'resource') {
 8721: 
 8722: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 8723: 	    if (!$symbparm) { $symbparm=&symbread(); }
 8724: 	}
 8725: 
 8726: 	if ($space eq 'title') {
 8727: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 8728: 	    return &gettitle($symbparm);
 8729: 	}
 8730: 	
 8731: 	if ($space eq 'map') {
 8732: 	    my ($map) = &decode_symb($symbparm);
 8733: 	    return &symbread($map);
 8734: 	}
 8735: 	if ($space eq 'filename') {
 8736: 	    if ($symbparm) {
 8737: 		return &clutter((&decode_symb($symbparm))[2]);
 8738: 	    }
 8739: 	    return &hreflocation('',$env{'request.filename'});
 8740: 	}
 8741: 
 8742: 	my ($section, $group, @groups);
 8743: 	my ($courselevelm,$courselevel);
 8744: 	if ($symbparm && defined($courseid) && 
 8745: 	    $courseid eq $env{'request.course.id'}) {
 8746: 
 8747: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 8748: 
 8749: # ----------------------------------------------------- Cascading lookup scheme
 8750: 	    my $symbp=$symbparm;
 8751: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 8752: 
 8753: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 8754: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 8755: 
 8756: 	    if (($env{'user.name'} eq $uname) &&
 8757: 		($env{'user.domain'} eq $udom)) {
 8758: 		$section=$env{'request.course.sec'};
 8759:                 @groups = split(/:/,$env{'request.course.groups'});  
 8760:                 @groups=&sort_course_groups($courseid,@groups); 
 8761: 	    } else {
 8762: 		if (! defined($usection)) {
 8763: 		    $section=&getsection($udom,$uname,$courseid);
 8764: 		} else {
 8765: 		    $section = $usection;
 8766: 		}
 8767:                 @groups = &get_users_groups($udom,$uname,$courseid);
 8768: 	    }
 8769: 
 8770: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 8771: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 8772: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 8773: 
 8774: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 8775: 	    my $courselevelr=$courseid.'.'.$symbparm;
 8776: 	    $courselevelm=$courseid.'.'.$mapparm;
 8777: 
 8778: # ----------------------------------------------------------- first, check user
 8779: 
 8780: 	    my $userreply=&resdata($uname,$udom,'user',
 8781: 				       ([$courselevelr,'resource'],
 8782: 					[$courselevelm,'map'     ],
 8783: 					[$courselevel, 'course'  ]));
 8784: 	    if (defined($userreply)) { return &get_reply($userreply); }
 8785: 
 8786: # ------------------------------------------------ second, check some of course
 8787:             my $coursereply;
 8788:             if (@groups > 0) {
 8789:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 8790:                                        $mapparm,$spacequalifierrest);
 8791:                 if (defined($coursereply)) { return &get_reply($coursereply); }
 8792:             }
 8793: 
 8794: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 8795: 				  $env{'course.'.$courseid.'.domain'},
 8796: 				  'course',
 8797: 				  ([$seclevelr,   'resource'],
 8798: 				   [$seclevelm,   'map'     ],
 8799: 				   [$seclevel,    'course'  ],
 8800: 				   [$courselevelr,'resource']));
 8801: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 8802: 
 8803: # ------------------------------------------------------ third, check map parms
 8804: 	    my %parmhash=();
 8805: 	    my $thisparm='';
 8806: 	    if (tie(%parmhash,'GDBM_File',
 8807: 		    $env{'request.course.fn'}.'_parms.db',
 8808: 		    &GDBM_READER(),0640)) {
 8809: 		$thisparm=$parmhash{$symbparm};
 8810: 		untie(%parmhash);
 8811: 	    }
 8812: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
 8813: 	}
 8814: # ------------------------------------------ fourth, look in resource metadata
 8815: 
 8816: 	$spacequalifierrest=~s/\./\_/;
 8817: 	my $filename;
 8818: 	if (!$symbparm) { $symbparm=&symbread(); }
 8819: 	if ($symbparm) {
 8820: 	    $filename=(&decode_symb($symbparm))[2];
 8821: 	} else {
 8822: 	    $filename=$env{'request.filename'};
 8823: 	}
 8824: 	my $metadata=&metadata($filename,$spacequalifierrest);
 8825: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 8826: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 8827: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 8828: 
 8829: # ---------------------------------------------- fourth, look in rest of course
 8830: 	if ($symbparm && defined($courseid) && 
 8831: 	    $courseid eq $env{'request.course.id'}) {
 8832: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 8833: 				     $env{'course.'.$courseid.'.domain'},
 8834: 				     'course',
 8835: 				     ([$courselevelm,'map'   ],
 8836: 				      [$courselevel, 'course']));
 8837: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 8838: 	}
 8839: # ------------------------------------------------------------------ Cascade up
 8840: 	unless ($space eq '0') {
 8841: 	    my @parts=split(/_/,$space);
 8842: 	    my $id=pop(@parts);
 8843: 	    my $part=join('_',@parts);
 8844: 	    if ($part eq '') { $part='0'; }
 8845: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 8846: 				 $symbparm,$udom,$uname,$section,1);
 8847: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
 8848: 	}
 8849: 	if ($recurse) { return undef; }
 8850: 	my $pack_def=&packages_tab_default($filename,$varname);
 8851: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
 8852: # ---------------------------------------------------- Any other user namespace
 8853:     } elsif ($realm eq 'environment') {
 8854: # ----------------------------------------------------------------- environment
 8855: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 8856: 	    return $env{'environment.'.$spacequalifierrest};
 8857: 	} else {
 8858: 	    if ($uname eq 'anonymous' && $udom eq '') {
 8859: 		return '';
 8860: 	    }
 8861: 	    my %returnhash=&userenvironment($udom,$uname,
 8862: 					    $spacequalifierrest);
 8863: 	    return $returnhash{$spacequalifierrest};
 8864: 	}
 8865:     } elsif ($realm eq 'system') {
 8866: # ----------------------------------------------------------------- system.time
 8867: 	if ($space eq 'time') {
 8868: 	    return time;
 8869:         }
 8870:     } elsif ($realm eq 'server') {
 8871: # ----------------------------------------------------------------- system.time
 8872: 	if ($space eq 'name') {
 8873: 	    return $ENV{'SERVER_NAME'};
 8874:         }
 8875:     }
 8876:     return '';
 8877: }
 8878: 
 8879: sub get_reply {
 8880:     my ($reply_value) = @_;
 8881:     if (ref($reply_value) eq 'ARRAY') {
 8882:         if (wantarray) {
 8883: 	    return @$reply_value;
 8884:         }
 8885:         return $reply_value->[0];
 8886:     } else {
 8887:         return $reply_value;
 8888:     }
 8889: }
 8890: 
 8891: sub check_group_parms {
 8892:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
 8893:     my @groupitems = ();
 8894:     my $resultitem;
 8895:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
 8896:     foreach my $group (@{$groups}) {
 8897:         foreach my $level (@levels) {
 8898:              my $item = $courseid.'.['.$group.'].'.$level->[0];
 8899:              push(@groupitems,[$item,$level->[1]]);
 8900:         }
 8901:     }
 8902:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
 8903:                             $env{'course.'.$courseid.'.domain'},
 8904:                                      'course',@groupitems);
 8905:     return $coursereply;
 8906: }
 8907: 
 8908: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
 8909:     my ($courseid,@groups) = @_;
 8910:     @groups = sort(@groups);
 8911:     return @groups;
 8912: }
 8913: 
 8914: sub packages_tab_default {
 8915:     my ($uri,$varname)=@_;
 8916:     my (undef,$part,$name)=split(/\./,$varname);
 8917: 
 8918:     my (@extension,@specifics,$do_default);
 8919:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
 8920: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 8921: 	if ($pack_type eq 'default') {
 8922: 	    $do_default=1;
 8923: 	} elsif ($pack_type eq 'extension') {
 8924: 	    push(@extension,[$package,$pack_type,$pack_part]);
 8925: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
 8926: 	    # only look at packages defaults for packages that this id is
 8927: 	    push(@specifics,[$package,$pack_type,$pack_part]);
 8928: 	}
 8929:     }
 8930:     # first look for a package that matches the requested part id
 8931:     foreach my $package (@specifics) {
 8932: 	my (undef,$pack_type,$pack_part)=@{$package};
 8933: 	next if ($pack_part ne $part);
 8934: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 8935: 	    return $packagetab{"$pack_type&$name&default"};
 8936: 	}
 8937:     }
 8938:     # look for any possible matching non extension_ package
 8939:     foreach my $package (@specifics) {
 8940: 	my (undef,$pack_type,$pack_part)=@{$package};
 8941: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 8942: 	    return $packagetab{"$pack_type&$name&default"};
 8943: 	}
 8944: 	if ($pack_type eq 'part') { $pack_part='0'; }
 8945: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
 8946: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
 8947: 	}
 8948:     }
 8949:     # look for any posible extension_ match
 8950:     foreach my $package (@extension) {
 8951: 	my ($package,$pack_type)=@{$package};
 8952: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 8953: 	    return $packagetab{"$pack_type&$name&default"};
 8954: 	}
 8955: 	if (defined($packagetab{$package."&$name&default"})) {
 8956: 	    return $packagetab{$package."&$name&default"};
 8957: 	}
 8958:     }
 8959:     # look for a global default setting
 8960:     if ($do_default && defined($packagetab{"default&$name&default"})) {
 8961: 	return $packagetab{"default&$name&default"};
 8962:     }
 8963:     return undef;
 8964: }
 8965: 
 8966: sub add_prefix_and_part {
 8967:     my ($prefix,$part)=@_;
 8968:     my $keyroot;
 8969:     if (defined($prefix) && $prefix !~ /^__/) {
 8970: 	# prefix that has a part already
 8971: 	$keyroot=$prefix;
 8972:     } elsif (defined($prefix)) {
 8973: 	# prefix that is missing a part
 8974: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 8975:     } else {
 8976: 	# no prefix at all
 8977: 	if (defined($part)) { $keyroot='_'.$part; }
 8978:     }
 8979:     return $keyroot;
 8980: }
 8981: 
 8982: # ---------------------------------------------------------------- Get metadata
 8983: 
 8984: my %metaentry;
 8985: my %importedpartids;
 8986: sub metadata {
 8987:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 8988:     $uri=&declutter($uri);
 8989:     # if it is a non metadata possible uri return quickly
 8990:     if (($uri eq '') || 
 8991: 	(($uri =~ m|^/*adm/|) && 
 8992: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
 8993:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
 8994: 	return undef;
 8995:     }
 8996:     if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) 
 8997: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
 8998: 	return undef;
 8999:     }
 9000:     my $filename=$uri;
 9001:     $uri=~s/\.meta$//;
 9002: #
 9003: # Is the metadata already cached?
 9004: # Look at timestamp of caching
 9005: # Everything is cached by the main uri, libraries are never directly cached
 9006: #
 9007:     if (!defined($liburi)) {
 9008: 	my ($result,$cached)=&is_cached_new('meta',$uri);
 9009: 	if (defined($cached)) { return $result->{':'.$what}; }
 9010:     }
 9011:     {
 9012: # Imported parts would go here
 9013:         my %importedids=();
 9014:         my @origfileimportpartids=();
 9015:         my $importedparts=0;
 9016: #
 9017: # Is this a recursive call for a library?
 9018: #
 9019: #	if (! exists($metacache{$uri})) {
 9020: #	    $metacache{$uri}={};
 9021: #	}
 9022: 	my $cachetime = 60*60;
 9023:         if ($liburi) {
 9024: 	    $liburi=&declutter($liburi);
 9025:             $filename=$liburi;
 9026:         } else {
 9027: 	    &devalidate_cache_new('meta',$uri);
 9028: 	    undef(%metaentry);
 9029: 	}
 9030:         my %metathesekeys=();
 9031:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 9032: 	my $metastring;
 9033: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
 9034: 	    my $which = &hreflocation('','/'.($liburi || $uri));
 9035: 	    $metastring = 
 9036: 		&Apache::lonnet::ssi_body($which,
 9037: 					  ('grade_target' => 'meta'));
 9038: 	    $cachetime = 1; # only want this cached in the child not long term
 9039: 	} elsif (($uri !~ m -^(editupload)/-) && 
 9040:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
 9041: 	    my $file=&filelocation('',&clutter($filename));
 9042: 	    #push(@{$metaentry{$uri.'.file'}},$file);
 9043: 	    $metastring=&getfile($file);
 9044: 	}
 9045:         my $parser=HTML::LCParser->new(\$metastring);
 9046:         my $token;
 9047:         undef %metathesekeys;
 9048:         while ($token=$parser->get_token) {
 9049: 	    if ($token->[0] eq 'S') {
 9050: 		if (defined($token->[2]->{'package'})) {
 9051: #
 9052: # This is a package - get package info
 9053: #
 9054: 		    my $package=$token->[2]->{'package'};
 9055: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 9056: 		    if (defined($token->[2]->{'id'})) { 
 9057: 			$keyroot.='_'.$token->[2]->{'id'}; 
 9058: 		    }
 9059: 		    if ($metaentry{':packages'}) {
 9060: 			$metaentry{':packages'}.=','.$package.$keyroot;
 9061: 		    } else {
 9062: 			$metaentry{':packages'}=$package.$keyroot;
 9063: 		    }
 9064: 		    foreach my $pack_entry (keys(%packagetab)) {
 9065: 			my $part=$keyroot;
 9066: 			$part=~s/^\_//;
 9067: 			if ($pack_entry=~/^\Q$package\E\&/ || 
 9068: 			    $pack_entry=~/^\Q$package\E_0\&/) {
 9069: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
 9070: 			    # ignore package.tab specified default values
 9071:                             # here &package_tab_default() will fetch those
 9072: 			    if ($subp eq 'default') { next; }
 9073: 			    my $value=$packagetab{$pack_entry};
 9074: 			    my $unikey;
 9075: 			    if ($pack =~ /_0$/) {
 9076: 				$unikey='parameter_0_'.$name;
 9077: 				$part=0;
 9078: 			    } else {
 9079: 				$unikey='parameter'.$keyroot.'_'.$name;
 9080: 			    }
 9081: 			    if ($subp eq 'display') {
 9082: 				$value.=' [Part: '.$part.']';
 9083: 			    }
 9084: 			    $metaentry{':'.$unikey.'.part'}=$part;
 9085: 			    $metathesekeys{$unikey}=1;
 9086: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 9087: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
 9088: 			    }
 9089: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
 9090: 				$metaentry{':'.$unikey}=
 9091: 				    $metaentry{':'.$unikey.'.default'};
 9092: 			    }
 9093: 			}
 9094: 		    }
 9095: 		} else {
 9096: #
 9097: # This is not a package - some other kind of start tag
 9098: #
 9099: 		    my $entry=$token->[1];
 9100: 		    my $unikey='';
 9101: 
 9102: 		    if ($entry eq 'import') {
 9103: #
 9104: # Importing a library here
 9105: #
 9106:                         my $location=$parser->get_text('/import');
 9107:                         my $dir=$filename;
 9108:                         $dir=~s|[^/]*$||;
 9109:                         $location=&filelocation($dir,$location);
 9110:                        
 9111:                         my $importmode=$token->[2]->{'importmode'};
 9112:                         if ($importmode eq 'problem') {
 9113: # Import as problem/response
 9114:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 9115:                         } elsif ($importmode eq 'part') {
 9116: # Import as part(s)
 9117:                            $importedparts=1;
 9118: # We need to get the original file and the imported file to get the part order correct
 9119: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
 9120: # Load and inspect original file
 9121:                            if ($#origfileimportpartids<0) {
 9122:                               undef(%importedpartids);
 9123:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
 9124:                               my $origfile=&getfile($origfilelocation);
 9125:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
 9126:                            }
 9127: 
 9128: # Load and inspect imported file
 9129:                            my $impfile=&getfile($location);
 9130:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
 9131:                            if ($#impfilepartids>=0) {
 9132: # This problem had parts
 9133:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
 9134:                            } else {
 9135: # Importing by turning a single problem into a problem part
 9136: # It gets the import-tags ID as part-ID
 9137:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
 9138:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
 9139:                            }
 9140:                         } else {
 9141: # Normal import
 9142:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 9143:                            if (defined($token->[2]->{'id'})) {
 9144:                               $unikey.='_'.$token->[2]->{'id'};
 9145:                            }
 9146:                         }
 9147: 
 9148: 			if ($depthcount<20) {
 9149: 			    my $metadata = 
 9150: 				&metadata($uri,'keys', $location,$unikey,
 9151: 					  $depthcount+1);
 9152: 			    foreach my $meta (split(',',$metadata)) {
 9153: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
 9154: 				$metathesekeys{$meta}=1;
 9155: 			    }
 9156: 			
 9157:                         }
 9158: 		    } else {
 9159: #
 9160: # Not importing, some other kind of non-package, non-library start tag
 9161: # 
 9162:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
 9163:                         if (defined($token->[2]->{'id'})) {
 9164:                             $unikey.='_'.$token->[2]->{'id'};
 9165:                         }
 9166: 			if (defined($token->[2]->{'name'})) { 
 9167: 			    $unikey.='_'.$token->[2]->{'name'}; 
 9168: 			}
 9169: 			$metathesekeys{$unikey}=1;
 9170: 			foreach my $param (@{$token->[3]}) {
 9171: 			    $metaentry{':'.$unikey.'.'.$param} =
 9172: 				$token->[2]->{$param};
 9173: 			}
 9174: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
 9175: 			my $default=$metaentry{':'.$unikey.'.default'};
 9176: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
 9177: 		 # only ws inside the tag, and not in default, so use default
 9178: 		 # as value
 9179: 			    $metaentry{':'.$unikey}=$default;
 9180: 			} elsif ( $internaltext =~ /\S/ ) {
 9181: 		  # something interesting inside the tag
 9182: 			    $metaentry{':'.$unikey}=$internaltext;
 9183: 			} else {
 9184: 		  # no interesting values, don't set a default
 9185: 			}
 9186: # end of not-a-package not-a-library import
 9187: 		    }
 9188: # end of not-a-package start tag
 9189: 		}
 9190: # the next is the end of "start tag"
 9191: 	    }
 9192: 	}
 9193: 	my ($extension) = ($uri =~ /\.(\w+)$/);
 9194: 	$extension = lc($extension);
 9195: 	if ($extension eq 'htm') { $extension='html'; }
 9196: 
 9197: 	foreach my $key (keys(%packagetab)) {
 9198: 	    #no specific packages #how's our extension
 9199: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
 9200: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
 9201: 					 \%metathesekeys);
 9202: 	}
 9203: 
 9204: 	if (!exists($metaentry{':packages'})
 9205: 	    || $packagetab{"import_defaults&extension_$extension"}) {
 9206: 	    foreach my $key (keys(%packagetab)) {
 9207: 		#no specific packages well let's get default then
 9208: 		if ($key!~/^default&/) { next; }
 9209: 		&metadata_create_package_def($uri,$key,'default',
 9210: 					     \%metathesekeys);
 9211: 	    }
 9212: 	}
 9213: # are there custom rights to evaluate
 9214: 	if ($metaentry{':copyright'} eq 'custom') {
 9215: 
 9216:     #
 9217:     # Importing a rights file here
 9218:     #
 9219: 	    unless ($depthcount) {
 9220: 		my $location=$metaentry{':customdistributionfile'};
 9221: 		my $dir=$filename;
 9222: 		$dir=~s|[^/]*$||;
 9223: 		$location=&filelocation($dir,$location);
 9224: 		my $rights_metadata =
 9225: 		    &metadata($uri,'keys',$location,'_rights',
 9226: 			      $depthcount+1);
 9227: 		foreach my $rights (split(',',$rights_metadata)) {
 9228: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
 9229: 		    $metathesekeys{$rights}=1;
 9230: 		}
 9231: 	    }
 9232: 	}
 9233: 	# uniqifiy package listing
 9234: 	my %seen;
 9235: 	my @uniq_packages =
 9236: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
 9237: 	$metaentry{':packages'} = join(',',@uniq_packages);
 9238: 
 9239:         if ($importedparts) {
 9240: # We had imported parts and need to rebuild partorder
 9241:            $metaentry{':partorder'}='';
 9242:            $metathesekeys{'partorder'}=1;
 9243:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
 9244:                if ($origfileimportpartids[$index] eq 'part') {
 9245: # original part, part of the problem
 9246:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
 9247:                } else {
 9248: # we have imported parts at this position
 9249:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
 9250:                }
 9251:            }
 9252:            $metaentry{':partorder'}=~s/^\,//;
 9253:         }
 9254: 
 9255: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
 9256: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
 9257: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
 9258: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
 9259: # this is the end of "was not already recently cached
 9260:     }
 9261:     return $metaentry{':'.$what};
 9262: }
 9263: 
 9264: sub metadata_create_package_def {
 9265:     my ($uri,$key,$package,$metathesekeys)=@_;
 9266:     my ($pack,$name,$subp)=split(/\&/,$key);
 9267:     if ($subp eq 'default') { next; }
 9268:     
 9269:     if (defined($metaentry{':packages'})) {
 9270: 	$metaentry{':packages'}.=','.$package;
 9271:     } else {
 9272: 	$metaentry{':packages'}=$package;
 9273:     }
 9274:     my $value=$packagetab{$key};
 9275:     my $unikey;
 9276:     $unikey='parameter_0_'.$name;
 9277:     $metaentry{':'.$unikey.'.part'}=0;
 9278:     $$metathesekeys{$unikey}=1;
 9279:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 9280: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
 9281:     }
 9282:     if (defined($metaentry{':'.$unikey.'.default'})) {
 9283: 	$metaentry{':'.$unikey}=
 9284: 	    $metaentry{':'.$unikey.'.default'};
 9285:     }
 9286: }
 9287: 
 9288: sub metadata_generate_part0 {
 9289:     my ($metadata,$metacache,$uri) = @_;
 9290:     my %allnames;
 9291:     foreach my $metakey (keys(%$metadata)) {
 9292: 	if ($metakey=~/^parameter\_(.*)/) {
 9293: 	  my $part=$$metacache{':'.$metakey.'.part'};
 9294: 	  my $name=$$metacache{':'.$metakey.'.name'};
 9295: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
 9296: 	    $allnames{$name}=$part;
 9297: 	  }
 9298: 	}
 9299:     }
 9300:     foreach my $name (keys(%allnames)) {
 9301:       $$metadata{"parameter_0_$name"}=1;
 9302:       my $key=":parameter_0_$name";
 9303:       $$metacache{"$key.part"}='0';
 9304:       $$metacache{"$key.name"}=$name;
 9305:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
 9306: 					   $allnames{$name}.'_'.$name.
 9307: 					   '.type'};
 9308:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
 9309: 			     '.display'};
 9310:       my $expr='[Part: '.$allnames{$name}.']';
 9311:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
 9312:       $$metacache{"$key.display"}=$olddis;
 9313:     }
 9314: }
 9315: 
 9316: # ------------------------------------------------------ Devalidate title cache
 9317: 
 9318: sub devalidate_title_cache {
 9319:     my ($url)=@_;
 9320:     if (!$env{'request.course.id'}) { return; }
 9321:     my $symb=&symbread($url);
 9322:     if (!$symb) { return; }
 9323:     my $key=$env{'request.course.id'}."\0".$symb;
 9324:     &devalidate_cache_new('title',$key);
 9325: }
 9326: 
 9327: # ------------------------------------------------- Get the title of a course
 9328: 
 9329: sub current_course_title {
 9330:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
 9331: }
 9332: # ------------------------------------------------- Get the title of a resource
 9333: 
 9334: sub gettitle {
 9335:     my $urlsymb=shift;
 9336:     my $symb=&symbread($urlsymb);
 9337:     if ($symb) {
 9338: 	my $key=$env{'request.course.id'}."\0".$symb;
 9339: 	my ($result,$cached)=&is_cached_new('title',$key);
 9340: 	if (defined($cached)) { 
 9341: 	    return $result;
 9342: 	}
 9343: 	my ($map,$resid,$url)=&decode_symb($symb);
 9344: 	my $title='';
 9345: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
 9346: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
 9347: 	} else {
 9348: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9349: 		    &GDBM_READER(),0640)) {
 9350: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
 9351: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
 9352: 		untie(%bighash);
 9353: 	    }
 9354: 	}
 9355: 	$title=~s/\&colon\;/\:/gs;
 9356: 	if ($title) {
 9357: 	    return &do_cache_new('title',$key,$title,600);
 9358: 	}
 9359: 	$urlsymb=$url;
 9360:     }
 9361:     my $title=&metadata($urlsymb,'title');
 9362:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
 9363:     return $title;
 9364: }
 9365: 
 9366: sub get_slot {
 9367:     my ($which,$cnum,$cdom)=@_;
 9368:     if (!$cnum || !$cdom) {
 9369: 	(undef,my $courseid)=&whichuser();
 9370: 	$cdom=$env{'course.'.$courseid.'.domain'};
 9371: 	$cnum=$env{'course.'.$courseid.'.num'};
 9372:     }
 9373:     my $key=join("\0",'slots',$cdom,$cnum,$which);
 9374:     my %slotinfo;
 9375:     if (exists($remembered{$key})) {
 9376: 	$slotinfo{$which} = $remembered{$key};
 9377:     } else {
 9378: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
 9379: 	&Apache::lonhomework::showhash(%slotinfo);
 9380: 	my ($tmp)=keys(%slotinfo);
 9381: 	if ($tmp=~/^error:/) { return (); }
 9382: 	$remembered{$key} = $slotinfo{$which};
 9383:     }
 9384:     if (ref($slotinfo{$which}) eq 'HASH') {
 9385: 	return %{$slotinfo{$which}};
 9386:     }
 9387:     return $slotinfo{$which};
 9388: }
 9389: # ------------------------------------------------- Update symbolic store links
 9390: 
 9391: sub symblist {
 9392:     my ($mapname,%newhash)=@_;
 9393:     $mapname=&deversion(&declutter($mapname));
 9394:     my %hash;
 9395:     if (($env{'request.course.fn'}) && (%newhash)) {
 9396:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 9397:                       &GDBM_WRCREAT(),0640)) {
 9398: 	    foreach my $url (keys(%newhash)) {
 9399: 		next if ($url eq 'last_known'
 9400: 			 && $env{'form.no_update_last_known'});
 9401: 		$hash{declutter($url)}=&encode_symb($mapname,
 9402: 						    $newhash{$url}->[1],
 9403: 						    $newhash{$url}->[0]);
 9404:             }
 9405:             if (untie(%hash)) {
 9406: 		return 'ok';
 9407:             }
 9408:         }
 9409:     }
 9410:     return 'error';
 9411: }
 9412: 
 9413: # --------------------------------------------------------------- Verify a symb
 9414: 
 9415: sub symbverify {
 9416:     my ($symb,$thisurl)=@_;
 9417:     my $thisfn=$thisurl;
 9418:     $thisfn=&declutter($thisfn);
 9419: # direct jump to resource in page or to a sequence - will construct own symbs
 9420:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
 9421: # check URL part
 9422:     my ($map,$resid,$url)=&decode_symb($symb);
 9423: 
 9424:     unless ($url eq $thisfn) { return 0; }
 9425: 
 9426:     $symb=&symbclean($symb);
 9427:     $thisurl=&deversion($thisurl);
 9428:     $thisfn=&deversion($thisfn);
 9429: 
 9430:     my %bighash;
 9431:     my $okay=0;
 9432: 
 9433:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9434:                             &GDBM_READER(),0640)) {
 9435:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
 9436:             $thisurl =~ s/\?.+$//;
 9437:         }
 9438:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
 9439:         unless ($ids) {
 9440:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
 9441:             $ids=$bighash{$idkey};
 9442:         }
 9443:         if ($ids) {
 9444: # ------------------------------------------------------------------- Has ID(s)
 9445: 	    foreach my $id (split(/\,/,$ids)) {
 9446: 	       my ($mapid,$resid)=split(/\./,$id);
 9447:                if ($thisfn =~ m{^/adm/wrapper/ext/}) {
 9448:                    $symb =~ s/\?.+$//;
 9449:                }
 9450:                if (
 9451:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
 9452:    eq $symb) { 
 9453: 		   if (($env{'request.role.adv'}) ||
 9454: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
 9455:                        ($thisurl eq '/adm/navmaps')) {
 9456: 		       $okay=1; 
 9457: 		   }
 9458: 	       }
 9459: 	   }
 9460:         }
 9461: 	untie(%bighash);
 9462:     }
 9463:     return $okay;
 9464: }
 9465: 
 9466: # --------------------------------------------------------------- Clean-up symb
 9467: 
 9468: sub symbclean {
 9469:     my $symb=shift;
 9470:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 9471: # remove version from map
 9472:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
 9473: 
 9474: # remove version from URL
 9475:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
 9476: 
 9477: # remove wrapper
 9478: 
 9479:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
 9480:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
 9481:     return $symb;
 9482: }
 9483: 
 9484: # ---------------------------------------------- Split symb to find map and url
 9485: 
 9486: sub encode_symb {
 9487:     my ($map,$resid,$url)=@_;
 9488:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
 9489: }
 9490: 
 9491: sub decode_symb {
 9492:     my $symb=shift;
 9493:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 9494:     my ($map,$resid,$url)=split(/___/,$symb);
 9495:     return (&fixversion($map),$resid,&fixversion($url));
 9496: }
 9497: 
 9498: sub fixversion {
 9499:     my $fn=shift;
 9500:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
 9501:     my %bighash;
 9502:     my $uri=&clutter($fn);
 9503:     my $key=$env{'request.course.id'}.'_'.$uri;
 9504: # is this cached?
 9505:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
 9506:     if (defined($cached)) { return $result; }
 9507: # unfortunately not cached, or expired
 9508:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9509: 	    &GDBM_READER(),0640)) {
 9510:  	if ($bighash{'version_'.$uri}) {
 9511:  	    my $version=$bighash{'version_'.$uri};
 9512:  	    unless (($version eq 'mostrecent') || 
 9513: 		    ($version==&getversion($uri))) {
 9514:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
 9515:  	    }
 9516:  	}
 9517:  	untie %bighash;
 9518:     }
 9519:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
 9520: }
 9521: 
 9522: sub deversion {
 9523:     my $url=shift;
 9524:     $url=~s/\.\d+\.(\w+)$/\.$1/;
 9525:     return $url;
 9526: }
 9527: 
 9528: # ------------------------------------------------------ Return symb list entry
 9529: 
 9530: sub symbread {
 9531:     my ($thisfn,$donotrecurse)=@_;
 9532:     my $cache_str='request.symbread.cached.'.$thisfn;
 9533:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
 9534: # no filename provided? try from environment
 9535:     unless ($thisfn) {
 9536:         if ($env{'request.symb'}) {
 9537: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
 9538: 	}
 9539: 	$thisfn=$env{'request.filename'};
 9540:     }
 9541:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 9542: # is that filename actually a symb? Verify, clean, and return
 9543:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
 9544: 	if (&symbverify($thisfn,$1)) {
 9545: 	    return $env{$cache_str}=&symbclean($thisfn);
 9546: 	}
 9547:     }
 9548:     $thisfn=declutter($thisfn);
 9549:     my %hash;
 9550:     my %bighash;
 9551:     my $syval='';
 9552:     if (($env{'request.course.fn'}) && ($thisfn)) {
 9553:         my $targetfn = $thisfn;
 9554:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
 9555:             $targetfn = 'adm/wrapper/'.$thisfn;
 9556:         }
 9557: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
 9558: 	    $targetfn=$1;
 9559: 	}
 9560:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 9561:                       &GDBM_READER(),0640)) {
 9562: 	    $syval=$hash{$targetfn};
 9563:             untie(%hash);
 9564:         }
 9565: # ---------------------------------------------------------- There was an entry
 9566:         if ($syval) {
 9567: 	    #unless ($syval=~/\_\d+$/) {
 9568: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
 9569: 		    #&appenv({'request.ambiguous' => $thisfn});
 9570: 		    #return $env{$cache_str}='';
 9571: 		#}    
 9572: 		#$syval.=$1;
 9573: 	    #}
 9574:         } else {
 9575: # ------------------------------------------------------- Was not in symb table
 9576:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9577:                             &GDBM_READER(),0640)) {
 9578: # ---------------------------------------------- Get ID(s) for current resource
 9579:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
 9580:               unless ($ids) { 
 9581:                  $ids=$bighash{'ids_/'.$thisfn};
 9582:               }
 9583:               unless ($ids) {
 9584: # alias?
 9585: 		  $ids=$bighash{'mapalias_'.$thisfn};
 9586:               }
 9587:               if ($ids) {
 9588: # ------------------------------------------------------------------- Has ID(s)
 9589:                  my @possibilities=split(/\,/,$ids);
 9590:                  if ($#possibilities==0) {
 9591: # ----------------------------------------------- There is only one possibility
 9592: 		     my ($mapid,$resid)=split(/\./,$ids);
 9593: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
 9594: 						    $resid,$thisfn);
 9595:                  } elsif (!$donotrecurse) {
 9596: # ------------------------------------------ There is more than one possibility
 9597:                      my $realpossible=0;
 9598:                      foreach my $id (@possibilities) {
 9599: 			 my $file=$bighash{'src_'.$id};
 9600:                          if (&allowed('bre',$file)) {
 9601:          		    my ($mapid,$resid)=split(/\./,$id);
 9602:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
 9603: 				$realpossible++;
 9604:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
 9605: 						    $resid,$thisfn);
 9606:                             }
 9607: 			 }
 9608:                      }
 9609: 		     if ($realpossible!=1) { $syval=''; }
 9610:                  } else {
 9611:                      $syval='';
 9612:                  }
 9613: 	      }
 9614:               untie(%bighash)
 9615:            }
 9616:         }
 9617:         if ($syval) {
 9618: 	    return $env{$cache_str}=$syval;
 9619:         }
 9620:     }
 9621:     &appenv({'request.ambiguous' => $thisfn});
 9622:     return $env{$cache_str}='';
 9623: }
 9624: 
 9625: # ---------------------------------------------------------- Return random seed
 9626: 
 9627: sub numval {
 9628:     my $txt=shift;
 9629:     $txt=~tr/A-J/0-9/;
 9630:     $txt=~tr/a-j/0-9/;
 9631:     $txt=~tr/K-T/0-9/;
 9632:     $txt=~tr/k-t/0-9/;
 9633:     $txt=~tr/U-Z/0-5/;
 9634:     $txt=~tr/u-z/0-5/;
 9635:     $txt=~s/\D//g;
 9636:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
 9637:     return int($txt);
 9638: }
 9639: 
 9640: sub numval2 {
 9641:     my $txt=shift;
 9642:     $txt=~tr/A-J/0-9/;
 9643:     $txt=~tr/a-j/0-9/;
 9644:     $txt=~tr/K-T/0-9/;
 9645:     $txt=~tr/k-t/0-9/;
 9646:     $txt=~tr/U-Z/0-5/;
 9647:     $txt=~tr/u-z/0-5/;
 9648:     $txt=~s/\D//g;
 9649:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 9650:     my $total;
 9651:     foreach my $val (@txts) { $total+=$val; }
 9652:     if ($_64bit) { if ($total > 2**32) { return -1; } }
 9653:     return int($total);
 9654: }
 9655: 
 9656: sub numval3 {
 9657:     use integer;
 9658:     my $txt=shift;
 9659:     $txt=~tr/A-J/0-9/;
 9660:     $txt=~tr/a-j/0-9/;
 9661:     $txt=~tr/K-T/0-9/;
 9662:     $txt=~tr/k-t/0-9/;
 9663:     $txt=~tr/U-Z/0-5/;
 9664:     $txt=~tr/u-z/0-5/;
 9665:     $txt=~s/\D//g;
 9666:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 9667:     my $total;
 9668:     foreach my $val (@txts) { $total+=$val; }
 9669:     if ($_64bit) { $total=(($total<<32)>>32); }
 9670:     return $total;
 9671: }
 9672: 
 9673: sub digest {
 9674:     my ($data)=@_;
 9675:     my $digest=&Digest::MD5::md5($data);
 9676:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
 9677:     my ($e,$f);
 9678:     {
 9679:         use integer;
 9680:         $e=($a+$b);
 9681:         $f=($c+$d);
 9682:         if ($_64bit) {
 9683:             $e=(($e<<32)>>32);
 9684:             $f=(($f<<32)>>32);
 9685:         }
 9686:     }
 9687:     if (wantarray) {
 9688: 	return ($e,$f);
 9689:     } else {
 9690: 	my $g;
 9691: 	{
 9692: 	    use integer;
 9693: 	    $g=($e+$f);
 9694: 	    if ($_64bit) {
 9695: 		$g=(($g<<32)>>32);
 9696: 	    }
 9697: 	}
 9698: 	return $g;
 9699:     }
 9700: }
 9701: 
 9702: sub latest_rnd_algorithm_id {
 9703:     return '64bit5';
 9704: }
 9705: 
 9706: sub get_rand_alg {
 9707:     my ($courseid)=@_;
 9708:     if (!$courseid) { $courseid=(&whichuser())[1]; }
 9709:     if ($courseid) {
 9710: 	return $env{"course.$courseid.rndseed"};
 9711:     }
 9712:     return &latest_rnd_algorithm_id();
 9713: }
 9714: 
 9715: sub validCODE {
 9716:     my ($CODE)=@_;
 9717:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
 9718:     return 0;
 9719: }
 9720: 
 9721: sub getCODE {
 9722:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
 9723:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
 9724: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
 9725: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
 9726: 	return $Apache::lonhomework::history{'resource.CODE'};
 9727:     }
 9728:     return undef;
 9729: }
 9730: #
 9731: #  Determines the random seed for a specific context:
 9732: #
 9733: # parameters:
 9734: #   symb      - in course context the symb for the seed.
 9735: #   course_id - The course id of the form domain_coursenum.
 9736: #   domain    - Domain for the user.
 9737: #   course    - Course for the user.
 9738: #   cenv      - environment of the course.
 9739: #
 9740: # NOTE:
 9741: #   All parameters are picked out of the environment if missing
 9742: #   or not defined.
 9743: #   If a symb cannot be determined the current time is used instead.
 9744: #
 9745: #  For a given well defined symb, courside, domain, username,
 9746: #  and course environment, the seed is reproducible.
 9747: #
 9748: sub rndseed {
 9749:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
 9750:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
 9751:     if (!defined($symb)) {
 9752: 	unless ($symb=$wsymb) { return time; }
 9753:     }
 9754:     if (!$courseid) { $courseid=$wcourseid; }
 9755:     if (!$domain) { $domain=$wdomain; }
 9756:     if (!$username) { $username=$wusername }
 9757: 
 9758:     my $which;
 9759:     if (defined($cenv->{'rndseed'})) {
 9760: 	$which = $cenv->{'rndseed'};
 9761:     } else {
 9762: 	$which =&get_rand_alg($courseid);
 9763:     }
 9764: 
 9765:     if (defined(&getCODE())) {
 9766: 
 9767: 	if ($which eq '64bit5') {
 9768: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
 9769: 	} elsif ($which eq '64bit4') {
 9770: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
 9771: 	} else {
 9772: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
 9773: 	}
 9774:     } elsif ($which eq '64bit5') {
 9775: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
 9776:     } elsif ($which eq '64bit4') {
 9777: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
 9778:     } elsif ($which eq '64bit3') {
 9779: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
 9780:     } elsif ($which eq '64bit2') {
 9781: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
 9782:     } elsif ($which eq '64bit') {
 9783: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
 9784:     }
 9785:     return &rndseed_32bit($symb,$courseid,$domain,$username);
 9786: }
 9787: 
 9788: sub rndseed_32bit {
 9789:     my ($symb,$courseid,$domain,$username)=@_;
 9790:     {
 9791: 	use integer;
 9792: 	my $symbchck=unpack("%32C*",$symb) << 27;
 9793: 	my $symbseed=numval($symb) << 22;
 9794: 	my $namechck=unpack("%32C*",$username) << 17;
 9795: 	my $nameseed=numval($username) << 12;
 9796: 	my $domainseed=unpack("%32C*",$domain) << 7;
 9797: 	my $courseseed=unpack("%32C*",$courseid);
 9798: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
 9799: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 9800: 	#&logthis("rndseed :$num:$symb");
 9801: 	if ($_64bit) { $num=(($num<<32)>>32); }
 9802: 	return $num;
 9803:     }
 9804: }
 9805: 
 9806: sub rndseed_64bit {
 9807:     my ($symb,$courseid,$domain,$username)=@_;
 9808:     {
 9809: 	use integer;
 9810: 	my $symbchck=unpack("%32S*",$symb) << 21;
 9811: 	my $symbseed=numval($symb) << 10;
 9812: 	my $namechck=unpack("%32S*",$username);
 9813: 	
 9814: 	my $nameseed=numval($username) << 21;
 9815: 	my $domainseed=unpack("%32S*",$domain) << 10;
 9816: 	my $courseseed=unpack("%32S*",$courseid);
 9817: 	
 9818: 	my $num1=$symbchck+$symbseed+$namechck;
 9819: 	my $num2=$nameseed+$domainseed+$courseseed;
 9820: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 9821: 	#&logthis("rndseed :$num:$symb");
 9822: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 9823: 	return "$num1,$num2";
 9824:     }
 9825: }
 9826: 
 9827: sub rndseed_64bit2 {
 9828:     my ($symb,$courseid,$domain,$username)=@_;
 9829:     {
 9830: 	use integer;
 9831: 	# strings need to be an even # of cahracters long, it it is odd the
 9832:         # last characters gets thrown away
 9833: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 9834: 	my $symbseed=numval($symb) << 10;
 9835: 	my $namechck=unpack("%32S*",$username.' ');
 9836: 	
 9837: 	my $nameseed=numval($username) << 21;
 9838: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 9839: 	my $courseseed=unpack("%32S*",$courseid.' ');
 9840: 	
 9841: 	my $num1=$symbchck+$symbseed+$namechck;
 9842: 	my $num2=$nameseed+$domainseed+$courseseed;
 9843: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 9844: 	#&logthis("rndseed :$num:$symb");
 9845: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 9846: 	return "$num1,$num2";
 9847:     }
 9848: }
 9849: 
 9850: sub rndseed_64bit3 {
 9851:     my ($symb,$courseid,$domain,$username)=@_;
 9852:     {
 9853: 	use integer;
 9854: 	# strings need to be an even # of cahracters long, it it is odd the
 9855:         # last characters gets thrown away
 9856: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 9857: 	my $symbseed=numval2($symb) << 10;
 9858: 	my $namechck=unpack("%32S*",$username.' ');
 9859: 	
 9860: 	my $nameseed=numval2($username) << 21;
 9861: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 9862: 	my $courseseed=unpack("%32S*",$courseid.' ');
 9863: 	
 9864: 	my $num1=$symbchck+$symbseed+$namechck;
 9865: 	my $num2=$nameseed+$domainseed+$courseseed;
 9866: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 9867: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 9868: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 9869: 	
 9870: 	return "$num1:$num2";
 9871:     }
 9872: }
 9873: 
 9874: sub rndseed_64bit4 {
 9875:     my ($symb,$courseid,$domain,$username)=@_;
 9876:     {
 9877: 	use integer;
 9878: 	# strings need to be an even # of cahracters long, it it is odd the
 9879:         # last characters gets thrown away
 9880: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 9881: 	my $symbseed=numval3($symb) << 10;
 9882: 	my $namechck=unpack("%32S*",$username.' ');
 9883: 	
 9884: 	my $nameseed=numval3($username) << 21;
 9885: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 9886: 	my $courseseed=unpack("%32S*",$courseid.' ');
 9887: 	
 9888: 	my $num1=$symbchck+$symbseed+$namechck;
 9889: 	my $num2=$nameseed+$domainseed+$courseseed;
 9890: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 9891: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 9892: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 9893: 	
 9894: 	return "$num1:$num2";
 9895:     }
 9896: }
 9897: 
 9898: sub rndseed_64bit5 {
 9899:     my ($symb,$courseid,$domain,$username)=@_;
 9900:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
 9901:     return "$num1:$num2";
 9902: }
 9903: 
 9904: sub rndseed_CODE_64bit {
 9905:     my ($symb,$courseid,$domain,$username)=@_;
 9906:     {
 9907: 	use integer;
 9908: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 9909: 	my $symbseed=numval2($symb);
 9910: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 9911: 	my $CODEseed=numval(&getCODE());
 9912: 	my $courseseed=unpack("%32S*",$courseid.' ');
 9913: 	my $num1=$symbseed+$CODEchck;
 9914: 	my $num2=$CODEseed+$courseseed+$symbchck;
 9915: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 9916: 	#&logthis("rndseed :$num1:$num2:$symb");
 9917: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 9918: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 9919: 	return "$num1:$num2";
 9920:     }
 9921: }
 9922: 
 9923: sub rndseed_CODE_64bit4 {
 9924:     my ($symb,$courseid,$domain,$username)=@_;
 9925:     {
 9926: 	use integer;
 9927: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 9928: 	my $symbseed=numval3($symb);
 9929: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 9930: 	my $CODEseed=numval3(&getCODE());
 9931: 	my $courseseed=unpack("%32S*",$courseid.' ');
 9932: 	my $num1=$symbseed+$CODEchck;
 9933: 	my $num2=$CODEseed+$courseseed+$symbchck;
 9934: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 9935: 	#&logthis("rndseed :$num1:$num2:$symb");
 9936: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 9937: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 9938: 	return "$num1:$num2";
 9939:     }
 9940: }
 9941: 
 9942: sub rndseed_CODE_64bit5 {
 9943:     my ($symb,$courseid,$domain,$username)=@_;
 9944:     my $code = &getCODE();
 9945:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
 9946:     return "$num1:$num2";
 9947: }
 9948: 
 9949: sub setup_random_from_rndseed {
 9950:     my ($rndseed)=@_;
 9951:     if ($rndseed =~/([,:])/) {
 9952: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
 9953: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
 9954:     } else {
 9955: 	&Math::Random::random_set_seed_from_phrase($rndseed);
 9956:     }
 9957: }
 9958: 
 9959: sub latest_receipt_algorithm_id {
 9960:     return 'receipt3';
 9961: }
 9962: 
 9963: sub recunique {
 9964:     my $fucourseid=shift;
 9965:     my $unique;
 9966:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
 9967: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 9968: 	$unique=$env{"course.$fucourseid.internal.encseed"};
 9969:     } else {
 9970: 	$unique=$perlvar{'lonReceipt'};
 9971:     }
 9972:     return unpack("%32C*",$unique);
 9973: }
 9974: 
 9975: sub recprefix {
 9976:     my $fucourseid=shift;
 9977:     my $prefix;
 9978:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
 9979: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 9980: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
 9981:     } else {
 9982: 	$prefix=$perlvar{'lonHostID'};
 9983:     }
 9984:     return unpack("%32C*",$prefix);
 9985: }
 9986: 
 9987: sub ireceipt {
 9988:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
 9989: 
 9990:     my $return =&recprefix($fucourseid).'-';
 9991: 
 9992:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
 9993: 	$env{'request.state'} eq 'construct') {
 9994: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
 9995: 	return $return;
 9996:     }
 9997: 
 9998:     my $cuname=unpack("%32C*",$funame);
 9999:     my $cudom=unpack("%32C*",$fudom);
10000:     my $cucourseid=unpack("%32C*",$fucourseid);
10001:     my $cusymb=unpack("%32C*",$fusymb);
10002:     my $cunique=&recunique($fucourseid);
10003:     my $cpart=unpack("%32S*",$part);
10004:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
10005: 
10006: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
10007: 			       
10008: 	$return.= ($cunique%$cuname+
10009: 		   $cunique%$cudom+
10010: 		   $cusymb%$cuname+
10011: 		   $cusymb%$cudom+
10012: 		   $cucourseid%$cuname+
10013: 		   $cucourseid%$cudom+
10014: 		   $cpart%$cuname+
10015: 		   $cpart%$cudom);
10016:     } else {
10017: 	$return.= ($cunique%$cuname+
10018: 		   $cunique%$cudom+
10019: 		   $cusymb%$cuname+
10020: 		   $cusymb%$cudom+
10021: 		   $cucourseid%$cuname+
10022: 		   $cucourseid%$cudom);
10023:     }
10024:     return $return;
10025: }
10026: 
10027: sub receipt {
10028:     my ($part)=@_;
10029:     my ($symb,$courseid,$domain,$name) = &whichuser();
10030:     return &ireceipt($name,$domain,$courseid,$symb,$part);
10031: }
10032: 
10033: sub whichuser {
10034:     my ($passedsymb)=@_;
10035:     my ($symb,$courseid,$domain,$name,$publicuser);
10036:     if (defined($env{'form.grade_symb'})) {
10037: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
10038: 	my $allowed=&allowed('vgr',$tmp_courseid);
10039: 	if (!$allowed &&
10040: 	    exists($env{'request.course.sec'}) &&
10041: 	    $env{'request.course.sec'} !~ /^\s*$/) {
10042: 	    $allowed=&allowed('vgr',$tmp_courseid.
10043: 			      '/'.$env{'request.course.sec'});
10044: 	}
10045: 	if ($allowed) {
10046: 	    ($symb)=&get_env_multiple('form.grade_symb');
10047: 	    $courseid=$tmp_courseid;
10048: 	    ($domain)=&get_env_multiple('form.grade_domain');
10049: 	    ($name)=&get_env_multiple('form.grade_username');
10050: 	    return ($symb,$courseid,$domain,$name,$publicuser);
10051: 	}
10052:     }
10053:     if (!$passedsymb) {
10054: 	$symb=&symbread();
10055:     } else {
10056: 	$symb=$passedsymb;
10057:     }
10058:     $courseid=$env{'request.course.id'};
10059:     $domain=$env{'user.domain'};
10060:     $name=$env{'user.name'};
10061:     if ($name eq 'public' && $domain eq 'public') {
10062: 	if (!defined($env{'form.username'})) {
10063: 	    $env{'form.username'}.=time.rand(10000000);
10064: 	}
10065: 	$name.=$env{'form.username'};
10066:     }
10067:     return ($symb,$courseid,$domain,$name,$publicuser);
10068: 
10069: }
10070: 
10071: # ------------------------------------------------------------ Serves up a file
10072: # returns either the contents of the file or 
10073: # -1 if the file doesn't exist
10074: #
10075: # if the target is a file that was uploaded via DOCS, 
10076: # a check will be made to see if a current copy exists on the local server,
10077: # if it does this will be served, otherwise a copy will be retrieved from
10078: # the home server for the course and stored in /home/httpd/html/userfiles on
10079: # the local server.   
10080: 
10081: sub getfile {
10082:     my ($file) = @_;
10083:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
10084:     &repcopy($file);
10085:     return &readfile($file);
10086: }
10087: 
10088: sub repcopy_userfile {
10089:     my ($file)=@_;
10090:     my $londocroot = $perlvar{'lonDocRoot'};
10091:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
10092:     if ($file =~ m{^\Q$londocroot/lonUsers/\E}) { return 'ok'; }
10093:     my ($cdom,$cnum,$filename) = 
10094: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
10095:     my $uri="/uploaded/$cdom/$cnum/$filename";
10096:     if (-e "$file") {
10097: # we already have a local copy, check it out
10098: 	my @fileinfo = stat($file);
10099: 	my $rtncode;
10100: 	my $info;
10101: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
10102: 	if ($lwpresp ne 'ok') {
10103: # there is no such file anymore, even though we had a local copy
10104: 	    if ($rtncode eq '404') {
10105: 		unlink($file);
10106: 	    }
10107: 	    return -1;
10108: 	}
10109: 	if ($info < $fileinfo[9]) {
10110: # nice, the file we have is up-to-date, just say okay
10111: 	    return 'ok';
10112: 	} else {
10113: # the file is outdated, get rid of it
10114: 	    unlink($file);
10115: 	}
10116:     }
10117: # one way or the other, at this point, we don't have the file
10118: # construct the correct path for the file
10119:     my @parts = ($cdom,$cnum); 
10120:     if ($filename =~ m|^(.+)/[^/]+$|) {
10121: 	push @parts, split(/\//,$1);
10122:     }
10123:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
10124:     foreach my $part (@parts) {
10125: 	$path .= '/'.$part;
10126: 	if (!-e $path) {
10127: 	    mkdir($path,0770);
10128: 	}
10129:     }
10130: # now the path exists for sure
10131: # get a user agent
10132:     my $ua=new LWP::UserAgent;
10133:     my $transferfile=$file.'.in.transfer';
10134: # FIXME: this should flock
10135:     if (-e $transferfile) { return 'ok'; }
10136:     my $request;
10137:     $uri=~s/^\///;
10138:     my $homeserver = &homeserver($cnum,$cdom);
10139:     my $protocol = $protocol{$homeserver};
10140:     $protocol = 'http' if ($protocol ne 'https');
10141:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
10142:     my $response=$ua->request($request,$transferfile);
10143: # did it work?
10144:     if ($response->is_error()) {
10145: 	unlink($transferfile);
10146: 	&logthis("Userfile repcopy failed for $uri");
10147: 	return -1;
10148:     }
10149: # worked, rename the transfer file
10150:     rename($transferfile,$file);
10151:     return 'ok';
10152: }
10153: 
10154: sub tokenwrapper {
10155:     my $uri=shift;
10156:     $uri=~s|^https?\://([^/]+)||;
10157:     $uri=~s|^/||;
10158:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
10159:     my $token=$1;
10160:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
10161:     if ($udom && $uname && $file) {
10162: 	$file=~s|(\?\.*)*$||;
10163:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
10164:         my $homeserver = &homeserver($uname,$udom);
10165:         my $protocol = $protocol{$homeserver};
10166:         $protocol = 'http' if ($protocol ne 'https');
10167:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
10168:                (($uri=~/\?/)?'&':'?').'token='.$token.
10169:                                '&tokenissued='.$perlvar{'lonHostID'};
10170:     } else {
10171:         return '/adm/notfound.html';
10172:     }
10173: }
10174: 
10175: # call with reqtype HEAD: get last modification time
10176: # call with reqtype GET: get the file contents
10177: # Do not call this with reqtype GET for large files! It loads everything into memory
10178: #
10179: sub getuploaded {
10180:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
10181:     $uri=~s/^\///;
10182:     my $homeserver = &homeserver($cnum,$cdom);
10183:     my $protocol = $protocol{$homeserver};
10184:     $protocol = 'http' if ($protocol ne 'https');
10185:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
10186:     my $ua=new LWP::UserAgent;
10187:     my $request=new HTTP::Request($reqtype,$uri);
10188:     my $response=$ua->request($request);
10189:     $$rtncode = $response->code;
10190:     if (! $response->is_success()) {
10191: 	return 'failed';
10192:     }      
10193:     if ($reqtype eq 'HEAD') {
10194: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
10195:     } elsif ($reqtype eq 'GET') {
10196: 	$$info = $response->content;
10197:     }
10198:     return 'ok';
10199: }
10200: 
10201: sub readfile {
10202:     my $file = shift;
10203:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
10204:     my $fh;
10205:     open($fh,"<$file");
10206:     my $a='';
10207:     while (my $line = <$fh>) { $a .= $line; }
10208:     return $a;
10209: }
10210: 
10211: sub filelocation {
10212:     my ($dir,$file) = @_;
10213:     my $location;
10214:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
10215: 
10216:     if ($file =~ m-^/adm/-) {
10217: 	$file=~s-^/adm/wrapper/-/-;
10218: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
10219:     }
10220: 
10221:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
10222:         $location = $file;
10223:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
10224:         my ($udom,$uname,$filename)=
10225:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
10226:         my $home=&homeserver($uname,$udom);
10227:         my $is_me=0;
10228:         my @ids=&current_machine_ids();
10229:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
10230:         if ($is_me) {
10231:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
10232:         } else {
10233:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
10234:   	      $udom.'/'.$uname.'/'.$filename;
10235:         }
10236:     } elsif ($file =~ m-^/adm/-) {
10237: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
10238:     } else {
10239:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
10240:         $file=~s:^/(res|priv)/:/:;
10241:         my $space=$1;
10242:         if ( !( $file =~ m:^/:) ) {
10243:             $location = $dir. '/'.$file;
10244:         } else {
10245:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
10246:         }
10247:     }
10248:     $location=~s://+:/:g; # remove duplicate /
10249:     while ($location=~m{/\.\./}) {
10250: 	if ($location =~ m{/[^/]+/\.\./}) {
10251: 	    $location=~ s{/[^/]+/\.\./}{/}g;
10252: 	} else {
10253: 	    $location=~ s{/\.\./}{/}g;
10254: 	}
10255:     } #remove dir/..
10256:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
10257:     return $location;
10258: }
10259: 
10260: sub hreflocation {
10261:     my ($dir,$file)=@_;
10262:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
10263: 	$file=filelocation($dir,$file);
10264:     } elsif ($file=~m-^/adm/-) {
10265: 	$file=~s-^/adm/wrapper/-/-;
10266: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
10267:     }
10268:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
10269: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
10270:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
10271: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
10272: 	        {/uploaded/$1/$2/}x;
10273:     }
10274:     if ($file=~ m{^/userfiles/}) {
10275: 	$file =~ s{^/userfiles/}{/uploaded/};
10276:     }
10277:     return $file;
10278: }
10279: 
10280: 
10281: 
10282: 
10283: 
10284: sub current_machine_domains {
10285:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
10286: }
10287: 
10288: sub machine_domains {
10289:     my ($hostname) = @_;
10290:     my @domains;
10291:     my %hostname = &all_hostnames();
10292:     while( my($id, $name) = each(%hostname)) {
10293: #	&logthis("-$id-$name-$hostname-");
10294: 	if ($hostname eq $name) {
10295: 	    push(@domains,&host_domain($id));
10296: 	}
10297:     }
10298:     return @domains;
10299: }
10300: 
10301: sub current_machine_ids {
10302:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
10303: }
10304: 
10305: sub machine_ids {
10306:     my ($hostname) = @_;
10307:     $hostname ||= &hostname($perlvar{'lonHostID'});
10308:     my @ids;
10309:     my %name_to_host = &all_names();
10310:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
10311: 	return @{ $name_to_host{$hostname} };
10312:     }
10313:     return;
10314: }
10315: 
10316: sub additional_machine_domains {
10317:     my @domains;
10318:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
10319:     while( my $line = <$fh>) {
10320:         $line =~ s/\s//g;
10321:         push(@domains,$line);
10322:     }
10323:     return @domains;
10324: }
10325: 
10326: sub default_login_domain {
10327:     my $domain = $perlvar{'lonDefDomain'};
10328:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
10329:     foreach my $posdom (&current_machine_domains(),
10330:                         &additional_machine_domains()) {
10331:         if (lc($posdom) eq lc($testdomain)) {
10332:             $domain=$posdom;
10333:             last;
10334:         }
10335:     }
10336:     return $domain;
10337: }
10338: 
10339: # ------------------------------------------------------------- Declutters URLs
10340: 
10341: sub declutter {
10342:     my $thisfn=shift;
10343:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
10344:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
10345:     $thisfn=~s/^\///;
10346:     $thisfn=~s|^adm/wrapper/||;
10347:     $thisfn=~s|^adm/coursedocs/showdoc/||;
10348:     $thisfn=~s/^res\///;
10349:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
10350:         $thisfn=~s/\?.+$//;
10351:     }
10352:     return $thisfn;
10353: }
10354: 
10355: # ------------------------------------------------------------- Clutter up URLs
10356: 
10357: sub clutter {
10358:     my $thisfn='/'.&declutter(shift);
10359:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
10360: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
10361:        $thisfn='/res'.$thisfn; 
10362:     }
10363:     if ($thisfn !~m|^/adm|) {
10364: 	if ($thisfn =~ m|^/ext/|) {
10365: 	    $thisfn='/adm/wrapper'.$thisfn;
10366: 	} else {
10367: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
10368: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
10369: 	    if ($embstyle eq 'ssi'
10370: 		|| ($embstyle eq 'hdn')
10371: 		|| ($embstyle eq 'rat')
10372: 		|| ($embstyle eq 'prv')
10373: 		|| ($embstyle eq 'ign')) {
10374: 		#do nothing with these
10375: 	    } elsif (($embstyle eq 'img') 
10376: 		|| ($embstyle eq 'emb')
10377: 		|| ($embstyle eq 'wrp')) {
10378: 		$thisfn='/adm/wrapper'.$thisfn;
10379: 	    } elsif ($embstyle eq 'unk'
10380: 		     && $thisfn!~/\.(sequence|page)$/) {
10381: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
10382: 	    } else {
10383: #		&logthis("Got a blank emb style");
10384: 	    }
10385: 	}
10386:     }
10387:     return $thisfn;
10388: }
10389: 
10390: sub clutter_with_no_wrapper {
10391:     my $uri = &clutter(shift);
10392:     if ($uri =~ m-^/adm/-) {
10393: 	$uri =~ s-^/adm/wrapper/-/-;
10394: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
10395:     }
10396:     return $uri;
10397: }
10398: 
10399: sub freeze_escape {
10400:     my ($value)=@_;
10401:     if (ref($value)) {
10402: 	$value=&nfreeze($value);
10403: 	return '__FROZEN__'.&escape($value);
10404:     }
10405:     return &escape($value);
10406: }
10407: 
10408: 
10409: sub thaw_unescape {
10410:     my ($value)=@_;
10411:     if ($value =~ /^__FROZEN__/) {
10412: 	substr($value,0,10,undef);
10413: 	$value=&unescape($value);
10414: 	return &thaw($value);
10415:     }
10416:     return &unescape($value);
10417: }
10418: 
10419: sub correct_line_ends {
10420:     my ($result)=@_;
10421:     $$result =~s/\r\n/\n/mg;
10422:     $$result =~s/\r/\n/mg;
10423: }
10424: # ================================================================ Main Program
10425: 
10426: sub goodbye {
10427:    &logthis("Starting Shut down");
10428: #not converted to using infrastruture and probably shouldn't be
10429:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
10430: #converted
10431: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
10432:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
10433: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
10434: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
10435: #1.1 only
10436: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
10437: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
10438: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
10439: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
10440:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
10441:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
10442:    &logthis(sprintf("%-20s is %s",'hits',$hits));
10443:    &flushcourselogs();
10444:    &logthis("Shutting down");
10445: }
10446: 
10447: sub get_dns {
10448:     my ($url,$func,$ignore_cache) = @_;
10449:     if (!$ignore_cache) {
10450: 	my ($content,$cached)=
10451: 	    &Apache::lonnet::is_cached_new('dns',$url);
10452: 	if ($cached) {
10453: 	    &$func($content);
10454: 	    return;
10455: 	}
10456:     }
10457: 
10458:     my %alldns;
10459:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
10460:     foreach my $dns (<$config>) {
10461: 	next if ($dns !~ /^\^(\S*)/x);
10462:         my $line = $1;
10463:         my ($host,$protocol) = split(/:/,$line);
10464:         if ($protocol ne 'https') {
10465:             $protocol = 'http';
10466:         }
10467: 	$alldns{$host} = $protocol;
10468:     }
10469:     while (%alldns) {
10470: 	my ($dns) = keys(%alldns);
10471: 	my $ua=new LWP::UserAgent;
10472:         $ua->timeout(30);
10473: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
10474: 	my $response=$ua->request($request);
10475:         delete($alldns{$dns});
10476: 	next if ($response->is_error());
10477: 	my @content = split("\n",$response->content);
10478: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
10479: 	&$func(\@content);
10480: 	return;
10481:     }
10482:     close($config);
10483:     my $which = (split('/',$url))[3];
10484:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
10485:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
10486:     my @content = <$config>;
10487:     &$func(\@content);
10488:     return;
10489: }
10490: # ------------------------------------------------------------ Read domain file
10491: {
10492:     my $loaded;
10493:     my %domain;
10494: 
10495:     sub parse_domain_tab {
10496: 	my ($lines) = @_;
10497: 	foreach my $line (@$lines) {
10498: 	    next if ($line =~ /^(\#|\s*$ )/x);
10499: 
10500: 	    chomp($line);
10501: 	    my ($name,@elements) = split(/:/,$line,9);
10502: 	    my %this_domain;
10503: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
10504: 			       'lang_def', 'city', 'longi', 'lati',
10505: 			       'primary') {
10506: 		$this_domain{$field} = shift(@elements);
10507: 	    }
10508: 	    $domain{$name} = \%this_domain;
10509: 	}
10510:     }
10511: 
10512:     sub reset_domain_info {
10513: 	undef($loaded);
10514: 	undef(%domain);
10515:     }
10516: 
10517:     sub load_domain_tab {
10518: 	my ($ignore_cache) = @_;
10519: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
10520: 	my $fh;
10521: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
10522: 	    my @lines = <$fh>;
10523: 	    &parse_domain_tab(\@lines);
10524: 	}
10525: 	close($fh);
10526: 	$loaded = 1;
10527:     }
10528: 
10529:     sub domain {
10530: 	&load_domain_tab() if (!$loaded);
10531: 
10532: 	my ($name,$what) = @_;
10533: 	return if ( !exists($domain{$name}) );
10534: 
10535: 	if (!$what) {
10536: 	    return $domain{$name}{'description'};
10537: 	}
10538: 	return $domain{$name}{$what};
10539:     }
10540: 
10541:     sub domain_info {
10542:         &load_domain_tab() if (!$loaded);
10543:         return %domain;
10544:     }
10545: 
10546: }
10547: 
10548: 
10549: # ------------------------------------------------------------- Read hosts file
10550: {
10551:     my %hostname;
10552:     my %hostdom;
10553:     my %libserv;
10554:     my $loaded;
10555:     my %name_to_host;
10556:     my %internetdom;
10557:     my %LC_dns_serv;
10558: 
10559:     sub parse_hosts_tab {
10560: 	my ($file) = @_;
10561: 	foreach my $configline (@$file) {
10562: 	    next if ($configline =~ /^(\#|\s*$ )/x);
10563:             chomp($configline);
10564: 	    if ($configline =~ /^\^/) {
10565:                 if ($configline =~ /^\^([\w.\-]+)/) {
10566:                     $LC_dns_serv{$1} = 1;
10567:                 }
10568:                 next;
10569:             }
10570: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
10571: 	    $name=~s/\s//g;
10572: 	    if ($id && $domain && $role && $name) {
10573: 		$hostname{$id}=$name;
10574: 		push(@{$name_to_host{$name}}, $id);
10575: 		$hostdom{$id}=$domain;
10576: 		if ($role eq 'library') { $libserv{$id}=$name; }
10577:                 if (defined($protocol)) {
10578:                     if ($protocol eq 'https') {
10579:                         $protocol{$id} = $protocol;
10580:                     } else {
10581:                         $protocol{$id} = 'http'; 
10582:                     }
10583:                 } else {
10584:                     $protocol{$id} = 'http';
10585:                 }
10586:                 if (defined($intdom)) {
10587:                     $internetdom{$id} = $intdom;
10588:                 }
10589: 	    }
10590: 	}
10591:     }
10592:     
10593:     sub reset_hosts_info {
10594: 	&purge_remembered();
10595: 	&reset_domain_info();
10596: 	&reset_hosts_ip_info();
10597: 	undef(%name_to_host);
10598: 	undef(%hostname);
10599: 	undef(%hostdom);
10600: 	undef(%libserv);
10601: 	undef($loaded);
10602:     }
10603: 
10604:     sub load_hosts_tab {
10605: 	my ($ignore_cache) = @_;
10606: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
10607: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
10608: 	my @config = <$config>;
10609: 	&parse_hosts_tab(\@config);
10610: 	close($config);
10611: 	$loaded=1;
10612:     }
10613: 
10614:     sub hostname {
10615: 	&load_hosts_tab() if (!$loaded);
10616: 
10617: 	my ($lonid) = @_;
10618: 	return $hostname{$lonid};
10619:     }
10620: 
10621:     sub all_hostnames {
10622: 	&load_hosts_tab() if (!$loaded);
10623: 
10624: 	return %hostname;
10625:     }
10626: 
10627:     sub all_names {
10628: 	&load_hosts_tab() if (!$loaded);
10629: 
10630: 	return %name_to_host;
10631:     }
10632: 
10633:     sub all_host_domain {
10634:         &load_hosts_tab() if (!$loaded);
10635:         return %hostdom;
10636:     }
10637: 
10638:     sub is_library {
10639: 	&load_hosts_tab() if (!$loaded);
10640: 
10641: 	return exists($libserv{$_[0]});
10642:     }
10643: 
10644:     sub all_library {
10645: 	&load_hosts_tab() if (!$loaded);
10646: 
10647: 	return %libserv;
10648:     }
10649: 
10650:     sub unique_library {
10651: 	#2x reverse removes all hostnames that appear more than once
10652:         my %unique = reverse &all_library();
10653:         return reverse %unique;
10654:     }
10655: 
10656:     sub get_servers {
10657: 	&load_hosts_tab() if (!$loaded);
10658: 
10659: 	my ($domain,$type) = @_;
10660: 	my %possible_hosts = ($type eq 'library') ? %libserv
10661: 	                                          : %hostname;
10662: 	my %result;
10663: 	if (ref($domain) eq 'ARRAY') {
10664: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
10665: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
10666: 		    $result{$host} = $hostname;
10667: 		}
10668: 	    }
10669: 	} else {
10670: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
10671: 		if ($hostdom{$host} eq $domain) {
10672: 		    $result{$host} = $hostname;
10673: 		}
10674: 	    }
10675: 	}
10676: 	return %result;
10677:     }
10678: 
10679:     sub get_unique_servers {
10680:         my %unique = reverse &get_servers(@_);
10681: 	return reverse %unique;
10682:     }
10683: 
10684:     sub host_domain {
10685: 	&load_hosts_tab() if (!$loaded);
10686: 
10687: 	my ($lonid) = @_;
10688: 	return $hostdom{$lonid};
10689:     }
10690: 
10691:     sub all_domains {
10692: 	&load_hosts_tab() if (!$loaded);
10693: 
10694: 	my %seen;
10695: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
10696: 	return @uniq;
10697:     }
10698: 
10699:     sub internet_dom {
10700:         &load_hosts_tab() if (!$loaded);
10701: 
10702:         my ($lonid) = @_;
10703:         return $internetdom{$lonid};
10704:     }
10705: 
10706:     sub is_LC_dns {
10707:         &load_hosts_tab() if (!$loaded);
10708: 
10709:         my ($hostname) = @_;
10710:         return exists($LC_dns_serv{$hostname});
10711:     }
10712: 
10713: }
10714: 
10715: { 
10716:     my %iphost;
10717:     my %name_to_ip;
10718:     my %lonid_to_ip;
10719: 
10720:     sub get_hosts_from_ip {
10721: 	my ($ip) = @_;
10722: 	my %iphosts = &get_iphost();
10723: 	if (ref($iphosts{$ip})) {
10724: 	    return @{$iphosts{$ip}};
10725: 	}
10726: 	return;
10727:     }
10728:     
10729:     sub reset_hosts_ip_info {
10730: 	undef(%iphost);
10731: 	undef(%name_to_ip);
10732: 	undef(%lonid_to_ip);
10733:     }
10734: 
10735:     sub get_host_ip {
10736: 	my ($lonid) = @_;
10737: 	if (exists($lonid_to_ip{$lonid})) {
10738: 	    return $lonid_to_ip{$lonid};
10739: 	}
10740: 	my $name=&hostname($lonid);
10741:    	my $ip = gethostbyname($name);
10742: 	return if (!$ip || length($ip) ne 4);
10743: 	$ip=inet_ntoa($ip);
10744: 	$name_to_ip{$name}   = $ip;
10745: 	$lonid_to_ip{$lonid} = $ip;
10746: 	return $ip;
10747:     }
10748:     
10749:     sub get_iphost {
10750: 	my ($ignore_cache) = @_;
10751: 
10752: 	if (!$ignore_cache) {
10753: 	    if (%iphost) {
10754: 		return %iphost;
10755: 	    }
10756: 	    my ($ip_info,$cached)=
10757: 		&Apache::lonnet::is_cached_new('iphost','iphost');
10758: 	    if ($cached) {
10759: 		%iphost      = %{$ip_info->[0]};
10760: 		%name_to_ip  = %{$ip_info->[1]};
10761: 		%lonid_to_ip = %{$ip_info->[2]};
10762: 		return %iphost;
10763: 	    }
10764: 	}
10765: 
10766: 	# get yesterday's info for fallback
10767: 	my %old_name_to_ip;
10768: 	my ($ip_info,$cached)=
10769: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
10770: 	if ($cached) {
10771: 	    %old_name_to_ip = %{$ip_info->[1]};
10772: 	}
10773: 
10774: 	my %name_to_host = &all_names();
10775: 	foreach my $name (keys(%name_to_host)) {
10776: 	    my $ip;
10777: 	    if (!exists($name_to_ip{$name})) {
10778: 		$ip = gethostbyname($name);
10779: 		if (!$ip || length($ip) ne 4) {
10780: 		    if (defined($old_name_to_ip{$name})) {
10781: 			$ip = $old_name_to_ip{$name};
10782: 			&logthis("Can't find $name defaulting to old $ip");
10783: 		    } else {
10784: 			&logthis("Name $name no IP found");
10785: 			next;
10786: 		    }
10787: 		} else {
10788: 		    $ip=inet_ntoa($ip);
10789: 		}
10790: 		$name_to_ip{$name} = $ip;
10791: 	    } else {
10792: 		$ip = $name_to_ip{$name};
10793: 	    }
10794: 	    foreach my $id (@{ $name_to_host{$name} }) {
10795: 		$lonid_to_ip{$id} = $ip;
10796: 	    }
10797: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
10798: 	}
10799: 	&Apache::lonnet::do_cache_new('iphost','iphost',
10800: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
10801: 				      48*60*60);
10802: 
10803: 	return %iphost;
10804:     }
10805: 
10806:     #
10807:     #  Given a DNS returns the loncapa host name for that DNS 
10808:     # 
10809:     sub host_from_dns {
10810:         my ($dns) = @_;
10811:         my @hosts;
10812:         my $ip;
10813: 
10814:         if (exists($name_to_ip{$dns})) {
10815:             $ip = $name_to_ip{$dns};
10816:         }
10817:         if (!$ip) {
10818:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
10819:             if (length($ip) == 4) { 
10820: 	        $ip   = &IO::Socket::inet_ntoa($ip);
10821:             }
10822:         }
10823:         if ($ip) {
10824: 	    @hosts = get_hosts_from_ip($ip);
10825: 	    return $hosts[0];
10826:         }
10827:         return undef;
10828:     }
10829: 
10830:     sub get_internet_names {
10831:         my ($lonid) = @_;
10832:         return if ($lonid eq '');
10833:         my ($idnref,$cached)=
10834:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
10835:         if ($cached) {
10836:             return $idnref;
10837:         }
10838:         my $ip = &get_host_ip($lonid);
10839:         my @hosts = &get_hosts_from_ip($ip);
10840:         my %iphost = &get_iphost();
10841:         my (@idns,%seen);
10842:         foreach my $id (@hosts) {
10843:             my $dom = &host_domain($id);
10844:             my $prim_id = &domain($dom,'primary');
10845:             my $prim_ip = &get_host_ip($prim_id);
10846:             next if ($seen{$prim_ip});
10847:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
10848:                 foreach my $id (@{$iphost{$prim_ip}}) {
10849:                     my $intdom = &internet_dom($id);
10850:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
10851:                         push(@idns,$intdom);
10852:                     }
10853:                 }
10854:             }
10855:             $seen{$prim_ip} = 1;
10856:         }
10857:         return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
10858:     }
10859: 
10860: }
10861: 
10862: sub all_loncaparevs {
10863:     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);
10864: }
10865: 
10866: BEGIN {
10867: 
10868: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
10869:     unless ($readit) {
10870: {
10871:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
10872:     %perlvar = (%perlvar,%{$configvars});
10873: }
10874: 
10875: 
10876: # ------------------------------------------------------ Read spare server file
10877: {
10878:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
10879: 
10880:     while (my $configline=<$config>) {
10881:        chomp($configline);
10882:        if ($configline) {
10883: 	   my ($host,$type) = split(':',$configline,2);
10884: 	   if (!defined($type) || $type eq '') { $type = 'default' };
10885: 	   push(@{ $spareid{$type} }, $host);
10886:        }
10887:     }
10888:     close($config);
10889: }
10890: # ------------------------------------------------------------ Read permissions
10891: {
10892:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
10893: 
10894:     while (my $configline=<$config>) {
10895: 	chomp($configline);
10896: 	if ($configline) {
10897: 	    my ($role,$perm)=split(/ /,$configline);
10898: 	    if ($perm ne '') { $pr{$role}=$perm; }
10899: 	}
10900:     }
10901:     close($config);
10902: }
10903: 
10904: # -------------------------------------------- Read plain texts for permissions
10905: {
10906:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
10907: 
10908:     while (my $configline=<$config>) {
10909: 	chomp($configline);
10910: 	if ($configline) {
10911: 	    my ($short,@plain)=split(/:/,$configline);
10912:             %{$prp{$short}} = ();
10913: 	    if (@plain > 0) {
10914:                 $prp{$short}{'std'} = $plain[0];
10915:                 for (my $i=1; $i<@plain; $i++) {
10916:                     $prp{$short}{'alt'.$i} = $plain[$i];  
10917:                 }
10918:             }
10919: 	}
10920:     }
10921:     close($config);
10922: }
10923: 
10924: # ---------------------------------------------------------- Read package table
10925: {
10926:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
10927: 
10928:     while (my $configline=<$config>) {
10929: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
10930: 	chomp($configline);
10931: 	my ($short,$plain)=split(/:/,$configline);
10932: 	my ($pack,$name)=split(/\&/,$short);
10933: 	if ($plain ne '') {
10934: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
10935: 	    $packagetab{$short}=$plain; 
10936: 	}
10937:     }
10938:     close($config);
10939: }
10940: 
10941: # ---------------------------------------------------------- Read loncaparev table
10942: {
10943:     if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
10944:         if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
10945:             while (my $configline=<$config>) {
10946:                 chomp($configline);
10947:                 my ($hostid,$loncaparev)=split(/:/,$configline);
10948:                 $loncaparevs{$hostid}=$loncaparev;
10949:             }
10950:             close($config);
10951:         }
10952:     }
10953: }
10954: 
10955: # ---------------------------------------------------------- Read serverhostID table
10956: {
10957:     if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
10958:         if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
10959:             while (my $configline=<$config>) {
10960:                 chomp($configline);
10961:                 my ($name,$id)=split(/:/,$configline);
10962:                 $serverhomeIDs{$name}=$id;
10963:             }
10964:             close($config);
10965:         }
10966:     }
10967: }
10968: 
10969: {
10970:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
10971:     if (-e $file) {
10972:         my $parser = HTML::LCParser->new($file);
10973:         while (my $token = $parser->get_token()) {
10974:             if ($token->[0] eq 'S') {
10975:                 my $item = $token->[1];
10976:                 my $name = $token->[2]{'name'};
10977:                 my $value = $token->[2]{'value'};
10978:                 if ($item ne '' && $name ne '' && $value ne '') {
10979:                     my $release = $parser->get_text();
10980:                     $release =~ s/(^\s*|\s*$ )//gx;
10981:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
10982:                 }
10983:             }
10984:         }
10985:     }
10986: }
10987: 
10988: # ---------------------------------------------------------- Read managers table
10989: {
10990:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
10991:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
10992:             while (my $configline=<$config>) {
10993:                 chomp($configline);
10994:                 next if ($configline =~ /^\#/);
10995:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
10996:                     $managerstab{$configline} = 1;
10997:                 }
10998:             }
10999:             close($config);
11000:         }
11001:     }
11002: }
11003: 
11004: # ------------- set up temporary directory
11005: {
11006:     $tmpdir = LONCAPA::tempdir();
11007: 
11008: }
11009: 
11010: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
11011: 				'compress_threshold'=> 20_000,
11012:  			        });
11013: 
11014: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
11015: $dumpcount=0;
11016: $locknum=0;
11017: 
11018: &logtouch();
11019: &logthis('<font color="yellow">INFO: Read configuration</font>');
11020: $readit=1;
11021:     {
11022: 	use integer;
11023: 	my $test=(2**32)+1;
11024: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
11025: 	&logthis(" Detected 64bit platform ($_64bit)");
11026:     }
11027: }
11028: }
11029: 
11030: 1;
11031: __END__
11032: 
11033: =pod
11034: 
11035: =head1 NAME
11036: 
11037: Apache::lonnet - Subroutines to ask questions about things in the network.
11038: 
11039: =head1 SYNOPSIS
11040: 
11041: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
11042: 
11043:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
11044: 
11045: Common parameters:
11046: 
11047: =over 4
11048: 
11049: =item *
11050: 
11051: $uname : an internal username (if $cname expecting a course Id specifically)
11052: 
11053: =item *
11054: 
11055: $udom : a domain (if $cdom expecting a course's domain specifically)
11056: 
11057: =item *
11058: 
11059: $symb : a resource instance identifier
11060: 
11061: =item *
11062: 
11063: $namespace : the name of a .db file that contains the data needed or
11064: being set.
11065: 
11066: =back
11067: 
11068: =head1 OVERVIEW
11069: 
11070: lonnet provides subroutines which interact with the
11071: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
11072: about classes, users, and resources.
11073: 
11074: For many of these objects you can also use this to store data about
11075: them or modify them in various ways.
11076: 
11077: =head2 Symbs
11078: 
11079: To identify a specific instance of a resource, LON-CAPA uses symbols
11080: or "symbs"X<symb>. These identifiers are built from the URL of the
11081: map, the resource number of the resource in the map, and the URL of
11082: the resource itself. The latter is somewhat redundant, but might help
11083: if maps change.
11084: 
11085: An example is
11086: 
11087:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
11088: 
11089: The respective map entry is
11090: 
11091:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
11092:   title="Problem 2">
11093:  </resource>
11094: 
11095: Symbs are used by the random number generator, as well as to store and
11096: restore data specific to a certain instance of for example a problem.
11097: 
11098: =head2 Storing And Retrieving Data
11099: 
11100: X<store()>X<cstore()>X<restore()>Three of the most important functions
11101: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
11102: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
11103: is is the non-critical message twin of cstore. These functions are for
11104: handlers to store a perl hash to a user's permanent data space in an
11105: easy manner, and to retrieve it again on another call. It is expected
11106: that a handler would use this once at the beginning to retrieve data,
11107: and then again once at the end to send only the new data back.
11108: 
11109: The data is stored in the user's data directory on the user's
11110: homeserver under the ID of the course.
11111: 
11112: The hash that is returned by restore will have all of the previous
11113: value for all of the elements of the hash.
11114: 
11115: Example:
11116: 
11117:  #creating a hash
11118:  my %hash;
11119:  $hash{'foo'}='bar';
11120: 
11121:  #storing it
11122:  &Apache::lonnet::cstore(\%hash);
11123: 
11124:  #changing a value
11125:  $hash{'foo'}='notbar';
11126: 
11127:  #adding a new value
11128:  $hash{'bar'}='foo';
11129:  &Apache::lonnet::cstore(\%hash);
11130: 
11131:  #retrieving the hash
11132:  my %history=&Apache::lonnet::restore();
11133: 
11134:  #print the hash
11135:  foreach my $key (sort(keys(%history))) {
11136:    print("\%history{$key} = $history{$key}");
11137:  }
11138: 
11139: Will print out:
11140: 
11141:  %history{1:foo} = bar
11142:  %history{1:keys} = foo:timestamp
11143:  %history{1:timestamp} = 990455579
11144:  %history{2:bar} = foo
11145:  %history{2:foo} = notbar
11146:  %history{2:keys} = foo:bar:timestamp
11147:  %history{2:timestamp} = 990455580
11148:  %history{bar} = foo
11149:  %history{foo} = notbar
11150:  %history{timestamp} = 990455580
11151:  %history{version} = 2
11152: 
11153: Note that the special hash entries C<keys>, C<version> and
11154: C<timestamp> were added to the hash. C<version> will be equal to the
11155: total number of versions of the data that have been stored. The
11156: C<timestamp> attribute will be the UNIX time the hash was
11157: stored. C<keys> is available in every historical section to list which
11158: keys were added or changed at a specific historical revision of a
11159: hash.
11160: 
11161: B<Warning>: do not store the hash that restore returns directly. This
11162: will cause a mess since it will restore the historical keys as if the
11163: were new keys. I.E. 1:foo will become 1:1:foo etc.
11164: 
11165: Calling convention:
11166: 
11167:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
11168:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
11169: 
11170: For more detailed information, see lonnet specific documentation.
11171: 
11172: =head1 RETURN MESSAGES
11173: 
11174: =over 4
11175: 
11176: =item * B<con_lost>: unable to contact remote host
11177: 
11178: =item * B<con_delayed>: unable to contact remote host, message will be delivered
11179: when the connection is brought back up
11180: 
11181: =item * B<con_failed>: unable to contact remote host and unable to save message
11182: for later delivery
11183: 
11184: =item * B<error:>: an error a occurred, a description of the error follows the :
11185: 
11186: =item * B<no_such_host>: unable to fund a host associated with the user/domain
11187: that was requested
11188: 
11189: =back
11190: 
11191: =head1 PUBLIC SUBROUTINES
11192: 
11193: =head2 Session Environment Functions
11194: 
11195: =over 4
11196: 
11197: =item * 
11198: X<appenv()>
11199: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
11200: the user envirnoment file, and will be restored for each access this
11201: user makes during this session, also modifies the %env for the current
11202: process. Optional rolesarrayref - if defined contains a reference to an array
11203: of roles which are exempt from the restriction on modifying user.role entries 
11204: in the user's environment.db and in %env.    
11205: 
11206: =item *
11207: X<delenv()>
11208: B<delenv($delthis,$regexp)>: removes all items from the session
11209: environment file that begin with $delthis. If the 
11210: optional second arg - $regexp - is true, $delthis is treated as a 
11211: regular expression, otherwise \Q$delthis\E is used. 
11212: The values are also deleted from the current processes %env.
11213: 
11214: =item * get_env_multiple($name) 
11215: 
11216: gets $name from the %env hash, it seemlessly handles the cases where multiple
11217: values may be defined and end up as an array ref.
11218: 
11219: returns an array of values
11220: 
11221: =back
11222: 
11223: =head2 User Information
11224: 
11225: =over 4
11226: 
11227: =item *
11228: X<queryauthenticate()>
11229: B<queryauthenticate($uname,$udom)>: try to determine user's current 
11230: authentication scheme
11231: 
11232: =item *
11233: X<authenticate()>
11234: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
11235: authenticate user from domain's lib servers (first use the current
11236: one). C<$upass> should be the users password.
11237: $checkdefauth is optional (value is 1 if a check should be made to
11238:    authenticate user using default authentication method, and allow
11239:    account creation if username does not have account in the domain).
11240: $clientcancheckhost is optional (value is 1 if checking whether the
11241:    server can host will occur on the client side in lonauth.pm).   
11242: 
11243: =item *
11244: X<homeserver()>
11245: B<homeserver($uname,$udom)>: find the server which has
11246: the user's directory and files (there must be only one), this caches
11247: the answer, and also caches if there is a borken connection.
11248: 
11249: =item *
11250: X<idget()>
11251: B<idget($udom,@ids)>: find the usernames behind a list of IDs
11252: (IDs are a unique resource in a domain, there must be only 1 ID per
11253: username, and only 1 username per ID in a specific domain) (returns
11254: hash: id=>name,id=>name)
11255: 
11256: =item *
11257: X<idrget()>
11258: B<idrget($udom,@unames)>: find the IDs behind a list of
11259: usernames (returns hash: name=>id,name=>id)
11260: 
11261: =item *
11262: X<idput()>
11263: B<idput($udom,%ids)>: store away a list of names and associated IDs
11264: 
11265: =item *
11266: X<rolesinit()>
11267: B<rolesinit($udom,$username,$authhost)>: get user privileges
11268: 
11269: =item *
11270: X<getsection()>
11271: B<getsection($udom,$uname,$cname)>: finds the section of student in the
11272: course $cname, return section name/number or '' for "not in course"
11273: and '-1' for "no section"
11274: 
11275: =item *
11276: X<userenvironment()>
11277: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
11278: passed in @what from the requested user's environment, returns a hash
11279: 
11280: =item * 
11281: X<userlog_query()>
11282: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
11283: activity.log file. %filters defines filters applied when parsing the
11284: log file. These can be start or end timestamps, or the type of action
11285: - log to look for Login or Logout events, check for Checkin or
11286: Checkout, role for role selection. The response is in the form
11287: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
11288: escaped strings of the action recorded in the activity.log file.
11289: 
11290: =back
11291: 
11292: =head2 User Roles
11293: 
11294: =over 4
11295: 
11296: =item *
11297: 
11298: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
11299:  F: full access
11300:  U,I,K: authentication modes (cxx only)
11301:  '': forbidden
11302:  1: user needs to choose course
11303:  2: browse allowed
11304:  A: passphrase authentication needed
11305: 
11306: =item *
11307: 
11308: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
11309: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
11310: and course level
11311: 
11312: =item *
11313: 
11314: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
11315: (rolesplain.tab); plain text explanation of a user role term.
11316: $type is Course (default) or Community.
11317: If $forcedefault evaluates to true, text returned will be default 
11318: text for $type. Otherwise, if this is a course, the text returned 
11319: will be a custom name for the role (if defined in the course's 
11320: environment).  If no custom name is defined the default is returned.
11321:    
11322: =item *
11323: 
11324: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
11325: All arguments are optional. Returns a hash of a roles, either for
11326: co-author/assistant author roles for a user's Construction Space
11327: (default), or if $context is 'userroles', roles for the user himself,
11328: In the hash, keys are set to colon-separated $uname,$udom,$role, and
11329: (optionally) if $withsec is true, a fourth colon-separated item - $section.
11330: For each key, value is set to colon-separated start and end times for
11331: the role.  If no username and domain are specified, will default to
11332: current user/domain. Types, roles, and roledoms are references to arrays
11333: of role statuses (active, future or previous), roles 
11334: (e.g., cc,in, st etc.) and domains of the roles which can be used
11335: to restrict the list of roles reported. If no array ref is 
11336: provided for types, will default to return only active roles.
11337: 
11338: =back
11339: 
11340: =head2 User Modification
11341: 
11342: =over 4
11343: 
11344: =item *
11345: 
11346: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
11347: user for the level given by URL.  Optional start and end dates (leave empty
11348: string or zero for "no date")
11349: 
11350: =item *
11351: 
11352: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
11353: change a users, password, possible return values are: ok,
11354: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
11355: refused
11356: 
11357: =item *
11358: 
11359: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
11360: 
11361: =item *
11362: 
11363: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
11364:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
11365: 
11366: will update user information (firstname,middlename,lastname,generation,
11367: permanentemail), and if forceid is true, student/employee ID also.
11368: A user's institutional affiliation(s) can also be updated.
11369: User information fields will not be overwritten with empty entries 
11370: unless the field is included in the $candelete array reference.
11371: This array is included when a single user is modified via "Manage Users",
11372: or when Autoupdate.pl is run by cron in a domain.
11373: 
11374: =item *
11375: 
11376: modifystudent
11377: 
11378: modify a student's enrollment and identification information.
11379: The course id is resolved based on the current users environment.  
11380: This means the envoking user must be a course coordinator or otherwise
11381: associated with a course.
11382: 
11383: This call is essentially a wrapper for lonnet::modifyuser and
11384: lonnet::modify_student_enrollment
11385: 
11386: Inputs: 
11387: 
11388: =over 4
11389: 
11390: =item B<$udom> Student's loncapa domain
11391: 
11392: =item B<$uname> Student's loncapa login name
11393: 
11394: =item B<$uid> Student/Employee ID
11395: 
11396: =item B<$umode> Student's authentication mode
11397: 
11398: =item B<$upass> Student's password
11399: 
11400: =item B<$first> Student's first name
11401: 
11402: =item B<$middle> Student's middle name
11403: 
11404: =item B<$last> Student's last name
11405: 
11406: =item B<$gene> Student's generation
11407: 
11408: =item B<$usec> Student's section in course
11409: 
11410: =item B<$end> Unix time of the roles expiration
11411: 
11412: =item B<$start> Unix time of the roles start date
11413: 
11414: =item B<$forceid> If defined, allow $uid to be changed
11415: 
11416: =item B<$desiredhome> server to use as home server for student
11417: 
11418: =item B<$email> Student's permanent e-mail address
11419: 
11420: =item B<$type> Type of enrollment (auto or manual)
11421: 
11422: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
11423: 
11424: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
11425: 
11426: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
11427: 
11428: =item B<$context> role change context (shown in User Management Logs display in a course)
11429: 
11430: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
11431: 
11432: =back
11433: 
11434: =item *
11435: 
11436: modify_student_enrollment
11437: 
11438: Change a students enrollment status in a class.  The environment variable
11439: 'role.request.course' must be defined for this function to proceed.
11440: 
11441: Inputs:
11442: 
11443: =over 4
11444: 
11445: =item $udom, students domain
11446: 
11447: =item $uname, students name
11448: 
11449: =item $uid, students user id
11450: 
11451: =item $first, students first name
11452: 
11453: =item $middle
11454: 
11455: =item $last
11456: 
11457: =item $gene
11458: 
11459: =item $usec
11460: 
11461: =item $end
11462: 
11463: =item $start
11464: 
11465: =item $type
11466: 
11467: =item $locktype
11468: 
11469: =item $cid
11470: 
11471: =item $selfenroll
11472: 
11473: =item $context
11474: 
11475: =back
11476: 
11477: 
11478: =item *
11479: 
11480: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
11481: custom role; give a custom role to a user for the level given by URL.  Specify
11482: name and domain of role author, and role name
11483: 
11484: =item *
11485: 
11486: revokerole($udom,$uname,$url,$role) : revoke a role for url
11487: 
11488: =item *
11489: 
11490: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
11491: 
11492: =back
11493: 
11494: =head2 Course Infomation
11495: 
11496: =over 4
11497: 
11498: =item *
11499: 
11500: coursedescription($courseid,$options) : returns a hash of information about the
11501: specified course id, including all environment settings for the
11502: course, the description of the course will be in the hash under the
11503: key 'description'
11504: 
11505: $options is an optional parameter that if supplied is a hash reference that controls
11506: what how this function works.  It has the following key/values:
11507: 
11508: =over 4
11509: 
11510: =item freshen_cache
11511: 
11512: If defined, and the environment cache for the course is valid, it is 
11513: returned in the returned hash.
11514: 
11515: =item one_time
11516: 
11517: If defined, the last cache time is set to _now_
11518: 
11519: =item user
11520: 
11521: If defined, the supplied username is used instead of the current user.
11522: 
11523: 
11524: =back
11525: 
11526: =item *
11527: 
11528: resdata($name,$domain,$type,@which) : request for current parameter
11529: setting for a specific $type, where $type is either 'course' or 'user',
11530: @what should be a list of parameters to ask about. This routine caches
11531: answers for 5 minutes.
11532: 
11533: =item *
11534: 
11535: get_courseresdata($courseid, $domain) : dump the entire course resource
11536: data base, returning a hash that is keyed by the resource name and has
11537: values that are the resource value.  I believe that the timestamps and
11538: versions are also returned.
11539: 
11540: 
11541: =back
11542: 
11543: =head2 Course Modification
11544: 
11545: =over 4
11546: 
11547: =item *
11548: 
11549: writecoursepref($courseid,%prefs) : write preferences (environment
11550: database) for a course
11551: 
11552: =item *
11553: 
11554: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
11555: 
11556: =item *
11557: 
11558: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
11559: 
11560: =back
11561: 
11562: =head2 Resource Subroutines
11563: 
11564: =over 4
11565: 
11566: =item *
11567: 
11568: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
11569: 
11570: =item *
11571: 
11572: repcopy($filename) : subscribes to the requested file, and attempts to
11573: replicate from the owning library server, Might return
11574: 'unavailable', 'not_found', 'forbidden', 'ok', or
11575: 'bad_request', also attempts to grab the metadata for the
11576: resource. Expects the local filesystem pathname
11577: (/home/httpd/html/res/....)
11578: 
11579: =back
11580: 
11581: =head2 Resource Information
11582: 
11583: =over 4
11584: 
11585: =item *
11586: 
11587: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
11588: a vairety of different possible values, $varname should be a request
11589: string, and the other parameters can be used to specify who and what
11590: one is asking about.
11591: 
11592: Possible values for $varname are environment.lastname (or other item
11593: from the envirnment hash), user.name (or someother aspect about the
11594: user), resource.0.maxtries (or some other part and parameter of a
11595: resource)
11596: 
11597: =item *
11598: 
11599: directcondval($number) : get current value of a condition; reads from a state
11600: string
11601: 
11602: =item *
11603: 
11604: condval($condidx) : value of condition index based on state
11605: 
11606: =item *
11607: 
11608: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
11609: resource's metadata, $what should be either a specific key, or either
11610: 'keys' (to get a list of possible keys) or 'packages' to get a list of
11611: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
11612: 
11613: this function automatically caches all requests
11614: 
11615: =item *
11616: 
11617: metadata_query($query,$custom,$customshow) : make a metadata query against the
11618: network of library servers; returns file handle of where SQL and regex results
11619: will be stored for query
11620: 
11621: =item *
11622: 
11623: symbread($filename) : return symbolic list entry (filename argument optional);
11624: returns the data handle
11625: 
11626: =item *
11627: 
11628: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
11629: a possible symb for the URL in $thisfn, and if is an encryypted
11630: resource that the user accessed using /enc/ returns a 1 on success, 0
11631: on failure, user must be in a course, as it assumes the existance of
11632: the course initial hash, and uses $env('request.course.id'}
11633: 
11634: 
11635: =item *
11636: 
11637: symbclean($symb) : removes versions numbers from a symb, returns the
11638: cleaned symb
11639: 
11640: =item *
11641: 
11642: is_on_map($uri) : checks if the $uri is somewhere on the current
11643: course map, user must be in a course for it to work.
11644: 
11645: =item *
11646: 
11647: numval($salt) : return random seed value (addend for rndseed)
11648: 
11649: =item *
11650: 
11651: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
11652: a random seed, all arguments are optional, if they aren't sent it uses the
11653: environment to derive them. Note: if symb isn't sent and it can't get one
11654: from &symbread it will use the current time as its return value
11655: 
11656: =item *
11657: 
11658: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
11659: unfakeable, receipt
11660: 
11661: =item *
11662: 
11663: receipt() : API to ireceipt working off of env values; given out to users
11664: 
11665: =item *
11666: 
11667: countacc($url) : count the number of accesses to a given URL
11668: 
11669: =item *
11670: 
11671: 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
11672: 
11673: =item *
11674: 
11675: 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)
11676: 
11677: =item *
11678: 
11679: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
11680: 
11681: =item *
11682: 
11683: devalidate($symb) : devalidate temporary spreadsheet calculations,
11684: forcing spreadsheet to reevaluate the resource scores next time.
11685: 
11686: =back
11687: 
11688: =head2 Storing/Retreiving Data
11689: 
11690: =over 4
11691: 
11692: =item *
11693: 
11694: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
11695: for this url; hashref needs to be given and should be a \%hashname; the
11696: remaining args aren't required and if they aren't passed or are '' they will
11697: be derived from the env
11698: 
11699: =item *
11700: 
11701: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
11702: uses critical subroutine
11703: 
11704: =item *
11705: 
11706: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
11707: all args are optional
11708: 
11709: =item *
11710: 
11711: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
11712: dumps the complete (or key matching regexp) namespace into a hash
11713: ($udom, $uname, $regexp, $range are optional) for a namespace that is
11714: normally &store()ed into
11715: 
11716: $range should be either an integer '100' (give me the first 100
11717:                                            matching records)
11718:               or be  two integers sperated by a - with no spaces
11719:                  '30-50' (give me the 30th through the 50th matching
11720:                           records)
11721: 
11722: 
11723: =item *
11724: 
11725: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
11726: replaces a &store() version of data with a replacement set of data
11727: for a particular resource in a namespace passed in the $storehash hash 
11728: reference
11729: 
11730: =item *
11731: 
11732: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
11733: works very similar to store/cstore, but all data is stored in a
11734: temporary location and can be reset using tmpreset, $storehash should
11735: be a hash reference, returns nothing on success
11736: 
11737: =item *
11738: 
11739: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
11740: similar to restore, but all data is stored in a temporary location and
11741: can be reset using tmpreset. Returns a hash of values on success,
11742: error string otherwise.
11743: 
11744: =item *
11745: 
11746: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
11747: deltes all keys for $symb form the temporary storage hash.
11748: 
11749: =item *
11750: 
11751: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
11752: reference filled in from namesp ($udom and $uname are optional)
11753: 
11754: =item *
11755: 
11756: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
11757: namesp ($udom and $uname are optional)
11758: 
11759: =item *
11760: 
11761: dump($namespace,$udom,$uname,$regexp,$range) : 
11762: dumps the complete (or key matching regexp) namespace into a hash
11763: ($udom, $uname, $regexp, $range are optional)
11764: 
11765: $range should be either an integer '100' (give me the first 100
11766:                                            matching records)
11767:               or be  two integers sperated by a - with no spaces
11768:                  '30-50' (give me the 30th through the 50th matching
11769:                           records)
11770: =item *
11771: 
11772: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
11773: $store can be a scalar, an array reference, or if the amount to be 
11774: incremented is > 1, a hash reference.
11775: 
11776: ($udom and $uname are optional)
11777: 
11778: =item *
11779: 
11780: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
11781: ($udom and $uname are optional)
11782: 
11783: =item *
11784: 
11785: cput($namespace,$storehash,$udom,$uname) : critical put
11786: ($udom and $uname are optional)
11787: 
11788: =item *
11789: 
11790: newput($namespace,$storehash,$udom,$uname) :
11791: 
11792: Attempts to store the items in the $storehash, but only if they don't
11793: currently exist, if this succeeds you can be certain that you have 
11794: successfully created a new key value pair in the $namespace db.
11795: 
11796: 
11797: Args:
11798:  $namespace: name of database to store values to
11799:  $storehash: hashref to store to the db
11800:  $udom: (optional) domain of user containing the db
11801:  $uname: (optional) name of user caontaining the db
11802: 
11803: Returns:
11804:  'ok' -> succeeded in storing all keys of $storehash
11805:  'key_exists: <key>' -> failed to anything out of $storehash, as at
11806:                         least <key> already existed in the db (other
11807:                         requested keys may also already exist)
11808:  'error: <msg>' -> unable to tie the DB or other error occurred
11809:  'con_lost' -> unable to contact request server
11810:  'refused' -> action was not allowed by remote machine
11811: 
11812: 
11813: =item *
11814: 
11815: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
11816: reference filled in from namesp (encrypts the return communication)
11817: ($udom and $uname are optional)
11818: 
11819: =item *
11820: 
11821: log($udom,$name,$home,$message) : write to permanent log for user; use
11822: critical subroutine
11823: 
11824: =item *
11825: 
11826: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
11827: array reference filled in from namespace found in domain level on either
11828: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
11829: 
11830: =item *
11831: 
11832: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
11833: domain level either on specified domain server ($uhome) or primary domain 
11834: server ($udom and $uhome are optional)
11835: 
11836: =item * 
11837: 
11838: get_domain_defaults($target_domain) : returns hash with defaults for
11839: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
11840: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
11841: or localauth), initial password or a kerberos realm, language (e.g., en-us).
11842: Values are retrieved from cache (if current), or from domain's configuration.db
11843: (if available), or lastly from values in lonTabs/dns_domain,tab, 
11844: or lonTabs/domain.tab. 
11845: 
11846: %domdefaults = &get_auth_defaults($target_domain);
11847: 
11848: =back
11849: 
11850: =head2 Network Status Functions
11851: 
11852: =over 4
11853: 
11854: =item *
11855: 
11856: dirlist() : return directory list based on URI (first arg).
11857: 
11858: Inputs: 1 required, 5 optional.
11859: 
11860: =over
11861: 
11862: =item 
11863: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
11864: 
11865: =item
11866: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
11867: 
11868: =item
11869: $username -  username of user/course to be listed. Extracted from $uri if absent. 
11870: 
11871: =item
11872: $getpropath - boolean: 1 if prepend path using &propath(). 
11873: 
11874: =item
11875: $getuserdir - boolean: 1 if prepend path for "userfiles".
11876: 
11877: =item 
11878: $alternateRoot - path to prepend in place of path from $uri.
11879: 
11880: =back
11881: 
11882: Returns: Array of up to two items.
11883: 
11884: =over
11885: 
11886: a reference to an array of files/subdirectories
11887: 
11888: =over
11889: 
11890: Each element in the array of files/subdirectories is a & separated list of
11891: item name and the result of running stat on the item.  If dirlist was requested
11892: for a file instead of a directory, the item name will be ''. For a directory 
11893: listing, if the item is a metadata file, the element will end &N&M 
11894: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
11895: default copyright set (1).  
11896: 
11897: =back
11898: 
11899: a scalar containing error condition (if encountered).
11900: 
11901: =over
11902: 
11903: =item 
11904: no_host (no homeserver identified for $username:$domain).
11905: 
11906: =item 
11907: no_such_host (server contacted for listing not identified as valid host).
11908: 
11909: =item 
11910: con_lost (connection to remote server failed).
11911: 
11912: =item 
11913: refused (invalid $username:$domain received on lond side).
11914: 
11915: =item 
11916: no_such_dir (directory at specified path on lond side does not exist). 
11917: 
11918: =item 
11919: empty (directory at specified path on lond side is empty).
11920: 
11921: =over
11922: 
11923: This is currently not encountered because the &ls3, &ls2, 
11924: &ls (_handler) routines on the lond side do not filter out
11925: . and .. from a directory listing. 
11926: 
11927: =back
11928: 
11929: =back
11930: 
11931: =back
11932: 
11933: =item *
11934: 
11935: spareserver() : find server with least workload from spare.tab
11936: 
11937: 
11938: =item *
11939: 
11940: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
11941: if there is no corresponding loncapa host.
11942: 
11943: =back
11944: 
11945: 
11946: =head2 Apache Request
11947: 
11948: =over 4
11949: 
11950: =item *
11951: 
11952: ssi($url,%hash) : server side include, does a complete request cycle on url to
11953: localhost, posts hash
11954: 
11955: =back
11956: 
11957: =head2 Data to String to Data
11958: 
11959: =over 4
11960: 
11961: =item *
11962: 
11963: hash2str(%hash) : convert a hash into a string complete with escaping and '='
11964: and '&' separators, supports elements that are arrayrefs and hashrefs
11965: 
11966: =item *
11967: 
11968: hashref2str($hashref) : convert a hashref into a string complete with
11969: escaping and '=' and '&' separators, supports elements that are
11970: arrayrefs and hashrefs
11971: 
11972: =item *
11973: 
11974: arrayref2str($arrayref) : convert an arrayref into a string complete
11975: with escaping and '&' separators, supports elements that are arrayrefs
11976: and hashrefs
11977: 
11978: =item *
11979: 
11980: str2hash($string) : convert string to hash using unescaping and
11981: splitting on '=' and '&', supports elements that are arrayrefs and
11982: hashrefs
11983: 
11984: =item *
11985: 
11986: str2array($string) : convert string to hash using unescaping and
11987: splitting on '&', supports elements that are arrayrefs and hashrefs
11988: 
11989: =back
11990: 
11991: =head2 Logging Routines
11992: 
11993: 
11994: These routines allow one to make log messages in the lonnet.log and
11995: lonnet.perm logfiles.
11996: 
11997: =over 4
11998: 
11999: =item *
12000: 
12001: logtouch() : make sure the logfile, lonnet.log, exists
12002: 
12003: =item *
12004: 
12005: logthis() : append message to the normal lonnet.log file, it gets
12006: preiodically rolled over and deleted.
12007: 
12008: =item *
12009: 
12010: logperm() : append a permanent message to lonnet.perm.log, this log
12011: file never gets deleted by any automated portion of the system, only
12012: messages of critical importance should go in here.
12013: 
12014: 
12015: =back
12016: 
12017: =head2 General File Helper Routines
12018: 
12019: =over 4
12020: 
12021: =item *
12022: 
12023: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
12024: (a) files in /uploaded
12025:   (i) If a local copy of the file exists - 
12026:       compares modification date of local copy with last-modified date for 
12027:       definitive version stored on home server for course. If local copy is 
12028:       stale, requests a new version from the home server and stores it. 
12029:       If the original has been removed from the home server, then local copy 
12030:       is unlinked.
12031:   (ii) If local copy does not exist -
12032:       requests the file from the home server and stores it. 
12033:   
12034:   If $caller is 'uploadrep':  
12035:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
12036:     for request for files originally uploaded via DOCS. 
12037:      - returns 'ok' if fresh local copy now available, -1 otherwise.
12038:   
12039:   Otherwise:
12040:      This indicates a call from the content generation phase of the request.
12041:      -  returns the entire contents of the file or -1.
12042:      
12043: (b) files in /res
12044:    - returns the entire contents of a file or -1; 
12045:    it properly subscribes to and replicates the file if neccessary.
12046: 
12047: 
12048: =item *
12049: 
12050: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
12051:                   reference
12052: 
12053: returns either a stat() list of data about the file or an empty list
12054: if the file doesn't exist or couldn't find out about it (connection
12055: problems or user unknown)
12056: 
12057: =item *
12058: 
12059: filelocation($dir,$file) : returns file system location of a file
12060: based on URI; meant to be "fairly clean" absolute reference, $dir is a
12061: directory that relative $file lookups are to looked in ($dir of /a/dir
12062: and a file of ../bob will become /a/bob)
12063: 
12064: =item *
12065: 
12066: hreflocation($dir,$file) : returns file system location or a URL; same as
12067: filelocation except for hrefs
12068: 
12069: =item *
12070: 
12071: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
12072: 
12073: =back
12074: 
12075: =head2 Usererfile file routines (/uploaded*)
12076: 
12077: =over 4
12078: 
12079: =item *
12080: 
12081: userfileupload(): main rotine for putting a file in a user or course's
12082:                   filespace, arguments are,
12083: 
12084:  formname - required - this is the name of the element in $env where the
12085:            filename, and the contents of the file to create/modifed exist
12086:            the filename is in $env{'form.'.$formname.'.filename'} and the
12087:            contents of the file is located in $env{'form.'.$formname}
12088:  context - if coursedoc, store the file in the course of the active role
12089:              of the current user; 
12090:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
12091:            if 'canceloverwrite': delete file in tmp/overwrites directory
12092:  subdir - required - subdirectory to put the file in under ../userfiles/
12093:          if undefined, it will be placed in "unknown"
12094: 
12095:  (This routine calls clean_filename() to remove any dangerous
12096:  characters from the filename, and then calls finuserfileupload() to
12097:  complete the transaction)
12098: 
12099:  returns either the url of the uploaded file (/uploaded/....) if successful
12100:  and /adm/notfound.html if unsuccessful
12101: 
12102: =item *
12103: 
12104: clean_filename(): routine for cleaing a filename up for storage in
12105:                  userfile space, argument is:
12106: 
12107:  filename - proposed filename
12108: 
12109: returns: the new clean filename
12110: 
12111: =item *
12112: 
12113: finishuserfileupload(): routine that creates and sends the file to
12114: userspace, probably shouldn't be called directly
12115: 
12116:   docuname: username or courseid of destination for the file
12117:   docudom: domain of user/course of destination for the file
12118:   formname: same as for userfileupload()
12119:   fname: filename (including subdirectories) for the file
12120:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
12121:   allfiles: reference to hash used to store objects found by parser
12122:   codebase: reference to hash used for codebases of java objects found by parser
12123:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
12124:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
12125:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
12126:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
12127:   context: if 'overwrite', will move the uploaded file from its temporary location to
12128:             userfiles to facilitate overwriting a previously uploaded file with same name.
12129:   mimetype: reference to scalar to accommodate mime type determined
12130:             from File::MMagic if $parser = parse.
12131: 
12132:  returns either the url of the uploaded file (/uploaded/....) if successful
12133:  and /adm/notfound.html if unsuccessful (or an error message if context 
12134:  was 'overwrite').
12135:  
12136: 
12137: =item *
12138: 
12139: renameuserfile(): renames an existing userfile to a new name
12140: 
12141:   Args:
12142:    docuname: username or courseid of destination for the file
12143:    docudom: domain of user/course of destination for the file
12144:    old: current file name (including any subdirs under userfiles)
12145:    new: desired file name (including any subdirs under userfiles)
12146: 
12147: =item *
12148: 
12149: mkdiruserfile(): creates a directory is a userfiles dir
12150: 
12151:   Args:
12152:    docuname: username or courseid of destination for the file
12153:    docudom: domain of user/course of destination for the file
12154:    dir: dir to create (including any subdirs under userfiles)
12155: 
12156: =item *
12157: 
12158: removeuserfile(): removes a file that exists in userfiles
12159: 
12160:   Args:
12161:    docuname: username or courseid of destination for the file
12162:    docudom: domain of user/course of destination for the file
12163:    fname: filname to delete (including any subdirs under userfiles)
12164: 
12165: =item *
12166: 
12167: removeuploadedurl(): convience function for removeuserfile()
12168: 
12169:   Args:
12170:    url:  a full /uploaded/... url to delete
12171: 
12172: =item * 
12173: 
12174: get_portfile_permissions():
12175:   Args:
12176:     domain: domain of user or course contain the portfolio files
12177:     user: name of user or num of course contain the portfolio files
12178:   Returns:
12179:     hashref of a dump of the proper file_permissions.db
12180:    
12181: 
12182: =item * 
12183: 
12184: get_access_controls():
12185: 
12186: Args:
12187:   current_permissions: the hash ref returned from get_portfile_permissions()
12188:   group: (optional) the group you want the files associated with
12189:   file: (optional) the file you want access info on
12190: 
12191: Returns:
12192:     a hash (keys are file names) of hashes containing
12193:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
12194:         values are XML containing access control settings (see below) 
12195: 
12196: Internal notes:
12197: 
12198:  access controls are stored in file_permissions.db as key=value pairs.
12199:     key -> path to file/file_name\0uniqueID:scope_end_start
12200:         where scope -> public,guest,course,group,domains or users.
12201:               end -> UNIX time for end of access (0 -> no end date)
12202:               start -> UNIX time for start of access
12203: 
12204:     value -> XML description of access control
12205:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
12206:             <start></start>
12207:             <end></end>
12208: 
12209:             <password></password>  for scope type = guest
12210: 
12211:             <domain></domain>     for scope type = course or group
12212:             <number></number>
12213:             <roles id="">
12214:              <role></role>
12215:              <access></access>
12216:              <section></section>
12217:              <group></group>
12218:             </roles>
12219: 
12220:             <dom></dom>         for scope type = domains
12221: 
12222:             <users>             for scope type = users
12223:              <user>
12224:               <uname></uname>
12225:               <udom></udom>
12226:              </user>
12227:             </users>
12228:            </scope> 
12229:               
12230:  Access data is also aggregated for each file in an additional key=value pair:
12231:  key -> path to file/file_name\0accesscontrol 
12232:  value -> reference to hash
12233:           hash contains key = value pairs
12234:           where key = uniqueID:scope_end_start
12235:                 value = UNIX time record was last updated
12236: 
12237:           Used to improve speed of look-ups of access controls for each file.  
12238:  
12239:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
12240: 
12241: modify_access_controls():
12242: 
12243: Modifies access controls for a portfolio file
12244: Args
12245: 1. file name
12246: 2. reference to hash of required changes,
12247: 3. domain
12248: 4. username
12249:   where domain,username are the domain of the portfolio owner 
12250:   (either a user or a course) 
12251: 
12252: Returns:
12253: 1. result of additions or updates ('ok' or 'error', with error message). 
12254: 2. result of deletions ('ok' or 'error', with error message).
12255: 3. reference to hash of any new or updated access controls.
12256: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
12257:    key = integer (inbound ID)
12258:    value = uniqueID  
12259: 
12260: =back
12261: 
12262: =head2 HTTP Helper Routines
12263: 
12264: =over 4
12265: 
12266: =item *
12267: 
12268: escape() : unpack non-word characters into CGI-compatible hex codes
12269: 
12270: =item *
12271: 
12272: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
12273: 
12274: =back
12275: 
12276: =head1 PRIVATE SUBROUTINES
12277: 
12278: =head2 Underlying communication routines (Shouldn't call)
12279: 
12280: =over 4
12281: 
12282: =item *
12283: 
12284: subreply() : tries to pass a message to lonc, returns con_lost if incapable
12285: 
12286: =item *
12287: 
12288: reply() : uses subreply to send a message to remote machine, logs all failures
12289: 
12290: =item *
12291: 
12292: critical() : passes a critical message to another server; if cannot
12293: get through then place message in connection buffer directory and
12294: returns con_delayed, if incapable of saving message, returns
12295: con_failed
12296: 
12297: =item *
12298: 
12299: reconlonc() : tries to reconnect lonc client processes.
12300: 
12301: =back
12302: 
12303: =head2 Resource Access Logging
12304: 
12305: =over 4
12306: 
12307: =item *
12308: 
12309: flushcourselogs() : flush (save) buffer logs and access logs
12310: 
12311: =item *
12312: 
12313: courselog($what) : save message for course in hash
12314: 
12315: =item *
12316: 
12317: courseacclog($what) : save message for course using &courselog().  Perform
12318: special processing for specific resource types (problems, exams, quizzes, etc).
12319: 
12320: =item *
12321: 
12322: goodbye() : flush course logs and log shutting down; it is called in srm.conf
12323: as a PerlChildExitHandler
12324: 
12325: =back
12326: 
12327: =head2 Other
12328: 
12329: =over 4
12330: 
12331: =item *
12332: 
12333: symblist($mapname,%newhash) : update symbolic storage links
12334: 
12335: =back
12336: 
12337: =cut
12338: 

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