File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1140: download - view: text, annotated - select for diffs
Mon Oct 24 12:05:58 2011 UTC (12 years, 8 months ago) by www
Branches: MAIN
CVS tags: HEAD
Bug #1320

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1140 2011/10/24 12:05:58 www Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: ###
   29: 
   30: =pod
   31: 
   32: =head1 NAME
   33: 
   34: Apache::lonnet.pm
   35: 
   36: =head1 SYNOPSIS
   37: 
   38: This file is an interface to the lonc processes of
   39: the LON-CAPA network as well as set of elaborated functions for handling information
   40: necessary for navigating through a given cluster of LON-CAPA machines within a
   41: domain. There are over 40 specialized functions in this module which handle the
   42: reading and transmission of metadata, user information (ids, names, environments, roles,
   43: logs), file information (storage, reading, directories, extensions, replication, embedded
   44: styles and descriptors), educational resources (course descriptions, section names and
   45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
   46: and from more descriptive phrases or explanations.
   47: 
   48: This is part of the LearningOnline Network with CAPA project
   49: described at http://www.lon-capa.org.
   50: 
   51: =head1 Package Variables
   52: 
   53: These are largely undocumented, so if you decipher one please note it here.
   54: 
   55: =over 4
   56: 
   57: =item $processmarker
   58: 
   59: Contains the time this process was started and this servers host id.
   60: 
   61: =item $dumpcount
   62: 
   63: Counts the number of times a message log flush has been attempted (regardless
   64: of success) by this process.  Used as part of the filename when messages are
   65: delayed.
   66: 
   67: =back
   68: 
   69: =cut
   70: 
   71: package Apache::lonnet;
   72: 
   73: use strict;
   74: use LWP::UserAgent();
   75: use HTTP::Date;
   76: use Image::Magick;
   77: 
   78: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
   79:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
   80:             %managerstab);
   81: 
   82: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
   83:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
   84:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
   85:     %courseownerbuf, %coursetypebuf,$locknum);
   86: 
   87: use IO::Socket;
   88: use GDBM_File;
   89: use HTML::LCParser;
   90: use Fcntl qw(:flock);
   91: use Storable qw(thaw nfreeze);
   92: use Time::HiRes qw( gettimeofday tv_interval );
   93: use Cache::Memcached;
   94: use Digest::MD5;
   95: use Math::Random;
   96: use File::MMagic;
   97: use LONCAPA qw(:DEFAULT :match);
   98: use LONCAPA::Configuration;
   99: 
  100: use File::Copy;
  101: 
  102: my $readit;
  103: my $max_connection_retries = 10;     # Or some such value.
  104: 
  105: require Exporter;
  106: 
  107: our @ISA = qw (Exporter);
  108: our @EXPORT = qw(%env);
  109: 
  110: 
  111: # --------------------------------------------------------------------- Logging
  112: {
  113:     my $logid;
  114:     sub instructor_log {
  115: 	my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
  116:         if (($cnum eq '') || ($cdom eq '')) {
  117:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  118:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  119:         }
  120: 	$logid++;
  121:         my $now = time();
  122: 	my $id=$now.'00000'.$$.'00000'.$logid;
  123: 	return &Apache::lonnet::put('nohist_'.$hash_name,
  124: 				    { $id => {
  125: 					'exe_uname' => $env{'user.name'},
  126: 					'exe_udom'  => $env{'user.domain'},
  127: 					'exe_time'  => $now,
  128: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
  129: 					'delflag'   => $delflag,
  130: 					'logentry'  => $storehash,
  131: 					'uname'     => $uname,
  132: 					'udom'      => $udom,
  133: 				    }
  134: 				  },$cdom,$cnum);
  135:     }
  136: }
  137: 
  138: sub logtouch {
  139:     my $execdir=$perlvar{'lonDaemons'};
  140:     unless (-e "$execdir/logs/lonnet.log") {	
  141: 	open(my $fh,">>$execdir/logs/lonnet.log");
  142: 	close $fh;
  143:     }
  144:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  145:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  146: }
  147: 
  148: sub logthis {
  149:     my $message=shift;
  150:     my $execdir=$perlvar{'lonDaemons'};
  151:     my $now=time;
  152:     my $local=localtime($now);
  153:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
  154: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
  155: 	print $fh $logstring;
  156: 	close($fh);
  157:     }
  158:     return 1;
  159: }
  160: 
  161: sub logperm {
  162:     my $message=shift;
  163:     my $execdir=$perlvar{'lonDaemons'};
  164:     my $now=time;
  165:     my $local=localtime($now);
  166:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
  167: 	print $fh "$now:$message:$local\n";
  168: 	close($fh);
  169:     }
  170:     return 1;
  171: }
  172: 
  173: sub create_connection {
  174:     my ($hostname,$lonid) = @_;
  175:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  176: 				     Type    => SOCK_STREAM,
  177: 				     Timeout => 10);
  178:     return 0 if (!$client);
  179:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
  180:     my $result = <$client>;
  181:     chomp($result);
  182:     return 1 if ($result eq 'done');
  183:     return 0;
  184: }
  185: 
  186: sub get_server_timezone {
  187:     my ($cnum,$cdom) = @_;
  188:     my $home=&homeserver($cnum,$cdom);
  189:     if ($home ne 'no_host') {
  190:         my $cachetime = 24*3600;
  191:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
  192:         if (defined($cached)) {
  193:             return $timezone;
  194:         } else {
  195:             my $timezone = &reply('servertimezone',$home);
  196:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
  197:         }
  198:     }
  199: }
  200: 
  201: sub get_server_distarch {
  202:     my ($lonhost,$ignore_cache) = @_;
  203:     if (defined($lonhost)) {
  204:         if (!defined(&hostname($lonhost))) {
  205:             return;
  206:         }
  207:         my $cachetime = 12*3600;
  208:         if (!$ignore_cache) {
  209:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
  210:             if (defined($cached)) {
  211:                 return $distarch;
  212:             }
  213:         }
  214:         my $rep = &reply('serverdistarch',$lonhost);
  215:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
  216:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
  217:                 $rep eq '') {
  218:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
  219:         }
  220:     }
  221:     return;
  222: }
  223: 
  224: sub get_server_loncaparev {
  225:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
  226:     if (defined($lonhost)) {
  227:         if (!defined(&hostname($lonhost))) {
  228:             undef($lonhost);
  229:         }
  230:     }
  231:     if (!defined($lonhost)) {
  232:         if (defined(&domain($dom,'primary'))) {
  233:             $lonhost=&domain($dom,'primary');
  234:             if ($lonhost eq 'no_host') {
  235:                 undef($lonhost);
  236:             }
  237:         }
  238:     }
  239:     if (defined($lonhost)) {
  240:         my $cachetime = 12*3600;
  241:         if (!$ignore_cache) {
  242:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
  243:             if (defined($cached)) {
  244:                 return $loncaparev;
  245:             }
  246:         }
  247:         my ($answer,$loncaparev);
  248:         my @ids=&current_machine_ids();
  249:         if (grep(/^\Q$lonhost\E$/,@ids)) {
  250:             $answer = $perlvar{'lonVersion'};
  251:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  252:                 $loncaparev = $1;
  253:             }
  254:         } else {
  255:             $answer = &reply('serverloncaparev',$lonhost);
  256:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
  257:                 if ($caller eq 'loncron') {
  258:                     my $ua=new LWP::UserAgent;
  259:                     $ua->timeout(4);
  260:                     my $protocol = $protocol{$lonhost};
  261:                     $protocol = 'http' if ($protocol ne 'https');
  262:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
  263:                     my $request=new HTTP::Request('GET',$url);
  264:                     my $response=$ua->request($request);
  265:                     unless ($response->is_error()) {
  266:                         my $content = $response->content;
  267:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
  268:                             $loncaparev = $1;
  269:                         }
  270:                     }
  271:                 } else {
  272:                     $loncaparev = $loncaparevs{$lonhost};
  273:                 }
  274:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  275:                 $loncaparev = $1;
  276:             }
  277:         }
  278:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
  279:     }
  280: }
  281: 
  282: sub get_server_homeID {
  283:     my ($hostname,$ignore_cache,$caller) = @_;
  284:     unless ($ignore_cache) {
  285:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
  286:         if (defined($cached)) {
  287:             return $serverhomeID;
  288:         }
  289:     }
  290:     my $cachetime = 12*3600;
  291:     my $serverhomeID;
  292:     if ($caller eq 'loncron') { 
  293:         my @machine_ids = &machine_ids($hostname);
  294:         foreach my $id (@machine_ids) {
  295:             my $response = &reply('serverhomeID',$id);
  296:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
  297:                 $serverhomeID = $response;
  298:                 last;
  299:             }
  300:         }
  301:         if ($serverhomeID eq '') {
  302:             $serverhomeID = $machine_ids[-1];
  303:         }
  304:     } else {
  305:         $serverhomeID = $serverhomeIDs{$hostname};
  306:     }
  307:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
  308: }
  309: 
  310: sub get_remote_globals {
  311:     my ($lonhost,$whathash,$ignore_cache) = @_;
  312:     my ($result,%returnhash,%whatneeded);
  313:     if (ref($whathash) eq 'HASH') {
  314:         foreach my $what (sort(keys(%{$whathash}))) {
  315:             my $hashid = $lonhost.'-'.$what;
  316:             my ($response,$cached);
  317:             unless ($ignore_cache) {
  318:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
  319:             }
  320:             if (defined($cached)) {
  321:                 $returnhash{$what} = $response;
  322:             } else {
  323:                 $whatneeded{$what} = 1;
  324:             }
  325:         }
  326:         if (keys(%whatneeded) == 0) {
  327:             $result = 'ok';
  328:         } else {
  329:             my $requested = &freeze_escape(\%whatneeded);
  330:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
  331:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  332:                 ($rep eq 'unknown_cmd')) {
  333:                 $result = $rep;
  334:             } else {
  335:                 $result = 'ok';
  336:                 my @pairs=split(/\&/,$rep);
  337:                 foreach my $item (@pairs) {
  338:                     my ($key,$value)=split(/=/,$item,2);
  339:                     my $what = &unescape($key);
  340:                     my $hashid = $lonhost.'-'.$what;
  341:                     $returnhash{$what}=&thaw_unescape($value);
  342:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
  343:                 }
  344:             }
  345:         }
  346:     }
  347:     return ($result,\%returnhash);
  348: }
  349: 
  350: sub remote_devalidate_cache {
  351:     my ($lonhost,$name,$id) = @_;
  352:     my $response = &reply('devalidatecache:'.&escape($name).':'.&escape($id),$lonhost);
  353:     return $response;
  354: }
  355: 
  356: # -------------------------------------------------- Non-critical communication
  357: sub subreply {
  358:     my ($cmd,$server)=@_;
  359:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  360:     #
  361:     #  With loncnew process trimming, there's a timing hole between lonc server
  362:     #  process exit and the master server picking up the listen on the AF_UNIX
  363:     #  socket.  In that time interval, a lock file will exist:
  364: 
  365:     my $lockfile=$peerfile.".lock";
  366:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  367: 	sleep(1);
  368:     }
  369:     # At this point, either a loncnew parent is listening or an old lonc
  370:     # or loncnew child is listening so we can connect or everything's dead.
  371:     #
  372:     #   We'll give the connection a few tries before abandoning it.  If
  373:     #   connection is not possible, we'll con_lost back to the client.
  374:     #   
  375:     my $client;
  376:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  377: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  378: 				      Type    => SOCK_STREAM,
  379: 				      Timeout => 10);
  380: 	if ($client) {
  381: 	    last;		# Connected!
  382: 	} else {
  383: 	    &create_connection(&hostname($server),$server);
  384: 	}
  385:         sleep(1);		# Try again later if failed connection.
  386:     }
  387:     my $answer;
  388:     if ($client) {
  389: 	print $client "sethost:$server:$cmd\n";
  390: 	$answer=<$client>;
  391: 	if (!$answer) { $answer="con_lost"; }
  392: 	chomp($answer);
  393:     } else {
  394: 	$answer = 'con_lost';	# Failed connection.
  395:     }
  396:     return $answer;
  397: }
  398: 
  399: sub reply {
  400:     my ($cmd,$server)=@_;
  401:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  402:     my $answer=subreply($cmd,$server);
  403:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  404:        &logthis("<font color=\"blue\">WARNING:".
  405:                 " $cmd to $server returned $answer</font>");
  406:     }
  407:     return $answer;
  408: }
  409: 
  410: # ----------------------------------------------------------- Send USR1 to lonc
  411: 
  412: sub reconlonc {
  413:     my ($lonid) = @_;
  414:     my $hostname = &hostname($lonid);
  415:     if ($lonid) {
  416: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  417: 	if ($hostname && -e $peerfile) {
  418: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  419: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  420: 					     Type    => SOCK_STREAM,
  421: 					     Timeout => 10);
  422: 	    if ($client) {
  423: 		print $client ("reset_retries\n");
  424: 		my $answer=<$client>;
  425: 		#reset just this one.
  426: 	    }
  427: 	}
  428: 	return;
  429:     }
  430: 
  431:     &logthis("Trying to reconnect lonc");
  432:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  433:     if (open(my $fh,"<$loncfile")) {
  434: 	my $loncpid=<$fh>;
  435:         chomp($loncpid);
  436:         if (kill 0 => $loncpid) {
  437: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  438:             kill USR1 => $loncpid;
  439:             sleep 1;
  440:          } else {
  441: 	    &logthis(
  442:                "<font color=\"blue\">WARNING:".
  443:                " lonc at pid $loncpid not responding, giving up</font>");
  444:         }
  445:     } else {
  446: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  447:     }
  448: }
  449: 
  450: # ------------------------------------------------------ Critical communication
  451: 
  452: sub critical {
  453:     my ($cmd,$server)=@_;
  454:     unless (&hostname($server)) {
  455:         &logthis("<font color=\"blue\">WARNING:".
  456:                " Critical message to unknown server ($server)</font>");
  457:         return 'no_such_host';
  458:     }
  459:     my $answer=reply($cmd,$server);
  460:     if ($answer eq 'con_lost') {
  461: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
  462: 	my $answer=reply($cmd,$server);
  463:         if ($answer eq 'con_lost') {
  464:             my $now=time;
  465:             my $middlename=$cmd;
  466:             $middlename=substr($middlename,0,16);
  467:             $middlename=~s/\W//g;
  468:             my $dfilename=
  469:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  470:             $dumpcount++;
  471:             {
  472: 		my $dfh;
  473: 		if (open($dfh,">$dfilename")) {
  474: 		    print $dfh "$cmd\n"; 
  475: 		    close($dfh);
  476: 		}
  477:             }
  478:             sleep 2;
  479:             my $wcmd='';
  480:             {
  481: 		my $dfh;
  482: 		if (open($dfh,"<$dfilename")) {
  483: 		    $wcmd=<$dfh>; 
  484: 		    close($dfh);
  485: 		}
  486:             }
  487:             chomp($wcmd);
  488:             if ($wcmd eq $cmd) {
  489: 		&logthis("<font color=\"blue\">WARNING: ".
  490:                          "Connection buffer $dfilename: $cmd</font>");
  491:                 &logperm("D:$server:$cmd");
  492: 	        return 'con_delayed';
  493:             } else {
  494:                 &logthis("<font color=\"red\">CRITICAL:"
  495:                         ." Critical connection failed: $server $cmd</font>");
  496:                 &logperm("F:$server:$cmd");
  497:                 return 'con_failed';
  498:             }
  499:         }
  500:     }
  501:     return $answer;
  502: }
  503: 
  504: # ------------------------------------------- check if return value is an error
  505: 
  506: sub error {
  507:     my ($result) = @_;
  508:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  509: 	if ($2 == 2) { return undef; }
  510: 	return $1;
  511:     }
  512:     return undef;
  513: }
  514: 
  515: sub convert_and_load_session_env {
  516:     my ($lonidsdir,$handle)=@_;
  517:     my @profile;
  518:     {
  519: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  520: 	if (!$opened) {
  521: 	    return 0;
  522: 	}
  523: 	flock($idf,LOCK_SH);
  524: 	@profile=<$idf>;
  525: 	close($idf);
  526:     }
  527:     my %temp_env;
  528:     foreach my $line (@profile) {
  529: 	if ($line !~ m/=/) {
  530: 	    return 0;
  531: 	}
  532: 	chomp($line);
  533: 	my ($envname,$envvalue)=split(/=/,$line,2);
  534: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  535:     }
  536:     unlink("$lonidsdir/$handle.id");
  537:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  538: 	    0640)) {
  539: 	%disk_env = %temp_env;
  540: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  541: 	untie(%disk_env);
  542:     }
  543:     return 1;
  544: }
  545: 
  546: # ------------------------------------------- Transfer profile into environment
  547: my $env_loaded;
  548: sub transfer_profile_to_env {
  549:     my ($lonidsdir,$handle,$force_transfer) = @_;
  550:     if (!$force_transfer && $env_loaded) { return; } 
  551: 
  552:     if (!defined($lonidsdir)) {
  553: 	$lonidsdir = $perlvar{'lonIDsDir'};
  554:     }
  555:     if (!defined($handle)) {
  556:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  557:     }
  558: 
  559:     my $convert;
  560:     {
  561:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  562: 	if (!$opened) {
  563: 	    return;
  564: 	}
  565: 	flock($idf,LOCK_SH);
  566: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  567: 		&GDBM_READER(),0640)) {
  568: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  569: 	    untie(%disk_env);
  570: 	} else {
  571: 	    $convert = 1;
  572: 	}
  573:     }
  574:     if ($convert) {
  575: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  576: 	    &logthis("Failed to load session, or convert session.");
  577: 	}
  578:     }
  579: 
  580:     my %remove;
  581:     while ( my $envname = each(%env) ) {
  582:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  583:             if ($time < time-300) {
  584:                 $remove{$key}++;
  585:             }
  586:         }
  587:     }
  588: 
  589:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  590:     $env_loaded=1;
  591:     foreach my $expired_key (keys(%remove)) {
  592:         &delenv($expired_key);
  593:     }
  594: }
  595: 
  596: # ---------------------------------------------------- Check for valid session 
  597: sub check_for_valid_session {
  598:     my ($r) = @_;
  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:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
 2433:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 2434:     if ($filename=~m|^/home/httpd/html/userfiles/| or
 2435: 	$filename=~m -^/*(uploaded|editupload)/-) { 
 2436: 	return &repcopy_userfile($filename);
 2437:     }
 2438:     $filename=~s/[\n\r]//g;
 2439:     my $transname="$filename.in.transfer";
 2440: # FIXME: this should flock
 2441:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 2442:     my $remoteurl=subscribe($filename);
 2443:     if ($remoteurl =~ /^con_lost by/) {
 2444: 	   &logthis("Subscribe returned $remoteurl: $filename");
 2445:            return 'unavailable';
 2446:     } elsif ($remoteurl eq 'not_found') {
 2447: 	   #&logthis("Subscribe returned not_found: $filename");
 2448: 	   return 'not_found';
 2449:     } elsif ($remoteurl =~ /^rejected by/) {
 2450: 	   &logthis("Subscribe returned $remoteurl: $filename");
 2451:            return 'forbidden';
 2452:     } elsif ($remoteurl eq 'directory') {
 2453:            return 'ok';
 2454:     } else {
 2455:         my $author=$filename;
 2456:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2457:         my ($udom,$uname)=split(/\//,$author);
 2458:         my $home=homeserver($uname,$udom);
 2459:         unless ($home eq $perlvar{'lonHostID'}) {
 2460:            my @parts=split(/\//,$filename);
 2461:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 2462:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
 2463:                &logthis("Malconfiguration for replication: $filename");
 2464: 	       return 'bad_request';
 2465:            }
 2466:            my $count;
 2467:            for ($count=5;$count<$#parts;$count++) {
 2468:                $path.="/$parts[$count]";
 2469:                if ((-e $path)!=1) {
 2470: 		   mkdir($path,0777);
 2471:                }
 2472:            }
 2473:            my $ua=new LWP::UserAgent;
 2474:            my $request=new HTTP::Request('GET',"$remoteurl");
 2475:            my $response=$ua->request($request,$transname);
 2476:            if ($response->is_error()) {
 2477: 	       unlink($transname);
 2478:                my $message=$response->status_line;
 2479:                &logthis("<font color=\"blue\">WARNING:"
 2480:                        ." LWP get: $message: $filename</font>");
 2481:                return 'unavailable';
 2482:            } else {
 2483: 	       if ($remoteurl!~/\.meta$/) {
 2484:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 2485:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 2486:                   if ($mresponse->is_error()) {
 2487: 		      unlink($filename.'.meta');
 2488:                       &logthis(
 2489:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 2490:                   }
 2491: 	       }
 2492:                rename($transname,$filename);
 2493:                return 'ok';
 2494:            }
 2495:        }
 2496:     }
 2497: }
 2498: 
 2499: # ------------------------------------------------ Get server side include body
 2500: sub ssi_body {
 2501:     my ($filelink,%form)=@_;
 2502:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 2503:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 2504:     }
 2505:     my $output='';
 2506:     my $response;
 2507:     if ($filelink=~/^https?\:/) {
 2508:        ($output,$response)=&externalssi($filelink);
 2509:     } else {
 2510:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 2511:        $filelink .= 'inhibitmenu=yes';
 2512:        ($output,$response)=&ssi($filelink,%form);
 2513:     }
 2514:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 2515:     $output=~s/^.*?\<body[^\>]*\>//si;
 2516:     $output=~s/\<\/body\s*\>.*?$//si;
 2517:     if (wantarray) {
 2518:         return ($output, $response);
 2519:     } else {
 2520:         return $output;
 2521:     }
 2522: }
 2523: 
 2524: # --------------------------------------------------------- Server Side Include
 2525: 
 2526: sub absolute_url {
 2527:     my ($host_name) = @_;
 2528:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 2529:     if ($host_name eq '') {
 2530: 	$host_name = $ENV{'SERVER_NAME'};
 2531:     }
 2532:     return $protocol.$host_name;
 2533: }
 2534: 
 2535: #
 2536: #   Server side include.
 2537: # Parameters:
 2538: #  fn     Possibly encrypted resource name/id.
 2539: #  form   Hash that describes how the rendering should be done
 2540: #         and other things.
 2541: # Returns:
 2542: #   Scalar context: The content of the response.
 2543: #   Array context:  2 element list of the content and the full response object.
 2544: #     
 2545: sub ssi {
 2546: 
 2547:     my ($fn,%form)=@_;
 2548:     my $ua=new LWP::UserAgent;
 2549:     my $request;
 2550: 
 2551:     $form{'no_update_last_known'}=1;
 2552:     &Apache::lonenc::check_encrypt(\$fn);
 2553:     if (%form) {
 2554:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 2555:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
 2556:     } else {
 2557:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 2558:     }
 2559: 
 2560:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 2561:     my $response=$ua->request($request);
 2562: 
 2563:     if (wantarray) {
 2564: 	return ($response->content, $response);
 2565:     } else {
 2566: 	return $response->content;
 2567:     }
 2568: }
 2569: 
 2570: sub externalssi {
 2571:     my ($url)=@_;
 2572:     my $ua=new LWP::UserAgent;
 2573:     my $request=new HTTP::Request('GET',$url);
 2574:     my $response=$ua->request($request);
 2575:     if (wantarray) {
 2576:         return ($response->content, $response);
 2577:     } else {
 2578:         return $response->content;
 2579:     }
 2580: }
 2581: 
 2582: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 2583: 
 2584: sub allowuploaded {
 2585:     my ($srcurl,$url)=@_;
 2586:     $url=&clutter(&declutter($url));
 2587:     my $dir=$url;
 2588:     $dir=~s/\/[^\/]+$//;
 2589:     my %httpref=();
 2590:     my $httpurl=&hreflocation('',$url);
 2591:     $httpref{'httpref.'.$httpurl}=$srcurl;
 2592:     &Apache::lonnet::appenv(\%httpref);
 2593: }
 2594: 
 2595: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 2596: # input: action, courseID, current domain, intended
 2597: #        path to file, source of file, instruction to parse file for objects,
 2598: #        ref to hash for embedded objects,
 2599: #        ref to hash for codebase of java objects.
 2600: #        reference to scalar to accommodate mime type determined
 2601: #          from File::MMagic if $parser = parse.
 2602: #
 2603: # output: url to file (if action was uploaddoc), 
 2604: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 2605: #
 2606: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 2607: # course.
 2608: #
 2609: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2610: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 2611: #          course's home server.
 2612: #
 2613: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 2614: #          be copied from $source (current location) to 
 2615: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2616: #         and will then be copied to
 2617: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 2618: #         course's home server.
 2619: #
 2620: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2621: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 2622: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2623: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 2624: #         in course's home server.
 2625: #
 2626: 
 2627: sub process_coursefile {
 2628:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 2629:         $mimetype)=@_;
 2630:     my $fetchresult;
 2631:     my $home=&homeserver($docuname,$docudom);
 2632:     if ($action eq 'propagate') {
 2633:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2634: 			     $home);
 2635:     } else {
 2636:         my $fpath = '';
 2637:         my $fname = $file;
 2638:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 2639:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 2640:         my $filepath = &build_filepath($fpath);
 2641:         if ($action eq 'copy') {
 2642:             if ($source eq '') {
 2643:                 $fetchresult = 'no source file';
 2644:                 return $fetchresult;
 2645:             } else {
 2646:                 my $destination = $filepath.'/'.$fname;
 2647:                 rename($source,$destination);
 2648:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2649:                                  $home);
 2650:             }
 2651:         } elsif ($action eq 'uploaddoc') {
 2652:             open(my $fh,'>'.$filepath.'/'.$fname);
 2653:             print $fh $env{'form.'.$source};
 2654:             close($fh);
 2655:             if ($parser eq 'parse') {
 2656:                 my $mm = new File::MMagic;
 2657:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 2658:                 if ($type eq 'text/html') {
 2659:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 2660:                     unless ($parse_result eq 'ok') {
 2661:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 2662:                     }
 2663:                 }
 2664:                 if (ref($mimetype)) {
 2665:                     $$mimetype = $type;
 2666:                 } 
 2667:             }
 2668:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2669:                                  $home);
 2670:             if ($fetchresult eq 'ok') {
 2671:                 return '/uploaded/'.$fpath.'/'.$fname;
 2672:             } else {
 2673:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2674:                         ' to host '.$home.': '.$fetchresult);
 2675:                 return '/adm/notfound.html';
 2676:             }
 2677:         }
 2678:     }
 2679:     unless ( $fetchresult eq 'ok') {
 2680:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2681:              ' to host '.$home.': '.$fetchresult);
 2682:     }
 2683:     return $fetchresult;
 2684: }
 2685: 
 2686: sub build_filepath {
 2687:     my ($fpath) = @_;
 2688:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 2689:     unless ($fpath eq '') {
 2690:         my @parts=split('/',$fpath);
 2691:         foreach my $part (@parts) {
 2692:             $filepath.= '/'.$part;
 2693:             if ((-e $filepath)!=1) {
 2694:                 mkdir($filepath,0777);
 2695:             }
 2696:         }
 2697:     }
 2698:     return $filepath;
 2699: }
 2700: 
 2701: sub store_edited_file {
 2702:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 2703:     my $file = $primary_url;
 2704:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 2705:     my $fpath = '';
 2706:     my $fname = $file;
 2707:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 2708:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 2709:     my $filepath = &build_filepath($fpath);
 2710:     open(my $fh,'>'.$filepath.'/'.$fname);
 2711:     print $fh $content;
 2712:     close($fh);
 2713:     my $home=&homeserver($docuname,$docudom);
 2714:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2715: 			  $home);
 2716:     if ($$fetchresult eq 'ok') {
 2717:         return '/uploaded/'.$fpath.'/'.$fname;
 2718:     } else {
 2719:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2720: 		 ' to host '.$home.': '.$$fetchresult);
 2721:         return '/adm/notfound.html';
 2722:     }
 2723: }
 2724: 
 2725: sub clean_filename {
 2726:     my ($fname,$args)=@_;
 2727: # Replace Windows backslashes by forward slashes
 2728:     $fname=~s/\\/\//g;
 2729:     if (!$args->{'keep_path'}) {
 2730:         # Get rid of everything but the actual filename
 2731: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 2732:     }
 2733: # Replace spaces by underscores
 2734:     $fname=~s/\s+/\_/g;
 2735: # Replace all other weird characters by nothing
 2736:     $fname=~s{[^/\w\.\-]}{}g;
 2737: # Replace all .\d. sequences with _\d. so they no longer look like version
 2738: # numbers
 2739:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 2740:     return $fname;
 2741: }
 2742: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 2743: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 2744: # image with the same aspect ratio as the original, but with dimensions which do 
 2745: # not exceed $resizewidth and $resizeheight.
 2746:  
 2747: sub resizeImage {
 2748:     my ($img_path,$resizewidth,$resizeheight) = @_;
 2749:     my $ima = Image::Magick->new;
 2750:     my $resized;
 2751:     if (-e $img_path) {
 2752:         $ima->Read($img_path);
 2753:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 2754:             my $width = $ima->Get('width');
 2755:             my $height = $ima->Get('height');
 2756:             if ($width > $resizewidth) {
 2757: 	        my $factor = $width/$resizewidth;
 2758:                 my $newheight = $height/$factor;
 2759:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 2760:                 $resized = 1;
 2761:             }
 2762:         }
 2763:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 2764:             my $width = $ima->Get('width');
 2765:             my $height = $ima->Get('height');
 2766:             if ($height > $resizeheight) {
 2767:                 my $factor = $height/$resizeheight;
 2768:                 my $newwidth = $width/$factor;
 2769:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 2770:                 $resized = 1;
 2771:             }
 2772:         }
 2773:         if ($resized) {
 2774:             $ima->Write($img_path);
 2775:         }
 2776:     }
 2777:     return;
 2778: }
 2779: 
 2780: # --------------- Take an uploaded file and put it into the userfiles directory
 2781: # input: $formname - the contents of the file are in $env{"form.$formname"}
 2782: #                    the desired filename is in $env{"form.$formname.filename"}
 2783: #        $context - possible values: coursedoc, existingfile, overwrite, 
 2784: #                                    canceloverwrite, or ''. 
 2785: #                   if 'coursedoc': upload to the current course
 2786: #                   if 'existingfile': write file to tmp/overwrites directory 
 2787: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 2788: #                   $context is passed as argument to &finishuserfileupload
 2789: #        $subdir - directory in userfile to store the file into
 2790: #        $parser - instruction to parse file for objects ($parser = parse)    
 2791: #        $allfiles - reference to hash for embedded objects
 2792: #        $codebase - reference to hash for codebase of java objects
 2793: #        $desuname - username for permanent storage of uploaded file
 2794: #        $dsetudom - domain for permanaent storage of uploaded file
 2795: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 2796: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 2797: #        $resizewidth - width (pixels) to which to resize uploaded image
 2798: #        $resizeheight - height (pixels) to which to resize uploaded image
 2799: #        $mimetype - reference to scalar to accommodate mime type determined
 2800: #                    from File::MMagic if $parser = parse.
 2801: # 
 2802: # output: url of file in userspace, or error: <message> 
 2803: #             or /adm/notfound.html if failure to upload occurse
 2804: 
 2805: sub userfileupload {
 2806:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 2807:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 2808:     if (!defined($subdir)) { $subdir='unknown'; }
 2809:     my $fname=$env{'form.'.$formname.'.filename'};
 2810:     $fname=&clean_filename($fname);
 2811:     # See if there is anything left
 2812:     unless ($fname) { return 'error: no uploaded file'; }
 2813:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 2814:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 2815:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 2816:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 2817:         my $now = time;
 2818:         my $filepath;
 2819:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 2820:              $filepath = 'tmp/helprequests/'.$now;
 2821:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 2822:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 2823:                          '_'.$env{'user.domain'}.'/pending';
 2824:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 2825:             my ($docuname,$docudom);
 2826:             if ($destudom) {
 2827:                 $docudom = $destudom;
 2828:             } else {
 2829:                 $docudom = $env{'user.domain'};
 2830:             }
 2831:             if ($destuname) {
 2832:                 $docuname = $destuname;
 2833:             } else {
 2834:                 $docuname = $env{'user.name'};
 2835:             }
 2836:             if (exists($env{'form.group'})) {
 2837:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2838:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2839:             }
 2840:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 2841:             if ($context eq 'canceloverwrite') {
 2842:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 2843:                 if (-e  $tempfile) {
 2844:                     my @info = stat($tempfile);
 2845:                     if ($info[9] eq $env{'form.timestamp'}) {
 2846:                         unlink($tempfile);
 2847:                     }
 2848:                 }
 2849:                 return;
 2850:             }
 2851:         }
 2852:         # Create the directory if not present
 2853:         my @parts=split(/\//,$filepath);
 2854:         my $fullpath = $perlvar{'lonDaemons'};
 2855:         for (my $i=0;$i<@parts;$i++) {
 2856:             $fullpath .= '/'.$parts[$i];
 2857:             if ((-e $fullpath)!=1) {
 2858:                 mkdir($fullpath,0777);
 2859:             }
 2860:         }
 2861:         open(my $fh,'>'.$fullpath.'/'.$fname);
 2862:         print $fh $env{'form.'.$formname};
 2863:         close($fh);
 2864:         if ($context eq 'existingfile') {
 2865:             my @info = stat($fullpath.'/'.$fname);
 2866:             return ($fullpath.'/'.$fname,$info[9]);
 2867:         } else {
 2868:             return $fullpath.'/'.$fname;
 2869:         }
 2870:     }
 2871:     if ($subdir eq 'scantron') {
 2872:         $fname = 'scantron_orig_'.$fname;
 2873:     } else {
 2874:         $fname="$subdir/$fname";
 2875:     }
 2876:     if ($context eq 'coursedoc') {
 2877: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2878: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2879:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 2880:             return &finishuserfileupload($docuname,$docudom,
 2881: 					 $formname,$fname,$parser,$allfiles,
 2882: 					 $codebase,$thumbwidth,$thumbheight,
 2883:                                          $resizewidth,$resizeheight,$context,$mimetype);
 2884:         } else {
 2885:             $fname=$env{'form.folder'}.'/'.$fname;
 2886:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 2887: 				       $fname,$formname,$parser,
 2888: 				       $allfiles,$codebase,$mimetype);
 2889:         }
 2890:     } elsif (defined($destuname)) {
 2891:         my $docuname=$destuname;
 2892:         my $docudom=$destudom;
 2893: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 2894: 				     $parser,$allfiles,$codebase,
 2895:                                      $thumbwidth,$thumbheight,
 2896:                                      $resizewidth,$resizeheight,$context,$mimetype);
 2897:     } else {
 2898:         my $docuname=$env{'user.name'};
 2899:         my $docudom=$env{'user.domain'};
 2900:         if (exists($env{'form.group'})) {
 2901:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2902:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2903:         }
 2904: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 2905: 				     $parser,$allfiles,$codebase,
 2906:                                      $thumbwidth,$thumbheight,
 2907:                                      $resizewidth,$resizeheight,$context,$mimetype);
 2908:     }
 2909: }
 2910: 
 2911: sub finishuserfileupload {
 2912:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 2913:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 2914:     my $path=$docudom.'/'.$docuname.'/';
 2915:     my $filepath=$perlvar{'lonDocRoot'};
 2916:   
 2917:     my ($fnamepath,$file,$fetchthumb);
 2918:     $file=$fname;
 2919:     if ($fname=~m|/|) {
 2920:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 2921: 	$path.=$fnamepath.'/';
 2922:     }
 2923:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 2924:     my $count;
 2925:     for ($count=4;$count<=$#parts;$count++) {
 2926:         $filepath.="/$parts[$count]";
 2927:         if ((-e $filepath)!=1) {
 2928: 	    mkdir($filepath,0777);
 2929:         }
 2930:     }
 2931: 
 2932: # Save the file
 2933:     {
 2934: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 2935: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 2936: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 2937: 	    return '/adm/notfound.html';
 2938: 	}
 2939:         if ($context eq 'overwrite') {
 2940:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 2941:             my $target = $filepath.'/'.$file;
 2942:             if (-e $source) {
 2943:                 my @info = stat($source);
 2944:                 if ($info[9] eq $env{'form.timestamp'}) {   
 2945:                     unless (&File::Copy::move($source,$target)) {
 2946:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 2947:                         return "Moving from $source failed";
 2948:                     }
 2949:                 } else {
 2950:                     return "Temporary file: $source had unexpected date/time for last modification";
 2951:                 }
 2952:             } else {
 2953:                 return "Temporary file: $source missing";
 2954:             }
 2955:         } elsif (!print FH ($env{'form.'.$formname})) {
 2956: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 2957: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 2958: 	    return '/adm/notfound.html';
 2959: 	}
 2960: 	close(FH);
 2961:         if ($resizewidth && $resizeheight) {
 2962:             my $mm = new File::MMagic;
 2963:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 2964:             if ($mime_type =~ m{^image/}) {
 2965: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 2966:             }  
 2967: 	}
 2968:     }
 2969:     if ($parser eq 'parse') {
 2970:         my $mm = new File::MMagic;
 2971:         my $type = $mm->checktype_filename($filepath.'/'.$file);
 2972:         if ($type eq 'text/html') {
 2973:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 2974:                                                        $allfiles,$codebase);
 2975:             unless ($parse_result eq 'ok') {
 2976:                 &logthis('Failed to parse '.$filepath.$file.
 2977: 	   	         ' for embedded media: '.$parse_result); 
 2978:             }
 2979:         }
 2980:         if (ref($mimetype)) {
 2981:             $$mimetype = $type;
 2982:         }
 2983:     }
 2984:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 2985:         my $input = $filepath.'/'.$file;
 2986:         my $output = $filepath.'/'.'tn-'.$file;
 2987:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 2988:         system("convert -sample $thumbsize $input $output");
 2989:         if (-e $filepath.'/'.'tn-'.$file) {
 2990:             $fetchthumb  = 1; 
 2991:         }
 2992:     }
 2993:  
 2994: # Notify homeserver to grep it
 2995: #
 2996:     my $docuhome=&homeserver($docuname,$docudom);	
 2997:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 2998:     if ($fetchresult eq 'ok') {
 2999:         if ($fetchthumb) {
 3000:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 3001:             if ($thumbresult ne 'ok') {
 3002:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 3003:                          $docuhome.': '.$thumbresult);
 3004:             }
 3005:         }
 3006: #
 3007: # Return the URL to it
 3008:         return '/uploaded/'.$path.$file;
 3009:     } else {
 3010:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 3011: 		 ': '.$fetchresult);
 3012:         return '/adm/notfound.html';
 3013:     }
 3014: }
 3015: 
 3016: sub extract_embedded_items {
 3017:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 3018:     my @state = ();
 3019:     my %javafiles = (
 3020:                       codebase => '',
 3021:                       code => '',
 3022:                       archive => ''
 3023:                     );
 3024:     my %mediafiles = (
 3025:                       src => '',
 3026:                       movie => '',
 3027:                      );
 3028:     my $p;
 3029:     if ($content) {
 3030:         $p = HTML::LCParser->new($content);
 3031:     } else {
 3032:         $p = HTML::LCParser->new($fullpath);
 3033:     }
 3034:     while (my $t=$p->get_token()) {
 3035: 	if ($t->[0] eq 'S') {
 3036: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 3037: 	    push(@state, $tagname);
 3038:             if (lc($tagname) eq 'allow') {
 3039:                 &add_filetype($allfiles,$attr->{'src'},'src');
 3040:             }
 3041: 	    if (lc($tagname) eq 'img') {
 3042: 		&add_filetype($allfiles,$attr->{'src'},'src');
 3043: 	    }
 3044: 	    if (lc($tagname) eq 'a') {
 3045: 		&add_filetype($allfiles,$attr->{'href'},'href');
 3046: 	    }
 3047:             if (lc($tagname) eq 'script') {
 3048:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 3049:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 3050:                 } else {
 3051:                     &add_filetype($allfiles,$attr->{'src'},'src');
 3052:                 }
 3053:             }
 3054:             if (lc($tagname) eq 'link') {
 3055:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 3056:                     &add_filetype($allfiles,$attr->{'href'},'href');
 3057:                 }
 3058:             }
 3059: 	    if (lc($tagname) eq 'object' ||
 3060: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 3061: 		foreach my $item (keys(%javafiles)) {
 3062: 		    $javafiles{$item} = '';
 3063: 		}
 3064: 	    }
 3065: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 3066: 		my $name = lc($attr->{'name'});
 3067: 		foreach my $item (keys(%javafiles)) {
 3068: 		    if ($name eq $item) {
 3069: 			$javafiles{$item} = $attr->{'value'};
 3070: 			last;
 3071: 		    }
 3072: 		}
 3073: 		foreach my $item (keys(%mediafiles)) {
 3074: 		    if ($name eq $item) {
 3075: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
 3076: 			last;
 3077: 		    }
 3078: 		}
 3079: 	    }
 3080: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 3081: 		foreach my $item (keys(%javafiles)) {
 3082: 		    if ($attr->{$item}) {
 3083: 			$javafiles{$item} = $attr->{$item};
 3084: 			last;
 3085: 		    }
 3086: 		}
 3087: 		foreach my $item (keys(%mediafiles)) {
 3088: 		    if ($attr->{$item}) {
 3089: 			&add_filetype($allfiles,$attr->{$item},$item);
 3090: 			last;
 3091: 		    }
 3092: 		}
 3093: 	    }
 3094: 	} elsif ($t->[0] eq 'E') {
 3095: 	    my ($tagname) = ($t->[1]);
 3096: 	    if ($javafiles{'codebase'} ne '') {
 3097: 		$javafiles{'codebase'} .= '/';
 3098: 	    }  
 3099: 	    if (lc($tagname) eq 'applet' ||
 3100: 		lc($tagname) eq 'object' ||
 3101: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 3102: 		) {
 3103: 		foreach my $item (keys(%javafiles)) {
 3104: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 3105: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 3106: 			&add_filetype($allfiles,$file,$item);
 3107: 		    }
 3108: 		}
 3109: 	    } 
 3110: 	    pop @state;
 3111: 	}
 3112:     }
 3113:     return 'ok';
 3114: }
 3115: 
 3116: sub add_filetype {
 3117:     my ($allfiles,$file,$type)=@_;
 3118:     if (exists($allfiles->{$file})) {
 3119: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 3120: 	    push(@{$allfiles->{$file}}, &escape($type));
 3121: 	}
 3122:     } else {
 3123: 	@{$allfiles->{$file}} = (&escape($type));
 3124:     }
 3125: }
 3126: 
 3127: sub removeuploadedurl {
 3128:     my ($url)=@_;	
 3129:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 3130:     return &removeuserfile($uname,$udom,$fname);
 3131: }
 3132: 
 3133: sub removeuserfile {
 3134:     my ($docuname,$docudom,$fname)=@_;
 3135:     my $home=&homeserver($docuname,$docudom);    
 3136:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 3137:     if ($result eq 'ok') {	
 3138:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 3139:             my $metafile = $fname.'.meta';
 3140:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 3141: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 3142:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 3143:             my $sqlresult = 
 3144:                 &update_portfolio_table($docuname,$docudom,$file,
 3145:                                         'portfolio_metadata',$group,
 3146:                                         'delete');
 3147:         }
 3148:     }
 3149:     return $result;
 3150: }
 3151: 
 3152: sub mkdiruserfile {
 3153:     my ($docuname,$docudom,$dir)=@_;
 3154:     my $home=&homeserver($docuname,$docudom);
 3155:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 3156: }
 3157: 
 3158: sub renameuserfile {
 3159:     my ($docuname,$docudom,$old,$new)=@_;
 3160:     my $home=&homeserver($docuname,$docudom);
 3161:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 3162:                         &escape("$old").':'.&escape("$new"),$home);
 3163:     if ($result eq 'ok') {
 3164:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 3165:             my $oldmeta = $old.'.meta';
 3166:             my $newmeta = $new.'.meta';
 3167:             my $metaresult = 
 3168:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 3169: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 3170:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 3171:             my $sqlresult = 
 3172:                 &update_portfolio_table($docuname,$docudom,$file,
 3173:                                         'portfolio_metadata',$group,
 3174:                                         'delete');
 3175:         }
 3176:     }
 3177:     return $result;
 3178: }
 3179: 
 3180: # ------------------------------------------------------------------------- Log
 3181: 
 3182: sub log {
 3183:     my ($dom,$nam,$hom,$what)=@_;
 3184:     return critical("log:$dom:$nam:$what",$hom);
 3185: }
 3186: 
 3187: # ------------------------------------------------------------------ Course Log
 3188: #
 3189: # This routine flushes several buffers of non-mission-critical nature
 3190: #
 3191: 
 3192: sub flushcourselogs {
 3193:     &logthis('Flushing log buffers');
 3194: #
 3195: # course logs
 3196: # This is a log of all transactions in a course, which can be used
 3197: # for data mining purposes
 3198: #
 3199: # It also collects the courseid database, which lists last transaction
 3200: # times and course titles for all courseids
 3201: #
 3202:     my %courseidbuffer=();
 3203:     foreach my $crsid (keys(%courselogs)) {
 3204:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 3205: 		          &escape($courselogs{$crsid}),
 3206: 		          $coursehombuf{$crsid}) eq 'ok') {
 3207: 	    delete $courselogs{$crsid};
 3208:         } else {
 3209:             &logthis('Failed to flush log buffer for '.$crsid);
 3210:             if (length($courselogs{$crsid})>40000) {
 3211:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 3212:                         " exceeded maximum size, deleting.</font>");
 3213:                delete $courselogs{$crsid};
 3214:             }
 3215:         }
 3216:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 3217:             'description' => $coursedescrbuf{$crsid},
 3218:             'inst_code'    => $courseinstcodebuf{$crsid},
 3219:             'type'        => $coursetypebuf{$crsid},
 3220:             'owner'       => $courseownerbuf{$crsid},
 3221:         };
 3222:     }
 3223: #
 3224: # Write course id database (reverse lookup) to homeserver of courses 
 3225: # Is used in pickcourse
 3226: #
 3227:     foreach my $crs_home (keys(%courseidbuffer)) {
 3228:         my $response = &courseidput(&host_domain($crs_home),
 3229:                                     $courseidbuffer{$crs_home},
 3230:                                     $crs_home,'timeonly');
 3231:     }
 3232: #
 3233: # File accesses
 3234: # Writes to the dynamic metadata of resources to get hit counts, etc.
 3235: #
 3236:     foreach my $entry (keys(%accesshash)) {
 3237:         if ($entry =~ /___count$/) {
 3238:             my ($dom,$name);
 3239:             ($dom,$name,undef)=
 3240: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 3241:             if (! defined($dom) || $dom eq '' || 
 3242:                 ! defined($name) || $name eq '') {
 3243:                 my $cid = $env{'request.course.id'};
 3244:                 $dom  = $env{'request.'.$cid.'.domain'};
 3245:                 $name = $env{'request.'.$cid.'.num'};
 3246:             }
 3247:             my $value = $accesshash{$entry};
 3248:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 3249:             my %temphash=($url => $value);
 3250:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 3251:             if ($result eq 'ok') {
 3252:                 delete $accesshash{$entry};
 3253:             } elsif ($result eq 'unknown_cmd') {
 3254:                 # Target server has old code running on it.
 3255:                 my %temphash=($entry => $value);
 3256:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 3257:                     delete $accesshash{$entry};
 3258:                 }
 3259:             }
 3260:         } else {
 3261:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 3262:             my %temphash=($entry => $accesshash{$entry});
 3263:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 3264:                 delete $accesshash{$entry};
 3265:             }
 3266:         }
 3267:     }
 3268: #
 3269: # Roles
 3270: # Reverse lookup of user roles for course faculty/staff and co-authorship
 3271: #
 3272:     foreach my $entry (keys(%userrolehash)) {
 3273:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 3274: 	    split(/\:/,$entry);
 3275:         if (&Apache::lonnet::put('nohist_userroles',
 3276:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 3277:                 $rudom,$runame) eq 'ok') {
 3278: 	    delete $userrolehash{$entry};
 3279:         }
 3280:     }
 3281: #
 3282: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 3283: #
 3284:     my %domrolebuffer = ();
 3285:     foreach my $entry (keys(%domainrolehash)) {
 3286:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 3287:         if ($domrolebuffer{$rudom}) {
 3288:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 3289:                       '='.&escape($domainrolehash{$entry});
 3290:         } else {
 3291:             $domrolebuffer{$rudom}.=&escape($entry).
 3292:                       '='.&escape($domainrolehash{$entry});
 3293:         }
 3294:         delete $domainrolehash{$entry};
 3295:     }
 3296:     foreach my $dom (keys(%domrolebuffer)) {
 3297: 	my %servers = &get_servers($dom,'library');
 3298: 	foreach my $tryserver (keys(%servers)) {
 3299: 	    unless (&reply('domroleput:'.$dom.':'.
 3300: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 3301: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 3302: 	    }
 3303:         }
 3304:     }
 3305:     $dumpcount++;
 3306: }
 3307: 
 3308: sub courselog {
 3309:     my $what=shift;
 3310:     $what=time.':'.$what;
 3311:     unless ($env{'request.course.id'}) { return ''; }
 3312:     $coursedombuf{$env{'request.course.id'}}=
 3313:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 3314:     $coursenumbuf{$env{'request.course.id'}}=
 3315:        $env{'course.'.$env{'request.course.id'}.'.num'};
 3316:     $coursehombuf{$env{'request.course.id'}}=
 3317:        $env{'course.'.$env{'request.course.id'}.'.home'};
 3318:     $coursedescrbuf{$env{'request.course.id'}}=
 3319:        $env{'course.'.$env{'request.course.id'}.'.description'};
 3320:     $courseinstcodebuf{$env{'request.course.id'}}=
 3321:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 3322:     $courseownerbuf{$env{'request.course.id'}}=
 3323:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 3324:     $coursetypebuf{$env{'request.course.id'}}=
 3325:        $env{'course.'.$env{'request.course.id'}.'.type'};
 3326:     if (defined $courselogs{$env{'request.course.id'}}) {
 3327: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 3328:     } else {
 3329: 	$courselogs{$env{'request.course.id'}}.=$what;
 3330:     }
 3331:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 3332: 	&flushcourselogs();
 3333:     }
 3334: }
 3335: 
 3336: sub courseacclog {
 3337:     my $fnsymb=shift;
 3338:     unless ($env{'request.course.id'}) { return ''; }
 3339:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 3340:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
 3341:         $what.=':POST';
 3342:         # FIXME: Probably ought to escape things....
 3343: 	foreach my $key (keys(%env)) {
 3344:             if ($key=~/^form\.(.*)/) {
 3345:                 my $formitem = $1;
 3346:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 3347:                     $what.=':'.$formitem.'='.$env{$key};
 3348:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 3349:                     $what.=':'.$formitem.'='.$env{$key};
 3350:                 }
 3351:             }
 3352:         }
 3353:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 3354:         # FIXME: We should not be depending on a form parameter that someone
 3355:         # editing lonsearchcat.pm might change in the future.
 3356:         if ($env{'form.phase'} eq 'course_search') {
 3357:             $what.= ':POST';
 3358:             # FIXME: Probably ought to escape things....
 3359:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 3360:                                  'crsdiscuss') {
 3361:                 $what.=':'.$element.'='.$env{'form.'.$element};
 3362:             }
 3363:         }
 3364:     }
 3365:     &courselog($what);
 3366: }
 3367: 
 3368: sub countacc {
 3369:     my $url=&declutter(shift);
 3370:     return if (! defined($url) || $url eq '');
 3371:     unless ($env{'request.course.id'}) { return ''; }
 3372:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 3373:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 3374:     $accesshash{$key}++;
 3375: }
 3376: 
 3377: sub linklog {
 3378:     my ($from,$to)=@_;
 3379:     $from=&declutter($from);
 3380:     $to=&declutter($to);
 3381:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 3382:     $accesshash{$to.'___'.$from.'___goto'}=1;
 3383: }
 3384:   
 3385: sub userrolelog {
 3386:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 3387:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
 3388:         ($trole=~/^in/) || ($trole=~/^cc/) ||
 3389:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
 3390:         ($trole=~/^ta/) || ($trole=~/^co/)) {
 3391:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 3392:        $userrolehash
 3393:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 3394:                     =$tend.':'.$tstart;
 3395:     }
 3396:     if (($env{'request.role'} =~ /dc\./) &&
 3397: 	(($trole=~/^au/) || ($trole=~/^in/) ||
 3398: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
 3399: 	 ($trole=~/^cr/) || ($trole=~/^ta/) ||
 3400:          ($trole=~/^co/))) {
 3401:        $userrolehash
 3402:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 3403:                     =$tend.':'.$tstart;
 3404:     }
 3405:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
 3406:         ($trole=~/^li/) || ($trole=~/^li/) ||
 3407:         ($trole=~/^au/) || ($trole=~/^dg/) ||
 3408:         ($trole=~/^sc/)) {
 3409:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 3410:        $domainrolehash
 3411:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 3412:                     = $tend.':'.$tstart;
 3413:     }
 3414: }
 3415: 
 3416: sub courserolelog {
 3417:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 3418:     if (($trole eq 'cc') || ($trole eq 'in') ||
 3419:         ($trole eq 'ep') || ($trole eq 'ad') ||
 3420:         ($trole eq 'ta') || ($trole eq 'st') ||
 3421:         ($trole=~/^cr/) || ($trole eq 'gr') ||
 3422:         ($trole eq 'co')) {
 3423:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 3424:             my $cdom = $1;
 3425:             my $cnum = $2;
 3426:             my $sec = $3;
 3427:             my $namespace = 'rolelog';
 3428:             my %storehash = (
 3429:                                role    => $trole,
 3430:                                start   => $tstart,
 3431:                                end     => $tend,
 3432:                                selfenroll => $selfenroll,
 3433:                                context    => $context,
 3434:                             );
 3435:             if ($trole eq 'gr') {
 3436:                 $namespace = 'groupslog';
 3437:                 $storehash{'group'} = $sec;
 3438:             } else {
 3439:                 $storehash{'section'} = $sec;
 3440:             }
 3441:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
 3442:             if (($trole ne 'st') || ($sec ne '')) {
 3443:                 &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 3444:             }
 3445:         }
 3446:     }
 3447:     return;
 3448: }
 3449: 
 3450: sub get_course_adv_roles {
 3451:     my ($cid,$codes) = @_;
 3452:     $cid=$env{'request.course.id'} unless (defined($cid));
 3453:     my %coursehash=&coursedescription($cid);
 3454:     my $crstype = &Apache::loncommon::course_type($cid);
 3455:     my %nothide=();
 3456:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3457:         if ($user !~ /:/) {
 3458: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 3459:         } else {
 3460:             $nothide{$user}=1;
 3461:         }
 3462:     }
 3463:     my %returnhash=();
 3464:     my %dumphash=
 3465:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 3466:     my $now=time;
 3467:     my %privileged;
 3468:     foreach my $entry (keys(%dumphash)) {
 3469: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 3470:         if (($tstart) && ($tstart<0)) { next; }
 3471:         if (($tend) && ($tend<$now)) { next; }
 3472:         if (($tstart) && ($now<$tstart)) { next; }
 3473:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 3474: 	if ($username eq '' || $domain eq '') { next; }
 3475:         unless (ref($privileged{$domain}) eq 'HASH') {
 3476:             my %dompersonnel =
 3477:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
 3478:             $privileged{$domain} = {};
 3479:             foreach my $server (keys(%dompersonnel)) {
 3480:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 3481:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
 3482:                         my ($trole,$uname,$udom) = split(/:/,$user);
 3483:                         $privileged{$udom}{$uname} = 1;
 3484:                     }
 3485:                 }
 3486:             }
 3487:         }
 3488:         if ((exists($privileged{$domain}{$username})) && 
 3489:             (!$nothide{$username.':'.$domain})) { next; }
 3490: 	if ($role eq 'cr') { next; }
 3491:         if ($codes) {
 3492:             if ($section) { $role .= ':'.$section; }
 3493:             if ($returnhash{$role}) {
 3494:                 $returnhash{$role}.=','.$username.':'.$domain;
 3495:             } else {
 3496:                 $returnhash{$role}=$username.':'.$domain;
 3497:             }
 3498:         } else {
 3499:             my $key=&plaintext($role,$crstype);
 3500:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 3501:             if ($returnhash{$key}) {
 3502: 	        $returnhash{$key}.=','.$username.':'.$domain;
 3503:             } else {
 3504:                 $returnhash{$key}=$username.':'.$domain;
 3505:             }
 3506:         }
 3507:     }
 3508:     return %returnhash;
 3509: }
 3510: 
 3511: sub get_my_roles {
 3512:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 3513:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 3514:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 3515:     my (%dumphash,%nothide);
 3516:     if ($context eq 'userroles') {
 3517:         my $extra = &freeze_escape({'skipcheck' => 1});
 3518:         %dumphash = &dump('roles',$udom,$uname,'.',undef,$extra);
 3519:     } else {
 3520:         %dumphash=
 3521:             &dump('nohist_userroles',$udom,$uname);
 3522:         if ($hidepriv) {
 3523:             my %coursehash=&coursedescription($udom.'_'.$uname);
 3524:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3525:                 if ($user !~ /:/) {
 3526:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 3527:                 } else {
 3528:                     $nothide{$user} = 1;
 3529:                 }
 3530:             }
 3531:         }
 3532:     }
 3533:     my %returnhash=();
 3534:     my $now=time;
 3535:     my %privileged;
 3536:     foreach my $entry (keys(%dumphash)) {
 3537:         my ($role,$tend,$tstart);
 3538:         if ($context eq 'userroles') {
 3539: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 3540:         } else {
 3541:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 3542:         }
 3543:         if (($tstart) && ($tstart<0)) { next; }
 3544:         my $status = 'active';
 3545:         if (($tend) && ($tend<=$now)) {
 3546:             $status = 'previous';
 3547:         } 
 3548:         if (($tstart) && ($now<$tstart)) {
 3549:             $status = 'future';
 3550:         }
 3551:         if (ref($types) eq 'ARRAY') {
 3552:             if (!grep(/^\Q$status\E$/,@{$types})) {
 3553:                 next;
 3554:             } 
 3555:         } else {
 3556:             if ($status ne 'active') {
 3557:                 next;
 3558:             }
 3559:         }
 3560:         my ($rolecode,$username,$domain,$section,$area);
 3561:         if ($context eq 'userroles') {
 3562:             ($area,$rolecode) = split(/_/,$entry);
 3563:             (undef,$domain,$username,$section) = split(/\//,$area);
 3564:         } else {
 3565:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 3566:         }
 3567:         if (ref($roledoms) eq 'ARRAY') {
 3568:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 3569:                 next;
 3570:             }
 3571:         }
 3572:         if (ref($roles) eq 'ARRAY') {
 3573:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 3574:                 if ($role =~ /^cr\//) {
 3575:                     if (!grep(/^cr$/,@{$roles})) {
 3576:                         next;
 3577:                     }
 3578:                 } elsif ($role =~ /^gr\//) {
 3579:                     if (!grep(/^gr$/,@{$roles})) {
 3580:                         next;
 3581:                     }
 3582:                 } else {
 3583:                     next;
 3584:                 }
 3585:             }
 3586:         }
 3587:         if ($hidepriv) {
 3588:             if ($context eq 'userroles') {
 3589:                 if ((&privileged($username,$domain)) &&
 3590:                     (!$nothide{$username.':'.$domain})) {
 3591:                     next;
 3592:                 }
 3593:             } else {
 3594:                 unless (ref($privileged{$domain}) eq 'HASH') {
 3595:                     my %dompersonnel =
 3596:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
 3597:                     $privileged{$domain} = {};
 3598:                     if (keys(%dompersonnel)) {
 3599:                         foreach my $server (keys(%dompersonnel)) {
 3600:                             if (ref($dompersonnel{$server}) eq 'HASH') {
 3601:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
 3602:                                     my ($trole,$uname,$udom) = split(/:/,$user);
 3603:                                     $privileged{$udom}{$uname} = $trole;
 3604:                                 }
 3605:                             }
 3606:                         }
 3607:                     }
 3608:                 }
 3609:                 if (exists($privileged{$domain}{$username})) {
 3610:                     if (!$nothide{$username.':'.$domain}) {
 3611:                         next;
 3612:                     }
 3613:                 }
 3614:             }
 3615:         }
 3616:         if ($withsec) {
 3617:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 3618:                 $tstart.':'.$tend;
 3619:         } else {
 3620:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 3621:         }
 3622:     }
 3623:     return %returnhash;
 3624: }
 3625: 
 3626: # ----------------------------------------------------- Frontpage Announcements
 3627: #
 3628: #
 3629: 
 3630: sub postannounce {
 3631:     my ($server,$text)=@_;
 3632:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 3633:     unless ($text=~/\w/) { $text=''; }
 3634:     return &reply('setannounce:'.&escape($text),$server);
 3635: }
 3636: 
 3637: sub getannounce {
 3638: 
 3639:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 3640: 	my $announcement='';
 3641: 	while (my $line = <$fh>) { $announcement .= $line; }
 3642: 	close($fh);
 3643: 	if ($announcement=~/\w/) { 
 3644: 	    return 
 3645:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 3646:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 3647: 	} else {
 3648: 	    return '';
 3649: 	}
 3650:     } else {
 3651: 	return '';
 3652:     }
 3653: }
 3654: 
 3655: # ---------------------------------------------------------- Course ID routines
 3656: # Deal with domain's nohist_courseid.db files
 3657: #
 3658: 
 3659: sub courseidput {
 3660:     my ($domain,$storehash,$coursehome,$caller) = @_;
 3661:     return unless (ref($storehash) eq 'HASH');
 3662:     my $outcome;
 3663:     if ($caller eq 'timeonly') {
 3664:         my $cids = '';
 3665:         foreach my $item (keys(%$storehash)) {
 3666:             $cids.=&escape($item).'&';
 3667:         }
 3668:         $cids=~s/\&$//;
 3669:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 3670:                           $coursehome);       
 3671:     } else {
 3672:         my $items = '';
 3673:         foreach my $item (keys(%$storehash)) {
 3674:             $items.= &escape($item).'='.
 3675:                      &freeze_escape($$storehash{$item}).'&';
 3676:         }
 3677:         $items=~s/\&$//;
 3678:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 3679:                           $coursehome);
 3680:     }
 3681:     if ($outcome eq 'unknown_cmd') {
 3682:         my $what;
 3683:         foreach my $cid (keys(%$storehash)) {
 3684:             $what .= &escape($cid).'=';
 3685:             foreach my $item ('description','inst_code','owner','type') {
 3686:                 $what .= &escape($storehash->{$cid}{$item}).':';
 3687:             }
 3688:             $what =~ s/\:$/&/;
 3689:         }
 3690:         $what =~ s/\&$//;  
 3691:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 3692:     } else {
 3693:         return $outcome;
 3694:     }
 3695: }
 3696: 
 3697: sub courseiddump {
 3698:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 3699:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 3700:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 3701:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
 3702:     my $as_hash = 1;
 3703:     my %returnhash;
 3704:     if (!$domfilter) { $domfilter=''; }
 3705:     my %libserv = &all_library();
 3706:     foreach my $tryserver (keys(%libserv)) {
 3707:         if ( (  $hostidflag == 1 
 3708: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 3709: 	     || (!defined($hostidflag)) ) {
 3710: 
 3711: 	    if (($domfilter eq '') ||
 3712: 		(&host_domain($tryserver) eq $domfilter)) {
 3713:                 my $rep = 
 3714:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
 3715:                          $sincefilter.':'.&escape($descfilter).':'.
 3716:                          &escape($instcodefilter).':'.&escape($ownerfilter).
 3717:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
 3718:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
 3719:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
 3720:                          $showhidden.':'.$caller.':'.&escape($cloner).':'.
 3721:                          &escape($cc_clone).':'.$cloneonly.':'.
 3722:                          &escape($createdbefore).':'.&escape($createdafter).':'.
 3723:                          &escape($creationcontext).':'.$domcloner,
 3724:                          $tryserver);
 3725:                 my @pairs=split(/\&/,$rep);
 3726:                 foreach my $item (@pairs) {
 3727:                     my ($key,$value)=split(/\=/,$item,2);
 3728:                     $key = &unescape($key);
 3729:                     next if ($key =~ /^error: 2 /);
 3730:                     my $result = &thaw_unescape($value);
 3731:                     if (ref($result) eq 'HASH') {
 3732:                         $returnhash{$key}=$result;
 3733:                     } else {
 3734:                         my @responses = split(/:/,$value);
 3735:                         my @items = ('description','inst_code','owner','type');
 3736:                         for (my $i=0; $i<@responses; $i++) {
 3737:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 3738:                         }
 3739:                     }
 3740:                 }
 3741:             }
 3742:         }
 3743:     }
 3744:     return %returnhash;
 3745: }
 3746: 
 3747: sub courselastaccess {
 3748:     my ($cdom,$cnum,$hostidref) = @_;
 3749:     my %returnhash;
 3750:     if ($cdom && $cnum) {
 3751:         my $chome = &homeserver($cnum,$cdom);
 3752:         if ($chome ne 'no_host') {
 3753:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 3754:             &extract_lastaccess(\%returnhash,$rep);
 3755:         }
 3756:     } else {
 3757:         if (!$cdom) { $cdom=''; }
 3758:         my %libserv = &all_library();
 3759:         foreach my $tryserver (keys(%libserv)) {
 3760:             if (ref($hostidref) eq 'ARRAY') {
 3761:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 3762:             } 
 3763:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 3764:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 3765:                 &extract_lastaccess(\%returnhash,$rep);
 3766:             }
 3767:         }
 3768:     }
 3769:     return %returnhash;
 3770: }
 3771: 
 3772: sub extract_lastaccess {
 3773:     my ($returnhash,$rep) = @_;
 3774:     if (ref($returnhash) eq 'HASH') {
 3775:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 3776:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 3777:                  $rep eq '') {
 3778:             my @pairs=split(/\&/,$rep);
 3779:             foreach my $item (@pairs) {
 3780:                 my ($key,$value)=split(/\=/,$item,2);
 3781:                 $key = &unescape($key);
 3782:                 next if ($key =~ /^error: 2 /);
 3783:                 $returnhash->{$key} = &thaw_unescape($value);
 3784:             }
 3785:         }
 3786:     }
 3787:     return;
 3788: }
 3789: 
 3790: # ---------------------------------------------------------- DC e-mail
 3791: 
 3792: sub dcmailput {
 3793:     my ($domain,$msgid,$message,$server)=@_;
 3794:     my $status = &Apache::lonnet::critical(
 3795:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 3796:        &escape($message),$server);
 3797:     return $status;
 3798: }
 3799: 
 3800: sub dcmaildump {
 3801:     my ($dom,$startdate,$enddate,$senders) = @_;
 3802:     my %returnhash=();
 3803: 
 3804:     if (defined(&domain($dom,'primary'))) {
 3805:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 3806:                                                          &escape($enddate).':';
 3807: 	my @esc_senders=map { &escape($_)} @$senders;
 3808: 	$cmd.=&escape(join('&',@esc_senders));
 3809: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 3810:             my ($key,$value) = split(/\=/,$line,2);
 3811:             if (($key) && ($value)) {
 3812:                 $returnhash{&unescape($key)} = &unescape($value);
 3813:             }
 3814:         }
 3815:     }
 3816:     return %returnhash;
 3817: }
 3818: # ---------------------------------------------------------- Domain roles
 3819: 
 3820: sub get_domain_roles {
 3821:     my ($dom,$roles,$startdate,$enddate)=@_;
 3822:     if ((!defined($startdate)) || ($startdate eq '')) {
 3823:         $startdate = '.';
 3824:     }
 3825:     if ((!defined($enddate)) || ($enddate eq '')) {
 3826:         $enddate = '.';
 3827:     }
 3828:     my $rolelist;
 3829:     if (ref($roles) eq 'ARRAY') {
 3830:         $rolelist = join(':',@{$roles});
 3831:     }
 3832:     my %personnel = ();
 3833: 
 3834:     my %servers = &get_servers($dom,'library');
 3835:     foreach my $tryserver (keys(%servers)) {
 3836: 	%{$personnel{$tryserver}}=();
 3837: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 3838: 					    &escape($startdate).':'.
 3839: 					    &escape($enddate).':'.
 3840: 					    &escape($rolelist), $tryserver))) {
 3841: 	    my ($key,$value) = split(/\=/,$line,2);
 3842: 	    if (($key) && ($value)) {
 3843: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 3844: 	    }
 3845: 	}
 3846:     }
 3847:     return %personnel;
 3848: }
 3849: 
 3850: # ----------------------------------------------------------- Interval timing 
 3851: 
 3852: sub get_first_access {
 3853:     my ($type,$argsymb)=@_;
 3854:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 3855:     if ($argsymb) { $symb=$argsymb; }
 3856:     my ($map,$id,$res)=&decode_symb($symb);
 3857:     if ($type eq 'course') {
 3858: 	$res='course';
 3859:     } elsif ($type eq 'map') {
 3860: 	$res=&symbread($map);
 3861:     } else {
 3862: 	$res=$symb;
 3863:     }
 3864:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
 3865:     return $times{"$courseid\0$res"};
 3866: }
 3867: 
 3868: sub set_first_access {
 3869:     my ($type)=@_;
 3870:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 3871:     my ($map,$id,$res)=&decode_symb($symb);
 3872:     if ($type eq 'course') {
 3873: 	$res='course';
 3874:     } elsif ($type eq 'map') {
 3875: 	$res=&symbread($map);
 3876:     } else {
 3877: 	$res=$symb;
 3878:     }
 3879:     my $firstaccess=&get_first_access($type,$symb);
 3880:     if (!$firstaccess) {
 3881: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
 3882:     }
 3883:     return 'already_set';
 3884: }
 3885: 
 3886: # --------------------------------------------- Set Expire Date for Spreadsheet
 3887: 
 3888: sub expirespread {
 3889:     my ($uname,$udom,$stype,$usymb)=@_;
 3890:     my $cid=$env{'request.course.id'}; 
 3891:     if ($cid) {
 3892:        my $now=time;
 3893:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 3894:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 3895:                             $env{'course.'.$cid.'.num'}.
 3896: 	        	    ':nohist_expirationdates:'.
 3897:                             &escape($key).'='.$now,
 3898:                             $env{'course.'.$cid.'.home'})
 3899:     }
 3900:     return 'ok';
 3901: }
 3902: 
 3903: # ----------------------------------------------------- Devalidate Spreadsheets
 3904: 
 3905: sub devalidate {
 3906:     my ($symb,$uname,$udom)=@_;
 3907:     my $cid=$env{'request.course.id'}; 
 3908:     if ($cid) {
 3909:         # delete the stored spreadsheets for
 3910:         # - the student level sheet of this user in course's homespace
 3911:         # - the assessment level sheet for this resource 
 3912:         #   for this user in user's homespace
 3913: 	# - current conditional state info
 3914: 	my $key=$uname.':'.$udom.':';
 3915:         my $status=
 3916: 	    &del('nohist_calculatedsheets',
 3917: 		 [$key.'studentcalc:'],
 3918: 		 $env{'course.'.$cid.'.domain'},
 3919: 		 $env{'course.'.$cid.'.num'})
 3920: 		.' '.
 3921: 	    &del('nohist_calculatedsheets_'.$cid,
 3922: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 3923:         unless ($status eq 'ok ok') {
 3924:            &logthis('Could not devalidate spreadsheet '.
 3925:                     $uname.' at '.$udom.' for '.
 3926: 		    $symb.': '.$status);
 3927:         }
 3928: 	&delenv('user.state.'.$cid);
 3929:     }
 3930: }
 3931: 
 3932: sub get_scalar {
 3933:     my ($string,$end) = @_;
 3934:     my $value;
 3935:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 3936: 	$value = $1;
 3937:     } elsif ($$string =~ s/^([^&]*?)&//) {
 3938: 	$value = $1;
 3939:     }
 3940:     return &unescape($value);
 3941: }
 3942: 
 3943: sub array2str {
 3944:   my (@array) = @_;
 3945:   my $result=&arrayref2str(\@array);
 3946:   $result=~s/^__ARRAY_REF__//;
 3947:   $result=~s/__END_ARRAY_REF__$//;
 3948:   return $result;
 3949: }
 3950: 
 3951: sub arrayref2str {
 3952:   my ($arrayref) = @_;
 3953:   my $result='__ARRAY_REF__';
 3954:   foreach my $elem (@$arrayref) {
 3955:     if(ref($elem) eq 'ARRAY') {
 3956:       $result.=&arrayref2str($elem).'&';
 3957:     } elsif(ref($elem) eq 'HASH') {
 3958:       $result.=&hashref2str($elem).'&';
 3959:     } elsif(ref($elem)) {
 3960:       #print("Got a ref of ".(ref($elem))." skipping.");
 3961:     } else {
 3962:       $result.=&escape($elem).'&';
 3963:     }
 3964:   }
 3965:   $result=~s/\&$//;
 3966:   $result .= '__END_ARRAY_REF__';
 3967:   return $result;
 3968: }
 3969: 
 3970: sub hash2str {
 3971:   my (%hash) = @_;
 3972:   my $result=&hashref2str(\%hash);
 3973:   $result=~s/^__HASH_REF__//;
 3974:   $result=~s/__END_HASH_REF__$//;
 3975:   return $result;
 3976: }
 3977: 
 3978: sub hashref2str {
 3979:   my ($hashref)=@_;
 3980:   my $result='__HASH_REF__';
 3981:   foreach my $key (sort(keys(%$hashref))) {
 3982:     if (ref($key) eq 'ARRAY') {
 3983:       $result.=&arrayref2str($key).'=';
 3984:     } elsif (ref($key) eq 'HASH') {
 3985:       $result.=&hashref2str($key).'=';
 3986:     } elsif (ref($key)) {
 3987:       $result.='=';
 3988:       #print("Got a ref of ".(ref($key))." skipping.");
 3989:     } else {
 3990: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 3991:     }
 3992: 
 3993:     if(ref($hashref->{$key}) eq 'ARRAY') {
 3994:       $result.=&arrayref2str($hashref->{$key}).'&';
 3995:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 3996:       $result.=&hashref2str($hashref->{$key}).'&';
 3997:     } elsif(ref($hashref->{$key})) {
 3998:        $result.='&';
 3999:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 4000:     } else {
 4001:       $result.=&escape($hashref->{$key}).'&';
 4002:     }
 4003:   }
 4004:   $result=~s/\&$//;
 4005:   $result .= '__END_HASH_REF__';
 4006:   return $result;
 4007: }
 4008: 
 4009: sub str2hash {
 4010:     my ($string)=@_;
 4011:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 4012:     return %$hash;
 4013: }
 4014: 
 4015: sub str2hashref {
 4016:   my ($string) = @_;
 4017: 
 4018:   my %hash;
 4019: 
 4020:   if($string !~ /^__HASH_REF__/) {
 4021:       if (! ($string eq '' || !defined($string))) {
 4022: 	  $hash{'error'}='Not hash reference';
 4023:       }
 4024:       return (\%hash, $string);
 4025:   }
 4026: 
 4027:   $string =~ s/^__HASH_REF__//;
 4028: 
 4029:   while($string !~ /^__END_HASH_REF__/) {
 4030:       #key
 4031:       my $key='';
 4032:       if($string =~ /^__HASH_REF__/) {
 4033:           ($key, $string)=&str2hashref($string);
 4034:           if(defined($key->{'error'})) {
 4035:               $hash{'error'}='Bad data';
 4036:               return (\%hash, $string);
 4037:           }
 4038:       } elsif($string =~ /^__ARRAY_REF__/) {
 4039:           ($key, $string)=&str2arrayref($string);
 4040:           if($key->[0] eq 'Array reference error') {
 4041:               $hash{'error'}='Bad data';
 4042:               return (\%hash, $string);
 4043:           }
 4044:       } else {
 4045:           $string =~ s/^(.*?)=//;
 4046: 	  $key=&unescape($1);
 4047:       }
 4048:       $string =~ s/^=//;
 4049: 
 4050:       #value
 4051:       my $value='';
 4052:       if($string =~ /^__HASH_REF__/) {
 4053:           ($value, $string)=&str2hashref($string);
 4054:           if(defined($value->{'error'})) {
 4055:               $hash{'error'}='Bad data';
 4056:               return (\%hash, $string);
 4057:           }
 4058:       } elsif($string =~ /^__ARRAY_REF__/) {
 4059:           ($value, $string)=&str2arrayref($string);
 4060:           if($value->[0] eq 'Array reference error') {
 4061:               $hash{'error'}='Bad data';
 4062:               return (\%hash, $string);
 4063:           }
 4064:       } else {
 4065: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 4066:       }
 4067:       $string =~ s/^&//;
 4068: 
 4069:       $hash{$key}=$value;
 4070:   }
 4071: 
 4072:   $string =~ s/^__END_HASH_REF__//;
 4073: 
 4074:   return (\%hash, $string);
 4075: }
 4076: 
 4077: sub str2array {
 4078:     my ($string)=@_;
 4079:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 4080:     return @$array;
 4081: }
 4082: 
 4083: sub str2arrayref {
 4084:   my ($string) = @_;
 4085:   my @array;
 4086: 
 4087:   if($string !~ /^__ARRAY_REF__/) {
 4088:       if (! ($string eq '' || !defined($string))) {
 4089: 	  $array[0]='Array reference error';
 4090:       }
 4091:       return (\@array, $string);
 4092:   }
 4093: 
 4094:   $string =~ s/^__ARRAY_REF__//;
 4095: 
 4096:   while($string !~ /^__END_ARRAY_REF__/) {
 4097:       my $value='';
 4098:       if($string =~ /^__HASH_REF__/) {
 4099:           ($value, $string)=&str2hashref($string);
 4100:           if(defined($value->{'error'})) {
 4101:               $array[0] ='Array reference error';
 4102:               return (\@array, $string);
 4103:           }
 4104:       } elsif($string =~ /^__ARRAY_REF__/) {
 4105:           ($value, $string)=&str2arrayref($string);
 4106:           if($value->[0] eq 'Array reference error') {
 4107:               $array[0] ='Array reference error';
 4108:               return (\@array, $string);
 4109:           }
 4110:       } else {
 4111: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 4112:       }
 4113:       $string =~ s/^&//;
 4114: 
 4115:       push(@array, $value);
 4116:   }
 4117: 
 4118:   $string =~ s/^__END_ARRAY_REF__//;
 4119: 
 4120:   return (\@array, $string);
 4121: }
 4122: 
 4123: # -------------------------------------------------------------------Temp Store
 4124: 
 4125: sub tmpreset {
 4126:   my ($symb,$namespace,$domain,$stuname) = @_;
 4127:   if (!$symb) {
 4128:     $symb=&symbread();
 4129:     if (!$symb) { $symb= $env{'request.url'}; }
 4130:   }
 4131:   $symb=escape($symb);
 4132: 
 4133:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4134:   $namespace=~s/\//\_/g;
 4135:   $namespace=~s/\W//g;
 4136: 
 4137:   if (!$domain) { $domain=$env{'user.domain'}; }
 4138:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4139:   if ($domain eq 'public' && $stuname eq 'public') {
 4140:       $stuname=$ENV{'REMOTE_ADDR'};
 4141:   }
 4142:   my $path=LONCAPA::tempdir();
 4143:   my %hash;
 4144:   if (tie(%hash,'GDBM_File',
 4145: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4146: 	  &GDBM_WRCREAT(),0640)) {
 4147:     foreach my $key (keys(%hash)) {
 4148:       if ($key=~ /:$symb/) {
 4149: 	delete($hash{$key});
 4150:       }
 4151:     }
 4152:   }
 4153: }
 4154: 
 4155: sub tmpstore {
 4156:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4157: 
 4158:   if (!$symb) {
 4159:     $symb=&symbread();
 4160:     if (!$symb) { $symb= $env{'request.url'}; }
 4161:   }
 4162:   $symb=escape($symb);
 4163: 
 4164:   if (!$namespace) {
 4165:     # I don't think we would ever want to store this for a course.
 4166:     # it seems this will only be used if we don't have a course.
 4167:     #$namespace=$env{'request.course.id'};
 4168:     #if (!$namespace) {
 4169:       $namespace=$env{'request.state'};
 4170:     #}
 4171:   }
 4172:   $namespace=~s/\//\_/g;
 4173:   $namespace=~s/\W//g;
 4174:   if (!$domain) { $domain=$env{'user.domain'}; }
 4175:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4176:   if ($domain eq 'public' && $stuname eq 'public') {
 4177:       $stuname=$ENV{'REMOTE_ADDR'};
 4178:   }
 4179:   my $now=time;
 4180:   my %hash;
 4181:   my $path=LONCAPA::tempdir();
 4182:   if (tie(%hash,'GDBM_File',
 4183: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4184: 	  &GDBM_WRCREAT(),0640)) {
 4185:     $hash{"version:$symb"}++;
 4186:     my $version=$hash{"version:$symb"};
 4187:     my $allkeys=''; 
 4188:     foreach my $key (keys(%$storehash)) {
 4189:       $allkeys.=$key.':';
 4190:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 4191:     }
 4192:     $hash{"$version:$symb:timestamp"}=$now;
 4193:     $allkeys.='timestamp';
 4194:     $hash{"$version:keys:$symb"}=$allkeys;
 4195:     if (untie(%hash)) {
 4196:       return 'ok';
 4197:     } else {
 4198:       return "error:$!";
 4199:     }
 4200:   } else {
 4201:     return "error:$!";
 4202:   }
 4203: }
 4204: 
 4205: # -----------------------------------------------------------------Temp Restore
 4206: 
 4207: sub tmprestore {
 4208:   my ($symb,$namespace,$domain,$stuname) = @_;
 4209: 
 4210:   if (!$symb) {
 4211:     $symb=&symbread();
 4212:     if (!$symb) { $symb= $env{'request.url'}; }
 4213:   }
 4214:   $symb=escape($symb);
 4215: 
 4216:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4217: 
 4218:   if (!$domain) { $domain=$env{'user.domain'}; }
 4219:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4220:   if ($domain eq 'public' && $stuname eq 'public') {
 4221:       $stuname=$ENV{'REMOTE_ADDR'};
 4222:   }
 4223:   my %returnhash;
 4224:   $namespace=~s/\//\_/g;
 4225:   $namespace=~s/\W//g;
 4226:   my %hash;
 4227:   my $path=LONCAPA::tempdir();
 4228:   if (tie(%hash,'GDBM_File',
 4229: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4230: 	  &GDBM_READER(),0640)) {
 4231:     my $version=$hash{"version:$symb"};
 4232:     $returnhash{'version'}=$version;
 4233:     my $scope;
 4234:     for ($scope=1;$scope<=$version;$scope++) {
 4235:       my $vkeys=$hash{"$scope:keys:$symb"};
 4236:       my @keys=split(/:/,$vkeys);
 4237:       my $key;
 4238:       $returnhash{"$scope:keys"}=$vkeys;
 4239:       foreach $key (@keys) {
 4240: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4241: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4242:       }
 4243:     }
 4244:     if (!(untie(%hash))) {
 4245:       return "error:$!";
 4246:     }
 4247:   } else {
 4248:     return "error:$!";
 4249:   }
 4250:   return %returnhash;
 4251: }
 4252: 
 4253: # ----------------------------------------------------------------------- Store
 4254: 
 4255: sub store {
 4256:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4257:     my $home='';
 4258: 
 4259:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4260: 
 4261:     $symb=&symbclean($symb);
 4262:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 4263: 
 4264:     if (!$domain) { $domain=$env{'user.domain'}; }
 4265:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4266: 
 4267:     &devalidate($symb,$stuname,$domain);
 4268: 
 4269:     $symb=escape($symb);
 4270:     if (!$namespace) { 
 4271:        unless ($namespace=$env{'request.course.id'}) { 
 4272:           return ''; 
 4273:        } 
 4274:     }
 4275:     if (!$home) { $home=$env{'user.home'}; }
 4276: 
 4277:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 4278:     $$storehash{'host'}=$perlvar{'lonHostID'};
 4279: 
 4280:     my $namevalue='';
 4281:     foreach my $key (keys(%$storehash)) {
 4282:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4283:     }
 4284:     $namevalue=~s/\&$//;
 4285:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 4286:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 4287: }
 4288: 
 4289: # -------------------------------------------------------------- Critical Store
 4290: 
 4291: sub cstore {
 4292:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4293:     my $home='';
 4294: 
 4295:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4296: 
 4297:     $symb=&symbclean($symb);
 4298:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 4299: 
 4300:     if (!$domain) { $domain=$env{'user.domain'}; }
 4301:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4302: 
 4303:     &devalidate($symb,$stuname,$domain);
 4304: 
 4305:     $symb=escape($symb);
 4306:     if (!$namespace) { 
 4307:        unless ($namespace=$env{'request.course.id'}) { 
 4308:           return ''; 
 4309:        } 
 4310:     }
 4311:     if (!$home) { $home=$env{'user.home'}; }
 4312: 
 4313:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 4314:     $$storehash{'host'}=$perlvar{'lonHostID'};
 4315: 
 4316:     my $namevalue='';
 4317:     foreach my $key (keys(%$storehash)) {
 4318:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4319:     }
 4320:     $namevalue=~s/\&$//;
 4321:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 4322:     return critical
 4323:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 4324: }
 4325: 
 4326: # --------------------------------------------------------------------- Restore
 4327: 
 4328: sub restore {
 4329:     my ($symb,$namespace,$domain,$stuname) = @_;
 4330:     my $home='';
 4331: 
 4332:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4333: 
 4334:     if (!$symb) {
 4335:       unless ($symb=escape(&symbread())) { return ''; }
 4336:     } else {
 4337:       $symb=&escape(&symbclean($symb));
 4338:     }
 4339:     if (!$namespace) { 
 4340:        unless ($namespace=$env{'request.course.id'}) { 
 4341:           return ''; 
 4342:        } 
 4343:     }
 4344:     if (!$domain) { $domain=$env{'user.domain'}; }
 4345:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4346:     if (!$home) { $home=$env{'user.home'}; }
 4347:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 4348: 
 4349:     my %returnhash=();
 4350:     foreach my $line (split(/\&/,$answer)) {
 4351: 	my ($name,$value)=split(/\=/,$line);
 4352:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 4353:     }
 4354:     my $version;
 4355:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 4356:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 4357:           $returnhash{$item}=$returnhash{$version.':'.$item};
 4358:        }
 4359:     }
 4360:     return %returnhash;
 4361: }
 4362: 
 4363: # ---------------------------------------------------------- Course Description
 4364: #
 4365: #  
 4366: 
 4367: sub coursedescription {
 4368:     my ($courseid,$args)=@_;
 4369:     $courseid=~s/^\///;
 4370:     $courseid=~s/\_/\//g;
 4371:     my ($cdomain,$cnum)=split(/\//,$courseid);
 4372:     my $chome=&homeserver($cnum,$cdomain);
 4373:     my $normalid=$cdomain.'_'.$cnum;
 4374:     # need to always cache even if we get errors otherwise we keep 
 4375:     # trying and trying and trying to get the course description.
 4376:     my %envhash=();
 4377:     my %returnhash=();
 4378:     
 4379:     my $expiretime=600;
 4380:     if ($env{'request.course.id'} eq $normalid) {
 4381: 	$expiretime=120;
 4382:     }
 4383: 
 4384:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 4385:     if (!$args->{'freshen_cache'}
 4386: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 4387: 	foreach my $key (keys(%env)) {
 4388: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 4389: 	    my ($setting) = $1;
 4390: 	    $returnhash{$setting} = $env{$key};
 4391: 	}
 4392: 	return %returnhash;
 4393:     }
 4394: 
 4395:     # get the data again
 4396: 
 4397:     if (!$args->{'one_time'}) {
 4398: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 4399:     }
 4400: 
 4401:     if ($chome ne 'no_host') {
 4402:        %returnhash=&dump('environment',$cdomain,$cnum);
 4403:        if (!exists($returnhash{'con_lost'})) {
 4404: 	   my $username = $env{'user.name'}; # Defult username
 4405: 	   if(defined $args->{'user'}) {
 4406: 	       $username = $args->{'user'};
 4407: 	   }
 4408:            $returnhash{'home'}= $chome;
 4409: 	   $returnhash{'domain'} = $cdomain;
 4410: 	   $returnhash{'num'} = $cnum;
 4411:            if (!defined($returnhash{'type'})) {
 4412:                $returnhash{'type'} = 'Course';
 4413:            }
 4414:            while (my ($name,$value) = each %returnhash) {
 4415:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 4416:            }
 4417:            $returnhash{'url'}=&clutter($returnhash{'url'});
 4418:            $returnhash{'fn'}=LONCAPA::tempdir() .
 4419: 	       $username.'_'.$cdomain.'_'.$cnum;
 4420:            $envhash{'course.'.$normalid.'.home'}=$chome;
 4421:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 4422:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 4423:        }
 4424:     }
 4425:     if (!$args->{'one_time'}) {
 4426: 	&appenv(\%envhash);
 4427:     }
 4428:     return %returnhash;
 4429: }
 4430: 
 4431: sub update_released_required {
 4432:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 4433:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 4434:         $cid = $env{'request.course.id'};
 4435:         $cdom = $env{'course.'.$cid.'.domain'};
 4436:         $cnum = $env{'course.'.$cid.'.num'};
 4437:         $chome = $env{'course.'.$cid.'.home'};
 4438:     }
 4439:     if ($needsrelease) {
 4440:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 4441:         my $needsupdate;
 4442:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 4443:             $needsupdate = 1;
 4444:         } else {
 4445:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 4446:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 4447:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 4448:                 $needsupdate = 1;
 4449:             }
 4450:         }
 4451:         if ($needsupdate) {
 4452:             my %needshash = (
 4453:                              'internal.releaserequired' => $needsrelease,
 4454:                             );
 4455:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 4456:             if ($putresult eq 'ok') {
 4457:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 4458:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 4459:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 4460:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 4461:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 4462:                 }
 4463:             }
 4464:         }
 4465:     }
 4466:     return;
 4467: }
 4468: 
 4469: # -------------------------------------------------See if a user is privileged
 4470: 
 4471: sub privileged {
 4472:     my ($username,$domain)=@_;
 4473:     my $rolesdump=&reply("dump:$domain:$username:roles",
 4474: 			&homeserver($username,$domain));
 4475:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
 4476:         ($rolesdump =~ /^error:/)) {
 4477:         return 0;
 4478:     }
 4479:     my $now=time;
 4480:     if ($rolesdump ne '') {
 4481:         foreach my $entry (split(/&/,$rolesdump)) {
 4482: 	    if ($entry!~/^rolesdef_/) {
 4483: 		my ($area,$role)=split(/=/,$entry);
 4484: 		$area=~s/\_\w\w$//;
 4485: 		my ($trole,$tend,$tstart)=split(/_/,$role);
 4486: 		if (($trole eq 'dc') || ($trole eq 'su')) {
 4487: 		    my $active=1;
 4488: 		    if ($tend) {
 4489: 			if ($tend<$now) { $active=0; }
 4490: 		    }
 4491: 		    if ($tstart) {
 4492: 			if ($tstart>$now) { $active=0; }
 4493: 		    }
 4494: 		    if ($active) { return 1; }
 4495: 		}
 4496: 	    }
 4497: 	}
 4498:     }
 4499:     return 0;
 4500: }
 4501: 
 4502: # -------------------------------------------------------- Get user privileges
 4503: 
 4504: sub rolesinit {
 4505:     my ($domain,$username,$authhost)=@_;
 4506:     my $now=time;
 4507:     my %userroles = ('user.login.time' => $now);
 4508:     my $extra = &freeze_escape({'skipcheck' => 1});
 4509:     my $rolesdump=reply("dump:$domain:$username:roles:.::$extra",$authhost);
 4510:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
 4511:         ($rolesdump =~ /^error:/)) {
 4512:         return \%userroles;
 4513:     }
 4514:     my %allroles=();
 4515:     my %allgroups=();   
 4516: 
 4517:     if ($rolesdump ne '') {
 4518:         foreach my $entry (split(/&/,$rolesdump)) {
 4519: 	  if ($entry!~/^rolesdef_/) {
 4520:             my ($area,$role)=split(/=/,$entry);
 4521: 	    $area=~s/\_\w\w$//;
 4522:             my ($trole,$tend,$tstart,$group_privs);
 4523: 	    if ($role=~/^cr/) { 
 4524: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 4525: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
 4526: 		    ($tend,$tstart)=split('_',$trest);
 4527: 		} else {
 4528: 		    $trole=$role;
 4529: 		}
 4530:             } elsif ($role =~ m|^gr/|) {
 4531:                 ($trole,$tend,$tstart) = split(/_/,$role);
 4532:                 next if ($tstart eq '-1');
 4533:                 ($trole,$group_privs) = split(/\//,$trole);
 4534:                 $group_privs = &unescape($group_privs);
 4535: 	    } else {
 4536: 		($trole,$tend,$tstart)=split(/_/,$role);
 4537: 	    }
 4538: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 4539: 					 $username);
 4540: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 4541:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
 4542:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
 4543:             if (($area ne '') && ($trole ne '')) {
 4544: 		my $spec=$trole.'.'.$area;
 4545: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
 4546: 		if ($trole =~ /^cr\//) {
 4547:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 4548:                 } elsif ($trole eq 'gr') {
 4549:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 4550: 		} else {
 4551:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 4552: 		}
 4553:             }
 4554:           }
 4555:         }
 4556:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
 4557:         $userroles{'user.adv'}    = $adv;
 4558: 	$userroles{'user.author'} = $author;
 4559:         $env{'user.adv'}=$adv;
 4560:     }
 4561:     return \%userroles;  
 4562: }
 4563: 
 4564: sub set_arearole {
 4565:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
 4566: # log the associated role with the area
 4567:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 4568:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 4569: }
 4570: 
 4571: sub custom_roleprivs {
 4572:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 4573:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 4574:     my $homsvr=homeserver($rauthor,$rdomain);
 4575:     if (&hostname($homsvr) ne '') {
 4576:         my ($rdummy,$roledef)=
 4577:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 4578:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 4579:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 4580:             if (defined($syspriv)) {
 4581:                 if ($trest =~ /^$match_community$/) {
 4582:                     $syspriv =~ s/bre\&S//; 
 4583:                 }
 4584:                 $$allroles{'cm./'}.=':'.$syspriv;
 4585:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 4586:             }
 4587:             if ($tdomain ne '') {
 4588:                 if (defined($dompriv)) {
 4589:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 4590:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 4591:                 }
 4592:                 if (($trest ne '') && (defined($coursepriv))) {
 4593:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 4594:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 4595:                 }
 4596:             }
 4597:         }
 4598:     }
 4599: }
 4600: 
 4601: sub group_roleprivs {
 4602:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 4603:     my $access = 1;
 4604:     my $now = time;
 4605:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 4606:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 4607:     if ($access) {
 4608:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 4609:         $$allgroups{$course}{$group} .=':'.$group_privs;
 4610:     }
 4611: }
 4612: 
 4613: sub standard_roleprivs {
 4614:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 4615:     if (defined($pr{$trole.':s'})) {
 4616:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 4617:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 4618:     }
 4619:     if ($tdomain ne '') {
 4620:         if (defined($pr{$trole.':d'})) {
 4621:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 4622:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 4623:         }
 4624:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 4625:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 4626:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 4627:         }
 4628:     }
 4629: }
 4630: 
 4631: sub set_userprivs {
 4632:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 4633:     my $author=0;
 4634:     my $adv=0;
 4635:     my %grouproles = ();
 4636:     if (keys(%{$allgroups}) > 0) {
 4637:         my @groupkeys; 
 4638:         foreach my $role (keys(%{$allroles})) {
 4639:             push(@groupkeys,$role);
 4640:         }
 4641:         if (ref($groups_roles) eq 'HASH') {
 4642:             foreach my $key (keys(%{$groups_roles})) {
 4643:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 4644:                     push(@groupkeys,$key);
 4645:                 }
 4646:             }
 4647:         }
 4648:         if (@groupkeys > 0) {
 4649:             foreach my $role (@groupkeys) {
 4650:                 my ($trole,$area,$sec,$extendedarea);
 4651:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 4652:                     $trole = $1;
 4653:                     $area = $2;
 4654:                     $sec = $3;
 4655:                     $extendedarea = $area.$sec;
 4656:                     if (exists($$allgroups{$area})) {
 4657:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 4658:                             my $spec = $trole.'.'.$extendedarea;
 4659:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 4660:                                                 $$allgroups{$area}{$group};
 4661:                         }
 4662:                     }
 4663:                 }
 4664:             }
 4665:         }
 4666:     }
 4667:     foreach my $group (keys(%grouproles)) {
 4668:         $$allroles{$group} = $grouproles{$group};
 4669:     }
 4670:     foreach my $role (keys(%{$allroles})) {
 4671:         my %thesepriv;
 4672:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 4673:         foreach my $item (split(/:/,$$allroles{$role})) {
 4674:             if ($item ne '') {
 4675:                 my ($privilege,$restrictions)=split(/&/,$item);
 4676:                 if ($restrictions eq '') {
 4677:                     $thesepriv{$privilege}='F';
 4678:                 } elsif ($thesepriv{$privilege} ne 'F') {
 4679:                     $thesepriv{$privilege}.=$restrictions;
 4680:                 }
 4681:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 4682:             }
 4683:         }
 4684:         my $thesestr='';
 4685:         foreach my $priv (sort(keys(%thesepriv))) {
 4686: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 4687: 	}
 4688:         $userroles->{'user.priv.'.$role} = $thesestr;
 4689:     }
 4690:     return ($author,$adv);
 4691: }
 4692: 
 4693: sub role_status {
 4694:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 4695:     my @pwhere = ();
 4696:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 4697:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
 4698:         unless (!defined($$role) || $$role eq '') {
 4699:             $$where=join('.',@pwhere);
 4700:             $$trolecode=$$role.'.'.$$where;
 4701:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 4702:             $$tstatus='is';
 4703:             if ($$tstart && $$tstart>$update) {
 4704:                 $$tstatus='future';
 4705:                 if ($$tstart<$now) {
 4706:                     if ($$tstart && $$tstart>$refresh) {
 4707:                         if (($$where ne '') && ($$role ne '')) {
 4708:                             my (%allroles,%allgroups,$group_privs,
 4709:                                 %groups_roles,@rolecodes);
 4710:                             my %userroles = (
 4711:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 4712:                             );
 4713:                             @rolecodes = ('cm'); 
 4714:                             my $spec=$$role.'.'.$$where;
 4715:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 4716:                             if ($$role =~ /^cr\//) {
 4717:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 4718:                                 push(@rolecodes,'cr');
 4719:                             } elsif ($$role eq 'gr') {
 4720:                                 push(@rolecodes,$$role);
 4721:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 4722:                                                     $env{'user.name'});
 4723:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 4724:                                 (undef,my $group_privs) = split(/\//,$trole);
 4725:                                 $group_privs = &unescape($group_privs);
 4726:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 4727:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 4728:                                 &get_groups_roles($tdomain,$trest,
 4729:                                                   \%course_roles,\@rolecodes,
 4730:                                                   \%groups_roles);
 4731:                             } else {
 4732:                                 push(@rolecodes,$$role);
 4733:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 4734:                             }
 4735:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
 4736:                             &appenv(\%userroles,\@rolecodes);
 4737:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 4738:                         }
 4739:                     }
 4740:                     $$tstatus = 'is';
 4741:                 }
 4742:             }
 4743:             if ($$tend) {
 4744:                 if ($$tend<$update) {
 4745:                     $$tstatus='expired';
 4746:                 } elsif ($$tend<$now) {
 4747:                     $$tstatus='will_not';
 4748:                 }
 4749:             }
 4750:         }
 4751:     }
 4752: }
 4753: 
 4754: sub get_groups_roles {
 4755:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 4756:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 4757:                   (ref($rolecodes) eq 'ARRAY') && 
 4758:                   (ref($groups_roles) eq 'HASH')); 
 4759:     if (keys(%{$cdom_courseroles}) > 0) {
 4760:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 4761:         if ($cdom ne '' && $cnum ne '') {
 4762:             foreach my $key (keys(%{$cdom_courseroles})) {
 4763:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 4764:                     my $crsrole = $1;
 4765:                     my $crssec = $2;
 4766:                     if ($crsrole =~ /^cr/) {
 4767:                         unless (grep(/^cr$/,@{$rolecodes})) {
 4768:                             push(@{$rolecodes},'cr');
 4769:                         }
 4770:                     } else {
 4771:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 4772:                             push(@{$rolecodes},$crsrole);
 4773:                         }
 4774:                     }
 4775:                     my $rolekey = "$crsrole./$cdom/$cnum";
 4776:                     if ($crssec ne '') {
 4777:                         $rolekey .= "/$crssec";
 4778:                     }
 4779:                     $rolekey .= './';
 4780:                     $groups_roles->{$rolekey} = $rolecodes;
 4781:                 }
 4782:             }
 4783:         }
 4784:     }
 4785:     return;
 4786: }
 4787: 
 4788: sub delete_env_groupprivs {
 4789:     my ($where,$courseroles,$possroles) = @_;
 4790:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 4791:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 4792:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 4793:         %{$courseroles->{$udom}} =
 4794:             &get_my_roles('','','userroles',['active'],
 4795:                           $possroles,[$udom],1);
 4796:     }
 4797:     if (ref($courseroles->{$udom}) eq 'HASH') {
 4798:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 4799:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 4800:             my $area = '/'.$cdom.'/'.$cnum;
 4801:             my $privkey = "user.priv.$crsrole.$area";
 4802:             if ($crssec ne '') {
 4803:                 $privkey .= '/'.$crssec;
 4804:             }
 4805:             $privkey .= ".$area/$group";
 4806:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 4807:         }
 4808:     }
 4809:     return;
 4810: }
 4811: 
 4812: sub check_adhoc_privs {
 4813:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
 4814:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 4815:     if ($env{$cckey}) {
 4816:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 4817:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 4818:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 4819:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 4820:         }
 4821:     } else {
 4822:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 4823:     }
 4824: }
 4825: 
 4826: sub set_adhoc_privileges {
 4827: # role can be cc or ca
 4828:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
 4829:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 4830:     my $spec = $role.'.'.$area;
 4831:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 4832:                                   $env{'user.name'});
 4833:     my %ccrole = ();
 4834:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
 4835:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
 4836:     &appenv(\%userroles,[$role,'cm']);
 4837:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 4838:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
 4839:         &appenv( {'request.role'        => $spec,
 4840:                   'request.role.domain' => $dcdom,
 4841:                   'request.course.sec'  => ''
 4842:                  }
 4843:                );
 4844:         my $tadv=0;
 4845:         if (&allowed('adv') eq 'F') { $tadv=1; }
 4846:         &appenv({'request.role.adv'    => $tadv});
 4847:     }
 4848: }
 4849: 
 4850: # --------------------------------------------------------------- get interface
 4851: 
 4852: sub get {
 4853:    my ($namespace,$storearr,$udomain,$uname)=@_;
 4854:    my $items='';
 4855:    foreach my $item (@$storearr) {
 4856:        $items.=&escape($item).'&';
 4857:    }
 4858:    $items=~s/\&$//;
 4859:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4860:    if (!$uname) { $uname=$env{'user.name'}; }
 4861:    my $uhome=&homeserver($uname,$udomain);
 4862: 
 4863:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 4864:    my @pairs=split(/\&/,$rep);
 4865:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 4866:      return @pairs;
 4867:    }
 4868:    my %returnhash=();
 4869:    my $i=0;
 4870:    foreach my $item (@$storearr) {
 4871:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 4872:       $i++;
 4873:    }
 4874:    return %returnhash;
 4875: }
 4876: 
 4877: # --------------------------------------------------------------- del interface
 4878: 
 4879: sub del {
 4880:    my ($namespace,$storearr,$udomain,$uname)=@_;
 4881:    my $items='';
 4882:    foreach my $item (@$storearr) {
 4883:        $items.=&escape($item).'&';
 4884:    }
 4885: 
 4886:    $items=~s/\&$//;
 4887:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4888:    if (!$uname) { $uname=$env{'user.name'}; }
 4889:    my $uhome=&homeserver($uname,$udomain);
 4890:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 4891: }
 4892: 
 4893: # -------------------------------------------------------------- dump interface
 4894: 
 4895: sub dump {
 4896:     my ($namespace,$udomain,$uname,$regexp,$range,$extra)=@_;
 4897:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 4898:     if (!$uname) { $uname=$env{'user.name'}; }
 4899:     my $uhome=&homeserver($uname,$udomain);
 4900:     if ($regexp) {
 4901: 	$regexp=&escape($regexp);
 4902:     } else {
 4903: 	$regexp='.';
 4904:     }
 4905:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range:$extra",$uhome);
 4906:     my @pairs=split(/\&/,$rep);
 4907:     my %returnhash=();
 4908:     if (!($rep =~ /^error/ )) {
 4909: 	foreach my $item (@pairs) {
 4910: 	    my ($key,$value)=split(/=/,$item,2);
 4911: 	    $key = &unescape($key);
 4912: 	    next if ($key =~ /^error: 2 /);
 4913: 	    $returnhash{$key}=&thaw_unescape($value);
 4914: 	}
 4915:     }
 4916:     return %returnhash;
 4917: }
 4918: 
 4919: 
 4920: # --------------------------------------------------------- dumpstore interface
 4921: 
 4922: sub dumpstore {
 4923:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 4924:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4925:    if (!$uname) { $uname=$env{'user.name'}; }
 4926:    my $uhome=&homeserver($uname,$udomain);
 4927:    if ($regexp) {
 4928:        $regexp=&escape($regexp);
 4929:    } else {
 4930:        $regexp='.';
 4931:    }
 4932:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 4933:    my @pairs=split(/\&/,$rep);
 4934:    my %returnhash=();
 4935:    foreach my $item (@pairs) {
 4936:        my ($key,$value)=split(/=/,$item,2);
 4937:        next if ($key =~ /^error: 2 /);
 4938:        $returnhash{$key}=&thaw_unescape($value);
 4939:    }
 4940:    return %returnhash;
 4941: }
 4942: 
 4943: # -------------------------------------------------------------- keys interface
 4944: 
 4945: sub getkeys {
 4946:    my ($namespace,$udomain,$uname)=@_;
 4947:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4948:    if (!$uname) { $uname=$env{'user.name'}; }
 4949:    my $uhome=&homeserver($uname,$udomain);
 4950:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 4951:    my @keyarray=();
 4952:    foreach my $key (split(/\&/,$rep)) {
 4953:       next if ($key =~ /^error: 2 /);
 4954:       push(@keyarray,&unescape($key));
 4955:    }
 4956:    return @keyarray;
 4957: }
 4958: 
 4959: # --------------------------------------------------------------- currentdump
 4960: sub currentdump {
 4961:    my ($courseid,$sdom,$sname)=@_;
 4962:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 4963:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 4964:    $sname    = $env{'user.name'}         if (! defined($sname));
 4965:    my $uhome = &homeserver($sname,$sdom);
 4966:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 4967:    return if ($rep =~ /^(error:|no_such_host)/);
 4968:    #
 4969:    my %returnhash=();
 4970:    #
 4971:    if ($rep eq "unknown_cmd") { 
 4972:        # an old lond will not know currentdump
 4973:        # Do a dump and make it look like a currentdump
 4974:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 4975:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 4976:        my %hash = @tmp;
 4977:        @tmp=();
 4978:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 4979:    } else {
 4980:        my @pairs=split(/\&/,$rep);
 4981:        foreach my $pair (@pairs) {
 4982:            my ($key,$value)=split(/=/,$pair,2);
 4983:            my ($symb,$param) = split(/:/,$key);
 4984:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 4985:                                                         &thaw_unescape($value);
 4986:        }
 4987:    }
 4988:    return %returnhash;
 4989: }
 4990: 
 4991: sub convert_dump_to_currentdump{
 4992:     my %hash = %{shift()};
 4993:     my %returnhash;
 4994:     # Code ripped from lond, essentially.  The only difference
 4995:     # here is the unescaping done by lonnet::dump().  Conceivably
 4996:     # we might run in to problems with parameter names =~ /^v\./
 4997:     while (my ($key,$value) = each(%hash)) {
 4998:         my ($v,$symb,$param) = split(/:/,$key);
 4999: 	$symb  = &unescape($symb);
 5000: 	$param = &unescape($param);
 5001:         next if ($v eq 'version' || $symb eq 'keys');
 5002:         next if (exists($returnhash{$symb}) &&
 5003:                  exists($returnhash{$symb}->{$param}) &&
 5004:                  $returnhash{$symb}->{'v.'.$param} > $v);
 5005:         $returnhash{$symb}->{$param}=$value;
 5006:         $returnhash{$symb}->{'v.'.$param}=$v;
 5007:     }
 5008:     #
 5009:     # Remove all of the keys in the hashes which keep track of
 5010:     # the version of the parameter.
 5011:     while (my ($symb,$param_hash) = each(%returnhash)) {
 5012:         # use a foreach because we are going to delete from the hash.
 5013:         foreach my $key (keys(%$param_hash)) {
 5014:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 5015:         }
 5016:     }
 5017:     return \%returnhash;
 5018: }
 5019: 
 5020: # ------------------------------------------------------ critical inc interface
 5021: 
 5022: sub cinc {
 5023:     return &inc(@_,'critical');
 5024: }
 5025: 
 5026: # --------------------------------------------------------------- inc interface
 5027: 
 5028: sub inc {
 5029:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 5030:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5031:     if (!$uname) { $uname=$env{'user.name'}; }
 5032:     my $uhome=&homeserver($uname,$udomain);
 5033:     my $items='';
 5034:     if (! ref($store)) {
 5035:         # got a single value, so use that instead
 5036:         $items = &escape($store).'=&';
 5037:     } elsif (ref($store) eq 'SCALAR') {
 5038:         $items = &escape($$store).'=&';        
 5039:     } elsif (ref($store) eq 'ARRAY') {
 5040:         $items = join('=&',map {&escape($_);} @{$store});
 5041:     } elsif (ref($store) eq 'HASH') {
 5042:         while (my($key,$value) = each(%{$store})) {
 5043:             $items.= &escape($key).'='.&escape($value).'&';
 5044:         }
 5045:     }
 5046:     $items=~s/\&$//;
 5047:     if ($critical) {
 5048: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 5049:     } else {
 5050: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 5051:     }
 5052: }
 5053: 
 5054: # --------------------------------------------------------------- put interface
 5055: 
 5056: sub put {
 5057:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5058:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5059:    if (!$uname) { $uname=$env{'user.name'}; }
 5060:    my $uhome=&homeserver($uname,$udomain);
 5061:    my $items='';
 5062:    foreach my $item (keys(%$storehash)) {
 5063:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5064:    }
 5065:    $items=~s/\&$//;
 5066:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5067: }
 5068: 
 5069: # ------------------------------------------------------------ newput interface
 5070: 
 5071: sub newput {
 5072:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5073:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5074:    if (!$uname) { $uname=$env{'user.name'}; }
 5075:    my $uhome=&homeserver($uname,$udomain);
 5076:    my $items='';
 5077:    foreach my $key (keys(%$storehash)) {
 5078:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 5079:    }
 5080:    $items=~s/\&$//;
 5081:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 5082: }
 5083: 
 5084: # ---------------------------------------------------------  putstore interface
 5085: 
 5086: sub putstore {
 5087:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 5088:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5089:    if (!$uname) { $uname=$env{'user.name'}; }
 5090:    my $uhome=&homeserver($uname,$udomain);
 5091:    my $items='';
 5092:    foreach my $key (keys(%$storehash)) {
 5093:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 5094:    }
 5095:    $items=~s/\&$//;
 5096:    my $esc_symb=&escape($symb);
 5097:    my $esc_v=&escape($version);
 5098:    my $reply =
 5099:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 5100: 	      $uhome);
 5101:    if ($reply eq 'unknown_cmd') {
 5102:        # gfall back to way things use to be done
 5103:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 5104: 			    $uname);
 5105:    }
 5106:    return $reply;
 5107: }
 5108: 
 5109: sub old_putstore {
 5110:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 5111:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5112:     if (!$uname) { $uname=$env{'user.name'}; }
 5113:     my $uhome=&homeserver($uname,$udomain);
 5114:     my %newstorehash;
 5115:     foreach my $item (keys(%$storehash)) {
 5116: 	my $key = $version.':'.&escape($symb).':'.$item;
 5117: 	$newstorehash{$key} = $storehash->{$item};
 5118:     }
 5119:     my $items='';
 5120:     my %allitems = ();
 5121:     foreach my $item (keys(%newstorehash)) {
 5122: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 5123: 	    my $key = $1.':keys:'.$2;
 5124: 	    $allitems{$key} .= $3.':';
 5125: 	}
 5126: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 5127:     }
 5128:     foreach my $item (keys(%allitems)) {
 5129: 	$allitems{$item} =~ s/\:$//;
 5130: 	$items.= $item.'='.$allitems{$item}.'&';
 5131:     }
 5132:     $items=~s/\&$//;
 5133:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5134: }
 5135: 
 5136: # ------------------------------------------------------ critical put interface
 5137: 
 5138: sub cput {
 5139:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5140:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5141:    if (!$uname) { $uname=$env{'user.name'}; }
 5142:    my $uhome=&homeserver($uname,$udomain);
 5143:    my $items='';
 5144:    foreach my $item (keys(%$storehash)) {
 5145:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5146:    }
 5147:    $items=~s/\&$//;
 5148:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 5149: }
 5150: 
 5151: # -------------------------------------------------------------- eget interface
 5152: 
 5153: sub eget {
 5154:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5155:    my $items='';
 5156:    foreach my $item (@$storearr) {
 5157:        $items.=&escape($item).'&';
 5158:    }
 5159:    $items=~s/\&$//;
 5160:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5161:    if (!$uname) { $uname=$env{'user.name'}; }
 5162:    my $uhome=&homeserver($uname,$udomain);
 5163:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 5164:    my @pairs=split(/\&/,$rep);
 5165:    my %returnhash=();
 5166:    my $i=0;
 5167:    foreach my $item (@$storearr) {
 5168:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 5169:       $i++;
 5170:    }
 5171:    return %returnhash;
 5172: }
 5173: 
 5174: # ------------------------------------------------------------ tmpput interface
 5175: sub tmpput {
 5176:     my ($storehash,$server,$context)=@_;
 5177:     my $items='';
 5178:     foreach my $item (keys(%$storehash)) {
 5179: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5180:     }
 5181:     $items=~s/\&$//;
 5182:     if (defined($context)) {
 5183:         $items .= ':'.&escape($context);
 5184:     }
 5185:     return &reply("tmpput:$items",$server);
 5186: }
 5187: 
 5188: # ------------------------------------------------------------ tmpget interface
 5189: sub tmpget {
 5190:     my ($token,$server)=@_;
 5191:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 5192:     my $rep=&reply("tmpget:$token",$server);
 5193:     my %returnhash;
 5194:     foreach my $item (split(/\&/,$rep)) {
 5195: 	my ($key,$value)=split(/=/,$item);
 5196:         next if ($key =~ /^error: 2 /);
 5197: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 5198:     }
 5199:     return %returnhash;
 5200: }
 5201: 
 5202: # ------------------------------------------------------------ tmpdel interface
 5203: sub tmpdel {
 5204:     my ($token,$server)=@_;
 5205:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 5206:     return &reply("tmpdel:$token",$server);
 5207: }
 5208: 
 5209: # -------------------------------------------------- portfolio access checking
 5210: 
 5211: sub portfolio_access {
 5212:     my ($requrl) = @_;
 5213:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 5214:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 5215:     if ($result) {
 5216:         my %setters;
 5217:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 5218:             my ($startblock,$endblock) =
 5219:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 5220:             if ($startblock && $endblock) {
 5221:                 return 'B';
 5222:             }
 5223:         } else {
 5224:             my ($startblock,$endblock) =
 5225:                 &Apache::loncommon::blockcheck(\%setters,'port');
 5226:             if ($startblock && $endblock) {
 5227:                 return 'B';
 5228:             }
 5229:         }
 5230:     }
 5231:     if ($result eq 'ok') {
 5232:        return 'F';
 5233:     } elsif ($result =~ /^[^:]+:guest_/) {
 5234:        return 'A';
 5235:     }
 5236:     return '';
 5237: }
 5238: 
 5239: sub get_portfolio_access {
 5240:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 5241: 
 5242:     if (!ref($access_hash)) {
 5243: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 5244: 	my %access_controls = &get_access_controls($current_perms,$group,
 5245: 						   $file_name);
 5246: 	$access_hash = $access_controls{$file_name};
 5247:     }
 5248: 
 5249:     my ($public,$guest,@domains,@users,@courses,@groups);
 5250:     my $now = time;
 5251:     if (ref($access_hash) eq 'HASH') {
 5252:         foreach my $key (keys(%{$access_hash})) {
 5253:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 5254:             if ($start > $now) {
 5255:                 next;
 5256:             }
 5257:             if ($end && $end<$now) {
 5258:                 next;
 5259:             }
 5260:             if ($scope eq 'public') {
 5261:                 $public = $key;
 5262:                 last;
 5263:             } elsif ($scope eq 'guest') {
 5264:                 $guest = $key;
 5265:             } elsif ($scope eq 'domains') {
 5266:                 push(@domains,$key);
 5267:             } elsif ($scope eq 'users') {
 5268:                 push(@users,$key);
 5269:             } elsif ($scope eq 'course') {
 5270:                 push(@courses,$key);
 5271:             } elsif ($scope eq 'group') {
 5272:                 push(@groups,$key);
 5273:             }
 5274:         }
 5275:         if ($public) {
 5276:             return 'ok';
 5277:         }
 5278:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 5279:             if ($guest) {
 5280:                 return $guest;
 5281:             }
 5282:         } else {
 5283:             if (@domains > 0) {
 5284:                 foreach my $domkey (@domains) {
 5285:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 5286:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 5287:                             return 'ok';
 5288:                         }
 5289:                     }
 5290:                 }
 5291:             }
 5292:             if (@users > 0) {
 5293:                 foreach my $userkey (@users) {
 5294:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 5295:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 5296:                             if (ref($item) eq 'HASH') {
 5297:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 5298:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 5299:                                     return 'ok';
 5300:                                 }
 5301:                             }
 5302:                         }
 5303:                     } 
 5304:                 }
 5305:             }
 5306:             my %roleshash;
 5307:             my @courses_and_groups = @courses;
 5308:             push(@courses_and_groups,@groups); 
 5309:             if (@courses_and_groups > 0) {
 5310:                 my (%allgroups,%allroles); 
 5311:                 my ($start,$end,$role,$sec,$group);
 5312:                 foreach my $envkey (%env) {
 5313:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 5314:                         my $cid = $2.'_'.$3; 
 5315:                         if ($1 eq 'gr') {
 5316:                             $group = $4;
 5317:                             $allgroups{$cid}{$group} = $env{$envkey};
 5318:                         } else {
 5319:                             if ($4 eq '') {
 5320:                                 $sec = 'none';
 5321:                             } else {
 5322:                                 $sec = $4;
 5323:                             }
 5324:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 5325:                         }
 5326:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 5327:                         my $cid = $2.'_'.$3;
 5328:                         if ($4 eq '') {
 5329:                             $sec = 'none';
 5330:                         } else {
 5331:                             $sec = $4;
 5332:                         }
 5333:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 5334:                     }
 5335:                 }
 5336:                 if (keys(%allroles) == 0) {
 5337:                     return;
 5338:                 }
 5339:                 foreach my $key (@courses_and_groups) {
 5340:                     my %content = %{$$access_hash{$key}};
 5341:                     my $cnum = $content{'number'};
 5342:                     my $cdom = $content{'domain'};
 5343:                     my $cid = $cdom.'_'.$cnum;
 5344:                     if (!exists($allroles{$cid})) {
 5345:                         next;
 5346:                     }    
 5347:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 5348:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 5349:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 5350:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 5351:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 5352:                         foreach my $role (keys(%{$allroles{$cid}})) {
 5353:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 5354:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 5355:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 5356:                                         if (grep/^all$/,@sections) {
 5357:                                             return 'ok';
 5358:                                         } else {
 5359:                                             if (grep/^$sec$/,@sections) {
 5360:                                                 return 'ok';
 5361:                                             }
 5362:                                         }
 5363:                                     }
 5364:                                 }
 5365:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 5366:                                     if (grep/^none$/,@groups) {
 5367:                                         return 'ok';
 5368:                                     }
 5369:                                 } else {
 5370:                                     if (grep/^all$/,@groups) {
 5371:                                         return 'ok';
 5372:                                     } 
 5373:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 5374:                                         if (grep/^$group$/,@groups) {
 5375:                                             return 'ok';
 5376:                                         }
 5377:                                     }
 5378:                                 } 
 5379:                             }
 5380:                         }
 5381:                     }
 5382:                 }
 5383:             }
 5384:             if ($guest) {
 5385:                 return $guest;
 5386:             }
 5387:         }
 5388:     }
 5389:     return;
 5390: }
 5391: 
 5392: sub course_group_datechecker {
 5393:     my ($dates,$now,$status) = @_;
 5394:     my ($start,$end) = split(/\./,$dates);
 5395:     if (!$start && !$end) {
 5396:         return 'ok';
 5397:     }
 5398:     if (grep/^active$/,@{$status}) {
 5399:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 5400:             return 'ok';
 5401:         }
 5402:     }
 5403:     if (grep/^previous$/,@{$status}) {
 5404:         if ($end > $now ) {
 5405:             return 'ok';
 5406:         }
 5407:     }
 5408:     if (grep/^future$/,@{$status}) {
 5409:         if ($start > $now) {
 5410:             return 'ok';
 5411:         }
 5412:     }
 5413:     return; 
 5414: }
 5415: 
 5416: sub parse_portfolio_url {
 5417:     my ($url) = @_;
 5418: 
 5419:     my ($type,$udom,$unum,$group,$file_name);
 5420:     
 5421:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 5422: 	$type = 1;
 5423:         $udom = $1;
 5424:         $unum = $2;
 5425:         $file_name = $3;
 5426:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 5427: 	$type = 2;
 5428:         $udom = $1;
 5429:         $unum = $2;
 5430:         $group = $3;
 5431:         $file_name = $3.'/'.$4;
 5432:     }
 5433:     if (wantarray) {
 5434: 	return ($type,$udom,$unum,$file_name,$group);
 5435:     }
 5436:     return $type;
 5437: }
 5438: 
 5439: sub is_portfolio_url {
 5440:     my ($url) = @_;
 5441:     return scalar(&parse_portfolio_url($url));
 5442: }
 5443: 
 5444: sub is_portfolio_file {
 5445:     my ($file) = @_;
 5446:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 5447:         return 1;
 5448:     }
 5449:     return;
 5450: }
 5451: 
 5452: sub usertools_access {
 5453:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 5454:     my ($access,%tools);
 5455:     if ($context eq '') {
 5456:         $context = 'tools';
 5457:     }
 5458:     if ($context eq 'requestcourses') {
 5459:         %tools = (
 5460:                       official   => 1,
 5461:                       unofficial => 1,
 5462:                       community  => 1,
 5463:                  );
 5464:     } else {
 5465:         %tools = (
 5466:                       aboutme   => 1,
 5467:                       blog      => 1,
 5468:                       portfolio => 1,
 5469:                  );
 5470:     }
 5471:     return if (!defined($tools{$tool}));
 5472: 
 5473:     if ((!defined($udom)) || (!defined($uname))) {
 5474:         $udom = $env{'user.domain'};
 5475:         $uname = $env{'user.name'};
 5476:     }
 5477: 
 5478:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 5479:         if ($action ne 'reload') {
 5480:             if ($context eq 'requestcourses') {
 5481:                 return $env{'environment.canrequest.'.$tool};
 5482:             } else {
 5483:                 return $env{'environment.availabletools.'.$tool};
 5484:             }
 5485:         }
 5486:     }
 5487: 
 5488:     my ($toolstatus,$inststatus);
 5489: 
 5490:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 5491:          ($action ne 'reload')) {
 5492:         $toolstatus = $env{'environment.'.$context.'.'.$tool};
 5493:         $inststatus = $env{'environment.inststatus'};
 5494:     } else {
 5495:         if (ref($userenvref) eq 'HASH') {
 5496:             $toolstatus = $userenvref->{$context.'.'.$tool};
 5497:             $inststatus = $userenvref->{'inststatus'};
 5498:         } else {
 5499:             my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
 5500:             $toolstatus = $userenv{$context.'.'.$tool};
 5501:             $inststatus = $userenv{'inststatus'};
 5502:         }
 5503:     }
 5504: 
 5505:     if ($toolstatus ne '') {
 5506:         if ($toolstatus) {
 5507:             $access = 1;
 5508:         } else {
 5509:             $access = 0;
 5510:         }
 5511:         return $access;
 5512:     }
 5513: 
 5514:     my ($is_adv,%domdef);
 5515:     if (ref($is_advref) eq 'HASH') {
 5516:         $is_adv = $is_advref->{'is_adv'};
 5517:     } else {
 5518:         $is_adv = &is_advanced_user($udom,$uname);
 5519:     }
 5520:     if (ref($domdefref) eq 'HASH') {
 5521:         %domdef = %{$domdefref};
 5522:     } else {
 5523:         %domdef = &get_domain_defaults($udom);
 5524:     }
 5525:     if (ref($domdef{$tool}) eq 'HASH') {
 5526:         if ($is_adv) {
 5527:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 5528:                 if ($domdef{$tool}{'_LC_adv'}) { 
 5529:                     $access = 1;
 5530:                 } else {
 5531:                     $access = 0;
 5532:                 }
 5533:                 return $access;
 5534:             }
 5535:         }
 5536:         if ($inststatus ne '') {
 5537:             my ($hasaccess,$hasnoaccess);
 5538:             foreach my $affiliation (split(/:/,$inststatus)) {
 5539:                 if ($domdef{$tool}{$affiliation} ne '') { 
 5540:                     if ($domdef{$tool}{$affiliation}) {
 5541:                         $hasaccess = 1;
 5542:                     } else {
 5543:                         $hasnoaccess = 1;
 5544:                     }
 5545:                 }
 5546:             }
 5547:             if ($hasaccess || $hasnoaccess) {
 5548:                 if ($hasaccess) {
 5549:                     $access = 1;
 5550:                 } elsif ($hasnoaccess) {
 5551:                     $access = 0; 
 5552:                 }
 5553:                 return $access;
 5554:             }
 5555:         } else {
 5556:             if ($domdef{$tool}{'default'} ne '') {
 5557:                 if ($domdef{$tool}{'default'}) {
 5558:                     $access = 1;
 5559:                 } elsif ($domdef{$tool}{'default'} == 0) {
 5560:                     $access = 0;
 5561:                 }
 5562:                 return $access;
 5563:             }
 5564:         }
 5565:     } else {
 5566:         if ($context eq 'tools') {
 5567:             $access = 1;
 5568:         } else {
 5569:             $access = 0;
 5570:         }
 5571:         return $access;
 5572:     }
 5573: }
 5574: 
 5575: sub is_course_owner {
 5576:     my ($cdom,$cnum,$udom,$uname) = @_;
 5577:     if (($udom eq '') || ($uname eq '')) {
 5578:         $udom = $env{'user.domain'};
 5579:         $uname = $env{'user.name'};
 5580:     }
 5581:     unless (($udom eq '') || ($uname eq '')) {
 5582:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 5583:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 5584:                 return 1;
 5585:             } else {
 5586:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 5587:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 5588:                     return 1;
 5589:                 }
 5590:             }
 5591:         }
 5592:     }
 5593:     return;
 5594: }
 5595: 
 5596: sub is_advanced_user {
 5597:     my ($udom,$uname) = @_;
 5598:     if ($udom ne '' && $uname ne '') {
 5599:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 5600:             if (wantarray) {
 5601:                 return ($env{'user.adv'},$env{'user.author'});
 5602:             } else {
 5603:                 return $env{'user.adv'};
 5604:             }
 5605:         }
 5606:     }
 5607:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 5608:     my %allroles;
 5609:     my ($is_adv,$is_author);
 5610:     foreach my $role (keys(%roleshash)) {
 5611:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 5612:         my $area = '/'.$tdomain.'/'.$trest;
 5613:         if ($sec ne '') {
 5614:             $area .= '/'.$sec;
 5615:         }
 5616:         if (($area ne '') && ($trole ne '')) {
 5617:             my $spec=$trole.'.'.$area;
 5618:             if ($trole =~ /^cr\//) {
 5619:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 5620:             } elsif ($trole ne 'gr') {
 5621:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 5622:             }
 5623:             if ($trole eq 'au') {
 5624:                 $is_author = 1;
 5625:             }
 5626:         }
 5627:     }
 5628:     foreach my $role (keys(%allroles)) {
 5629:         last if ($is_adv);
 5630:         foreach my $item (split(/:/,$allroles{$role})) {
 5631:             if ($item ne '') {
 5632:                 my ($privilege,$restrictions)=split(/&/,$item);
 5633:                 if ($privilege eq 'adv') {
 5634:                     $is_adv = 1;
 5635:                     last;
 5636:                 }
 5637:             }
 5638:         }
 5639:     }
 5640:     if (wantarray) {
 5641:         return ($is_adv,$is_author);
 5642:     }
 5643:     return $is_adv;
 5644: }
 5645: 
 5646: sub check_can_request {
 5647:     my ($dom,$can_request,$request_domains) = @_;
 5648:     my $canreq = 0;
 5649:     my ($types,$typename) = &Apache::loncommon::course_types();
 5650:     my @options = ('approval','validate','autolimit');
 5651:     my $optregex = join('|',@options);
 5652:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 5653:         foreach my $type (@{$types}) {
 5654:             if (&usertools_access($env{'user.name'},
 5655:                                   $env{'user.domain'},
 5656:                                   $type,undef,'requestcourses')) {
 5657:                 $canreq ++;
 5658:                 if (ref($request_domains) eq 'HASH') {
 5659:                     push(@{$request_domains->{$type}},$env{'user.domain'});
 5660:                 }
 5661:                 if ($dom eq $env{'user.domain'}) {
 5662:                     $can_request->{$type} = 1;
 5663:                 }
 5664:             }
 5665:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
 5666:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 5667:                 if (@curr > 0) {
 5668:                     foreach my $item (@curr) {
 5669:                         if (ref($request_domains) eq 'HASH') {
 5670:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 5671:                             if ($otherdom ne '') {
 5672:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 5673:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 5674:                                         push(@{$request_domains->{$type}},$otherdom);
 5675:                                     }
 5676:                                 } else {
 5677:                                     push(@{$request_domains->{$type}},$otherdom);
 5678:                                 }
 5679:                             }
 5680:                         }
 5681:                     }
 5682:                     unless($dom eq $env{'user.domain'}) {
 5683:                         $canreq ++;
 5684:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 5685:                             $can_request->{$type} = 1;
 5686:                         }
 5687:                     }
 5688:                 }
 5689:             }
 5690:         }
 5691:     }
 5692:     return $canreq;
 5693: }
 5694: 
 5695: # ---------------------------------------------- Custom access rule evaluation
 5696: 
 5697: sub customaccess {
 5698:     my ($priv,$uri)=@_;
 5699:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 5700:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 5701:     $udom = &LONCAPA::clean_domain($udom);
 5702:     $ucrs = &LONCAPA::clean_username($ucrs);
 5703:     my $access=0;
 5704:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 5705: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 5706: 	if ($type eq 'user') {
 5707: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 5708: 		my ($tdom,$tuname)=split(m{/},$scope);
 5709: 		if ($tdom) {
 5710: 		    if ($tdom ne $env{'user.domain'}) { next; }
 5711: 		}
 5712: 		if ($tuname) {
 5713: 		    if ($tuname ne $env{'user.name'}) { next; }
 5714: 		}
 5715: 		$access=($effect eq 'allow');
 5716: 		last;
 5717: 	    }
 5718: 	} else {
 5719: 	    if ($role) {
 5720: 		if ($role ne $urole) { next; }
 5721: 	    }
 5722: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 5723: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 5724: 		if ($tdom) {
 5725: 		    if ($tdom ne $udom) { next; }
 5726: 		}
 5727: 		if ($tcrs) {
 5728: 		    if ($tcrs ne $ucrs) { next; }
 5729: 		}
 5730: 		if ($tsec) {
 5731: 		    if ($tsec ne $usec) { next; }
 5732: 		}
 5733: 		$access=($effect eq 'allow');
 5734: 		last;
 5735: 	    }
 5736: 	    if ($realm eq '' && $role eq '') {
 5737: 		$access=($effect eq 'allow');
 5738: 	    }
 5739: 	}
 5740:     }
 5741:     return $access;
 5742: }
 5743: 
 5744: # ------------------------------------------------- Check for a user privilege
 5745: 
 5746: sub allowed {
 5747:     my ($priv,$uri,$symb,$role)=@_;
 5748:     my $ver_orguri=$uri;
 5749:     $uri=&deversion($uri);
 5750:     my $orguri=$uri;
 5751:     $uri=&declutter($uri);
 5752: 
 5753:     if ($priv eq 'evb') {
 5754: # Evade communication block restrictions for specified role in a course
 5755:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 5756:             return $1;
 5757:         } else {
 5758:             return;
 5759:         }
 5760:     }
 5761: 
 5762:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 5763: # Free bre access to adm and meta resources
 5764:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 5765: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 5766: 	&& ($priv eq 'bre')) {
 5767: 	return 'F';
 5768:     }
 5769: 
 5770: # Free bre access to user's own portfolio contents
 5771:     my ($space,$domain,$name,@dir)=split('/',$uri);
 5772:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 5773: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 5774:         my %setters;
 5775:         my ($startblock,$endblock) = 
 5776:             &Apache::loncommon::blockcheck(\%setters,'port');
 5777:         if ($startblock && $endblock) {
 5778:             return 'B';
 5779:         } else {
 5780:             return 'F';
 5781:         }
 5782:     }
 5783: 
 5784: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 5785:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 5786:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 5787:         if (exists($env{'request.course.id'})) {
 5788:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5789:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5790:             if (($domain eq $cdom) && ($name eq $cnum)) {
 5791:                 my $courseprivid=$env{'request.course.id'};
 5792:                 $courseprivid=~s/\_/\//;
 5793:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 5794:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 5795:                     return $1; 
 5796:                 } else {
 5797:                     if ($env{'request.course.sec'}) {
 5798:                         $courseprivid.='/'.$env{'request.course.sec'};
 5799:                     }
 5800:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 5801:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 5802:                         return $2;
 5803:                     }
 5804:                 }
 5805:             }
 5806:         }
 5807:     }
 5808: 
 5809: # Free bre to public access
 5810: 
 5811:     if ($priv eq 'bre') {
 5812:         my $copyright=&metadata($uri,'copyright');
 5813: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 5814:            return 'F'; 
 5815:         }
 5816:         if ($copyright eq 'priv') {
 5817:             $uri=~/([^\/]+)\/([^\/]+)\//;
 5818: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 5819: 		return '';
 5820:             }
 5821:         }
 5822:         if ($copyright eq 'domain') {
 5823:             $uri=~/([^\/]+)\/([^\/]+)\//;
 5824: 	    unless (($env{'user.domain'} eq $1) ||
 5825:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 5826: 		return '';
 5827:             }
 5828:         }
 5829:         if ($env{'request.role'}=~ /li\.\//) {
 5830:             # Library role, so allow browsing of resources in this domain.
 5831:             return 'F';
 5832:         }
 5833:         if ($copyright eq 'custom') {
 5834: 	    unless (&customaccess($priv,$uri)) { return ''; }
 5835:         }
 5836:     }
 5837:     # Domain coordinator is trying to create a course
 5838:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 5839:         # uri is the requested domain in this case.
 5840:         # comparison to 'request.role.domain' shows if the user has selected
 5841:         # a role of dc for the domain in question.
 5842:         return 'F' if ($uri eq $env{'request.role.domain'});
 5843:     }
 5844: 
 5845:     my $thisallowed='';
 5846:     my $statecond=0;
 5847:     my $courseprivid='';
 5848: 
 5849:     my $ownaccess;
 5850:     # Community Coordinator or Assistant Co-author browsing resource space.
 5851:     if (($priv eq 'bro') && ($env{'user.author'})) {
 5852:         if ($uri eq '') {
 5853:             $ownaccess = 1;
 5854:         } else {
 5855:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 5856:                 my $udom = $env{'user.domain'};
 5857:                 my $uname = $env{'user.name'};
 5858:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 5859:                     $ownaccess = 1;
 5860:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 5861:                     unless ($uri =~ m{\.\./}) {
 5862:                         $ownaccess = 1;
 5863:                     }
 5864:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 5865:                     my $now = time;
 5866:                     if ($uri =~ m{^([^/]+)/?$}) {
 5867:                         my $adom = $1;
 5868:                         foreach my $key (keys(%env)) {
 5869:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 5870:                                 my ($start,$end) = split('.',$env{$key});
 5871:                                 if (($now >= $start) && (!$end || $end < $now)) {
 5872:                                     $ownaccess = 1;
 5873:                                     last;
 5874:                                 }
 5875:                             }
 5876:                         }
 5877:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 5878:                         my $adom = $1;
 5879:                         my $aname = $2;
 5880:                         foreach my $role ('ca','aa') { 
 5881:                             if ($env{"user.role.$role./$adom/$aname"}) {
 5882:                                 my ($start,$end) =
 5883:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 5884:                                 if (($now >= $start) && (!$end || $end < $now)) {
 5885:                                     $ownaccess = 1;
 5886:                                     last;
 5887:                                 }
 5888:                             }
 5889:                         }
 5890:                     }
 5891:                 }
 5892:             }
 5893:         }
 5894:     }
 5895: 
 5896: # Course
 5897: 
 5898:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 5899:         unless (($priv eq 'bro') && (!$ownaccess)) {
 5900:             $thisallowed.=$1;
 5901:         }
 5902:     }
 5903: 
 5904: # Domain
 5905: 
 5906:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 5907:        =~/\Q$priv\E\&([^\:]*)/) {
 5908:         unless (($priv eq 'bro') && (!$ownaccess)) {
 5909:             $thisallowed.=$1;
 5910:         }
 5911:     }
 5912: 
 5913: # Course: uri itself is a course
 5914:     my $courseuri=$uri;
 5915:     $courseuri=~s/\_(\d)/\/$1/;
 5916:     $courseuri=~s/^([^\/])/\/$1/;
 5917: 
 5918:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 5919:        =~/\Q$priv\E\&([^\:]*)/) {
 5920:         unless (($priv eq 'bro') && (!$ownaccess)) {
 5921:             $thisallowed.=$1;
 5922:         }
 5923:     }
 5924: 
 5925: # URI is an uploaded document for this course, default permissions don't matter
 5926: # not allowing 'edit' access (editupload) to uploaded course docs
 5927:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 5928: 	$thisallowed='';
 5929:         my ($match)=&is_on_map($uri);
 5930:         if ($match) {
 5931:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 5932:                   =~/\Q$priv\E\&([^\:]*)/) {
 5933:                 $thisallowed.=$1;
 5934:             }
 5935:         } else {
 5936:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 5937:             if ($refuri) {
 5938:                 if ($refuri =~ m|^/adm/|) {
 5939:                     $thisallowed='F';
 5940:                 } else {
 5941:                     $refuri=&declutter($refuri);
 5942:                     my ($match) = &is_on_map($refuri);
 5943:                     if ($match) {
 5944:                         $thisallowed='F';
 5945:                     }
 5946:                 }
 5947:             }
 5948:         }
 5949:     }
 5950: 
 5951:     if ($priv eq 'bre'
 5952: 	&& $thisallowed ne 'F' 
 5953: 	&& $thisallowed ne '2'
 5954: 	&& &is_portfolio_url($uri)) {
 5955: 	$thisallowed = &portfolio_access($uri);
 5956:     }
 5957:     
 5958: # Full access at system, domain or course-wide level? Exit.
 5959:     if ($thisallowed=~/F/) {
 5960: 	return 'F';
 5961:     }
 5962: 
 5963: # If this is generating or modifying users, exit with special codes
 5964: 
 5965:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 5966: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 5967: 	    my ($audom,$auname)=split('/',$uri);
 5968: # no author name given, so this just checks on the general right to make a co-author in this domain
 5969: 	    unless ($auname) { return $thisallowed; }
 5970: # an author name is given, so we are about to actually make a co-author for a certain account
 5971: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 5972: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 5973: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 5974: 	}
 5975: 	return $thisallowed;
 5976:     }
 5977: #
 5978: # Gathered so far: system, domain and course wide privileges
 5979: #
 5980: # Course: See if uri or referer is an individual resource that is part of 
 5981: # the course
 5982: 
 5983:     if ($env{'request.course.id'}) {
 5984: 
 5985:        $courseprivid=$env{'request.course.id'};
 5986:        if ($env{'request.course.sec'}) {
 5987:           $courseprivid.='/'.$env{'request.course.sec'};
 5988:        }
 5989:        $courseprivid=~s/\_/\//;
 5990:        my $checkreferer=1;
 5991:        my ($match,$cond)=&is_on_map($uri);
 5992:        if ($match) {
 5993:            $statecond=$cond;
 5994:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 5995:                =~/\Q$priv\E\&([^\:]*)/) {
 5996:                $thisallowed.=$1;
 5997:                $checkreferer=0;
 5998:            }
 5999:        }
 6000:        
 6001:        if ($checkreferer) {
 6002: 	  my $refuri=$env{'httpref.'.$orguri};
 6003:             unless ($refuri) {
 6004:                 foreach my $key (keys(%env)) {
 6005: 		    if ($key=~/^httpref\..*\*/) {
 6006: 			my $pattern=$key;
 6007:                         $pattern=~s/^httpref\.\/res\///;
 6008:                         $pattern=~s/\*/\[\^\/\]\+/g;
 6009:                         $pattern=~s/\//\\\//g;
 6010:                         if ($orguri=~/$pattern/) {
 6011: 			    $refuri=$env{$key};
 6012:                         }
 6013:                     }
 6014:                 }
 6015:             }
 6016: 
 6017:          if ($refuri) { 
 6018: 	  $refuri=&declutter($refuri);
 6019:           my ($match,$cond)=&is_on_map($refuri);
 6020:             if ($match) {
 6021:               my $refstatecond=$cond;
 6022:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 6023:                   =~/\Q$priv\E\&([^\:]*)/) {
 6024:                   $thisallowed.=$1;
 6025:                   $uri=$refuri;
 6026:                   $statecond=$refstatecond;
 6027:               }
 6028:           }
 6029:         }
 6030:        }
 6031:    }
 6032: 
 6033: #
 6034: # Gathered now: all privileges that could apply, and condition number
 6035: # 
 6036: #
 6037: # Full or no access?
 6038: #
 6039: 
 6040:     if ($thisallowed=~/F/) {
 6041: 	return 'F';
 6042:     }
 6043: 
 6044:     unless ($thisallowed) {
 6045:         return '';
 6046:     }
 6047: 
 6048: # Restrictions exist, deal with them
 6049: #
 6050: #   C:according to course preferences
 6051: #   R:according to resource settings
 6052: #   L:unless locked
 6053: #   X:according to user session state
 6054: #
 6055: 
 6056: # Possibly locked functionality, check all courses
 6057: # Locks might take effect only after 10 minutes cache expiration for other
 6058: # courses, and 2 minutes for current course
 6059: 
 6060:     my $envkey;
 6061:     if ($thisallowed=~/L/) {
 6062:         foreach $envkey (keys(%env)) {
 6063:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 6064:                my $courseid=$2;
 6065:                my $roleid=$1.'.'.$2;
 6066:                $courseid=~s/^\///;
 6067:                my $expiretime=600;
 6068:                if ($env{'request.role'} eq $roleid) {
 6069: 		  $expiretime=120;
 6070:                }
 6071: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 6072:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 6073:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 6074: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 6075:                }
 6076:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 6077:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 6078: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 6079:                        &log($env{'user.domain'},$env{'user.name'},
 6080:                             $env{'user.home'},
 6081:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 6082:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 6083:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 6084: 		       return '';
 6085:                    }
 6086:                }
 6087:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 6088:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 6089: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 6090:                        &log($env{'user.domain'},$env{'user.name'},
 6091:                             $env{'user.home'},
 6092:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 6093:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 6094:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 6095: 		       return '';
 6096:                    }
 6097:                }
 6098: 	   }
 6099:        }
 6100:     }
 6101:    
 6102: #
 6103: # Rest of the restrictions depend on selected course
 6104: #
 6105: 
 6106:     unless ($env{'request.course.id'}) {
 6107: 	if ($thisallowed eq 'A') {
 6108: 	    return 'A';
 6109:         } elsif ($thisallowed eq 'B') {
 6110:             return 'B';
 6111: 	} else {
 6112: 	    return '1';
 6113: 	}
 6114:     }
 6115: 
 6116: #
 6117: # Now user is definitely in a course
 6118: #
 6119: 
 6120: 
 6121: # Course preferences
 6122: 
 6123:    if ($thisallowed=~/C/) {
 6124:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 6125:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 6126:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 6127: 	   =~/\Q$rolecode\E/) {
 6128: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6129: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 6130: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 6131: 			$env{'request.course.id'});
 6132: 	   }
 6133:            return '';
 6134:        }
 6135: 
 6136:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 6137: 	   =~/\Q$unamedom\E/) {
 6138: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6139: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 6140: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 6141: 			$env{'request.course.id'});
 6142: 	   }
 6143:            return '';
 6144:        }
 6145:    }
 6146: 
 6147: # Resource preferences
 6148: 
 6149:    if ($thisallowed=~/R/) {
 6150:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 6151:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 6152: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6153: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 6154: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 6155: 	   }
 6156: 	   return '';
 6157:        }
 6158:    }
 6159: 
 6160: # Restricted by state or randomout?
 6161: 
 6162:    if ($thisallowed=~/X/) {
 6163:       if ($env{'acc.randomout'}) {
 6164: 	 if (!$symb) { $symb=&symbread($uri,1); }
 6165:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 6166:             return ''; 
 6167:          }
 6168:       }
 6169:       if (&condval($statecond)) {
 6170: 	 return '2';
 6171:       } else {
 6172:          return '';
 6173:       }
 6174:    }
 6175: 
 6176:     if ($thisallowed eq 'A') {
 6177: 	return 'A';
 6178:     } elsif ($thisallowed eq 'B') {
 6179:         return 'B';
 6180:     }
 6181:    return 'F';
 6182: }
 6183: #
 6184: #   Removes the versino from a URI and
 6185: #   splits it in to its filename and path to the filename.
 6186: #   Seems like File::Basename could have done this more clearly.
 6187: #   Parameters:
 6188: #      $uri   - input URI
 6189: #   Returns:
 6190: #     Two element list consisting of 
 6191: #     $pathname  - the URI up to and excluding the trailing /
 6192: #     $filename  - The part of the URI following the last /
 6193: #  NOTE:
 6194: #    Another realization of this is simply:
 6195: #    use File::Basename;
 6196: #    ...
 6197: #    $uri = shift;
 6198: #    $filename = basename($uri);
 6199: #    $path     = dirname($uri);
 6200: #    return ($filename, $path);
 6201: #
 6202: #     The implementation below is probably faster however.
 6203: #
 6204: sub split_uri_for_cond {
 6205:     my $uri=&deversion(&declutter(shift));
 6206:     my @uriparts=split(/\//,$uri);
 6207:     my $filename=pop(@uriparts);
 6208:     my $pathname=join('/',@uriparts);
 6209:     return ($pathname,$filename);
 6210: }
 6211: # --------------------------------------------------- Is a resource on the map?
 6212: 
 6213: sub is_on_map {
 6214:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 6215:     #Trying to find the conditional for the file
 6216:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 6217: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 6218:     if ($match) {
 6219: 	return (1,$1);
 6220:     } else {
 6221: 	return (0,0);
 6222:     }
 6223: }
 6224: 
 6225: # --------------------------------------------------------- Get symb from alias
 6226: 
 6227: sub get_symb_from_alias {
 6228:     my $symb=shift;
 6229:     my ($map,$resid,$url)=&decode_symb($symb);
 6230: # Already is a symb
 6231:     if ($url) { return $symb; }
 6232: # Must be an alias
 6233:     my $aliassymb='';
 6234:     my %bighash;
 6235:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6236:                             &GDBM_READER(),0640)) {
 6237:         my $rid=$bighash{'mapalias_'.$symb};
 6238: 	if ($rid) {
 6239: 	    my ($mapid,$resid)=split(/\./,$rid);
 6240: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 6241: 				    $resid,$bighash{'src_'.$rid});
 6242: 	}
 6243:         untie %bighash;
 6244:     }
 6245:     return $aliassymb;
 6246: }
 6247: 
 6248: # ----------------------------------------------------------------- Define Role
 6249: 
 6250: sub definerole {
 6251:   if (allowed('mcr','/')) {
 6252:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 6253:     foreach my $role (split(':',$sysrole)) {
 6254: 	my ($crole,$cqual)=split(/\&/,$role);
 6255:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 6256:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 6257: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 6258:                return "refused:s:$crole&$cqual"; 
 6259:             }
 6260:         }
 6261:     }
 6262:     foreach my $role (split(':',$domrole)) {
 6263: 	my ($crole,$cqual)=split(/\&/,$role);
 6264:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 6265:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 6266: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 6267:                return "refused:d:$crole&$cqual"; 
 6268:             }
 6269:         }
 6270:     }
 6271:     foreach my $role (split(':',$courole)) {
 6272: 	my ($crole,$cqual)=split(/\&/,$role);
 6273:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 6274:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 6275: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 6276:                return "refused:c:$crole&$cqual"; 
 6277:             }
 6278:         }
 6279:     }
 6280:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 6281:                 "$env{'user.domain'}:$env{'user.name'}:".
 6282: 	        "rolesdef_$rolename=".
 6283:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 6284:     return reply($command,$env{'user.home'});
 6285:   } else {
 6286:     return 'refused';
 6287:   }
 6288: }
 6289: 
 6290: # ---------------- Make a metadata query against the network of library servers
 6291: 
 6292: sub metadata_query {
 6293:     my ($query,$custom,$customshow,$server_array)=@_;
 6294:     my %rhash;
 6295:     my %libserv = &all_library();
 6296:     my @server_list = (defined($server_array) ? @$server_array
 6297:                                               : keys(%libserv) );
 6298:     for my $server (@server_list) {
 6299: 	unless ($custom or $customshow) {
 6300: 	    my $reply=&reply("querysend:".&escape($query),$server);
 6301: 	    $rhash{$server}=$reply;
 6302: 	}
 6303: 	else {
 6304: 	    my $reply=&reply("querysend:".&escape($query).':'.
 6305: 			     &escape($custom).':'.&escape($customshow),
 6306: 			     $server);
 6307: 	    $rhash{$server}=$reply;
 6308: 	}
 6309:     }
 6310:     return \%rhash;
 6311: }
 6312: 
 6313: # ----------------------------------------- Send log queries and wait for reply
 6314: 
 6315: sub log_query {
 6316:     my ($uname,$udom,$query,%filters)=@_;
 6317:     my $uhome=&homeserver($uname,$udom);
 6318:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 6319:     my $uhost=&hostname($uhome);
 6320:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 6321:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 6322:                        $uhome);
 6323:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 6324:     return get_query_reply($queryid);
 6325: }
 6326: 
 6327: # -------------------------- Update MySQL table for portfolio file
 6328: 
 6329: sub update_portfolio_table {
 6330:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 6331:     if ($group ne '') {
 6332:         $file_name =~s /^\Q$group\E//;
 6333:     }
 6334:     my $homeserver = &homeserver($uname,$udom);
 6335:     my $queryid=
 6336:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 6337:                ':'.&escape($file_name).':'.$action,$homeserver);
 6338:     my $reply = &get_query_reply($queryid);
 6339:     return $reply;
 6340: }
 6341: 
 6342: # -------------------------- Update MySQL allusers table
 6343: 
 6344: sub update_allusers_table {
 6345:     my ($uname,$udom,$names) = @_;
 6346:     my $homeserver = &homeserver($uname,$udom);
 6347:     my $queryid=
 6348:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 6349:                'lastname='.&escape($names->{'lastname'}).'%%'.
 6350:                'firstname='.&escape($names->{'firstname'}).'%%'.
 6351:                'middlename='.&escape($names->{'middlename'}).'%%'.
 6352:                'generation='.&escape($names->{'generation'}).'%%'.
 6353:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 6354:                'id='.&escape($names->{'id'}),$homeserver);
 6355:     return;
 6356: }
 6357: 
 6358: # ------- Request retrieval of institutional classlists for course(s)
 6359: 
 6360: sub fetch_enrollment_query {
 6361:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 6362:     my $homeserver;
 6363:     my $maxtries = 1;
 6364:     if ($context eq 'automated') {
 6365:         $homeserver = $perlvar{'lonHostID'};
 6366:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 6367:     } else {
 6368:         $homeserver = &homeserver($cnum,$dom);
 6369:     }
 6370:     my $host=&hostname($homeserver);
 6371:     my $cmd = '';
 6372:     foreach my $affiliate (keys(%{$affiliatesref})) {
 6373:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 6374:     }
 6375:     $cmd =~ s/%%$//;
 6376:     $cmd = &escape($cmd);
 6377:     my $query = 'fetchenrollment';
 6378:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 6379:     unless ($queryid=~/^\Q$host\E\_/) { 
 6380:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 6381:         return 'error: '.$queryid;
 6382:     }
 6383:     my $reply = &get_query_reply($queryid);
 6384:     my $tries = 1;
 6385:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 6386:         $reply = &get_query_reply($queryid);
 6387:         $tries ++;
 6388:     }
 6389:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 6390:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 6391:     } else {
 6392:         my @responses = split(/:/,$reply);
 6393:         if ($homeserver eq $perlvar{'lonHostID'}) {
 6394:             foreach my $line (@responses) {
 6395:                 my ($key,$value) = split(/=/,$line,2);
 6396:                 $$replyref{$key} = $value;
 6397:             }
 6398:         } else {
 6399:             my $pathname = LONCAPA::tempdir();
 6400:             foreach my $line (@responses) {
 6401:                 my ($key,$value) = split(/=/,$line);
 6402:                 $$replyref{$key} = $value;
 6403:                 if ($value > 0) {
 6404:                     foreach my $item (@{$$affiliatesref{$key}}) {
 6405:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 6406:                         my $destname = $pathname.'/'.$filename;
 6407:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 6408:                         if ($xml_classlist =~ /^error/) {
 6409:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 6410:                         } else {
 6411:                             if ( open(FILE,">$destname") ) {
 6412:                                 print FILE &unescape($xml_classlist);
 6413:                                 close(FILE);
 6414:                             } else {
 6415:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 6416:                             }
 6417:                         }
 6418:                     }
 6419:                 }
 6420:             }
 6421:         }
 6422:         return 'ok';
 6423:     }
 6424:     return 'error';
 6425: }
 6426: 
 6427: sub get_query_reply {
 6428:     my $queryid=shift;
 6429:     my $replyfile=LONCAPA::tempdir().$queryid;
 6430:     my $reply='';
 6431:     for (1..100) {
 6432: 	sleep 2;
 6433:         if (-e $replyfile.'.end') {
 6434: 	    if (open(my $fh,$replyfile)) {
 6435: 		$reply = join('',<$fh>);
 6436: 		close($fh);
 6437: 	   } else { return 'error: reply_file_error'; }
 6438:            return &unescape($reply);
 6439: 	}
 6440:     }
 6441:     return 'timeout:'.$queryid;
 6442: }
 6443: 
 6444: sub courselog_query {
 6445: #
 6446: # possible filters:
 6447: # url: url or symb
 6448: # username
 6449: # domain
 6450: # action: view, submit, grade
 6451: # start: timestamp
 6452: # end: timestamp
 6453: #
 6454:     my (%filters)=@_;
 6455:     unless ($env{'request.course.id'}) { return 'no_course'; }
 6456:     if ($filters{'url'}) {
 6457: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 6458:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 6459:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 6460:     }
 6461:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6462:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6463:     return &log_query($cname,$cdom,'courselog',%filters);
 6464: }
 6465: 
 6466: sub userlog_query {
 6467: #
 6468: # possible filters:
 6469: # action: log check role
 6470: # start: timestamp
 6471: # end: timestamp
 6472: #
 6473:     my ($uname,$udom,%filters)=@_;
 6474:     return &log_query($uname,$udom,'userlog',%filters);
 6475: }
 6476: 
 6477: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 6478: 
 6479: sub auto_run {
 6480:     my ($cnum,$cdom) = @_;
 6481:     my $response = 0;
 6482:     my $settings;
 6483:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 6484:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 6485:         $settings = $domconfig{'autoenroll'};
 6486:         if ($settings->{'run'} eq '1') {
 6487:             $response = 1;
 6488:         }
 6489:     } else {
 6490:         my $homeserver;
 6491:         if (&is_course($cdom,$cnum)) {
 6492:             $homeserver = &homeserver($cnum,$cdom);
 6493:         } else {
 6494:             $homeserver = &domain($cdom,'primary');
 6495:         }
 6496:         if ($homeserver ne 'no_host') {
 6497:             $response = &reply('autorun:'.$cdom,$homeserver);
 6498:         }
 6499:     }
 6500:     return $response;
 6501: }
 6502: 
 6503: sub auto_get_sections {
 6504:     my ($cnum,$cdom,$inst_coursecode) = @_;
 6505:     my $homeserver;
 6506:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 6507:         $homeserver = &homeserver($cnum,$cdom);
 6508:     }
 6509:     if (!defined($homeserver)) { 
 6510:         if ($cdom =~ /^$match_domain$/) {
 6511:             $homeserver = &domain($cdom,'primary');
 6512:         }
 6513:     }
 6514:     my @secs;
 6515:     if (defined($homeserver)) {
 6516:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 6517:         unless ($response eq 'refused') {
 6518:             @secs = split(/:/,$response);
 6519:         }
 6520:     }
 6521:     return @secs;
 6522: }
 6523: 
 6524: sub auto_new_course {
 6525:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 6526:     my $homeserver = &homeserver($cnum,$cdom);
 6527:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 6528:     return $response;
 6529: }
 6530: 
 6531: sub auto_validate_courseID {
 6532:     my ($cnum,$cdom,$inst_course_id) = @_;
 6533:     my $homeserver = &homeserver($cnum,$cdom);
 6534:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 6535:     return $response;
 6536: }
 6537: 
 6538: sub auto_validate_instcode {
 6539:     my ($cnum,$cdom,$instcode,$owner) = @_;
 6540:     my ($homeserver,$response);
 6541:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 6542:         $homeserver = &homeserver($cnum,$cdom);
 6543:     }
 6544:     if (!defined($homeserver)) {
 6545:         if ($cdom =~ /^$match_domain$/) {
 6546:             $homeserver = &domain($cdom,'primary');
 6547:         }
 6548:     }
 6549:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 6550:                         &escape($instcode).':'.&escape($owner),$homeserver));
 6551:     my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
 6552:     return ($outcome,$description);
 6553: }
 6554: 
 6555: sub auto_create_password {
 6556:     my ($cnum,$cdom,$authparam,$udom) = @_;
 6557:     my ($homeserver,$response);
 6558:     my $create_passwd = 0;
 6559:     my $authchk = '';
 6560:     if ($udom =~ /^$match_domain$/) {
 6561:         $homeserver = &domain($udom,'primary');
 6562:     }
 6563:     if ($homeserver eq '') {
 6564:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 6565:             $homeserver = &homeserver($cnum,$cdom);
 6566:         }
 6567:     }
 6568:     if ($homeserver eq '') {
 6569:         $authchk = 'nodomain';
 6570:     } else {
 6571:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 6572:         if ($response eq 'refused') {
 6573:             $authchk = 'refused';
 6574:         } else {
 6575:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 6576:         }
 6577:     }
 6578:     return ($authparam,$create_passwd,$authchk);
 6579: }
 6580: 
 6581: sub auto_photo_permission {
 6582:     my ($cnum,$cdom,$students) = @_;
 6583:     my $homeserver = &homeserver($cnum,$cdom);
 6584:     my ($outcome,$perm_reqd,$conditions) = 
 6585: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 6586:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 6587: 	return (undef,undef);
 6588:     }
 6589:     return ($outcome,$perm_reqd,$conditions);
 6590: }
 6591: 
 6592: sub auto_checkphotos {
 6593:     my ($uname,$udom,$pid) = @_;
 6594:     my $homeserver = &homeserver($uname,$udom);
 6595:     my ($result,$resulttype);
 6596:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 6597: 				   &escape($uname).':'.&escape($pid),
 6598: 				   $homeserver));
 6599:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 6600: 	return (undef,undef);
 6601:     }
 6602:     if ($outcome) {
 6603:         ($result,$resulttype) = split(/:/,$outcome);
 6604:     } 
 6605:     return ($result,$resulttype);
 6606: }
 6607: 
 6608: sub auto_photochoice {
 6609:     my ($cnum,$cdom) = @_;
 6610:     my $homeserver = &homeserver($cnum,$cdom);
 6611:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 6612: 						       &escape($cdom),
 6613: 						       $homeserver)));
 6614:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 6615: 	return (undef,undef);
 6616:     }
 6617:     return ($update,$comment);
 6618: }
 6619: 
 6620: sub auto_photoupdate {
 6621:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 6622:     my $homeserver = &homeserver($cnum,$dom);
 6623:     my $host=&hostname($homeserver);
 6624:     my $cmd = '';
 6625:     my $maxtries = 1;
 6626:     foreach my $affiliate (keys(%{$affiliatesref})) {
 6627:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 6628:     }
 6629:     $cmd =~ s/%%$//;
 6630:     $cmd = &escape($cmd);
 6631:     my $query = 'institutionalphotos';
 6632:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 6633:     unless ($queryid=~/^\Q$host\E\_/) {
 6634:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 6635:         return 'error: '.$queryid;
 6636:     }
 6637:     my $reply = &get_query_reply($queryid);
 6638:     my $tries = 1;
 6639:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 6640:         $reply = &get_query_reply($queryid);
 6641:         $tries ++;
 6642:     }
 6643:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 6644:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 6645:     } else {
 6646:         my @responses = split(/:/,$reply);
 6647:         my $outcome = shift(@responses); 
 6648:         foreach my $item (@responses) {
 6649:             my ($key,$value) = split(/=/,$item);
 6650:             $$photo{$key} = $value;
 6651:         }
 6652:         return $outcome;
 6653:     }
 6654:     return 'error';
 6655: }
 6656: 
 6657: sub auto_instcode_format {
 6658:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 6659: 	$cat_order) = @_;
 6660:     my $courses = '';
 6661:     my @homeservers;
 6662:     if ($caller eq 'global') {
 6663: 	my %servers = &get_servers($codedom,'library');
 6664: 	foreach my $tryserver (keys(%servers)) {
 6665: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 6666: 		push(@homeservers,$tryserver);
 6667: 	    }
 6668:         }
 6669:     } elsif ($caller eq 'requests') {
 6670:         if ($codedom =~ /^$match_domain$/) {
 6671:             my $chome = &domain($codedom,'primary');
 6672:             unless ($chome eq 'no_host') {
 6673:                 push(@homeservers,$chome);
 6674:             }
 6675:         }
 6676:     } else {
 6677:         push(@homeservers,&homeserver($caller,$codedom));
 6678:     }
 6679:     foreach my $code (keys(%{$instcodes})) {
 6680:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 6681:     }
 6682:     chop($courses);
 6683:     my $ok_response = 0;
 6684:     my $response;
 6685:     while (@homeservers > 0 && $ok_response == 0) {
 6686:         my $server = shift(@homeservers); 
 6687:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 6688:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 6689:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 6690: 		split(/:/,$response);
 6691:             %{$codes} = (%{$codes},&str2hash($codes_str));
 6692:             push(@{$codetitles},&str2array($codetitles_str));
 6693:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 6694:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 6695:             $ok_response = 1;
 6696:         }
 6697:     }
 6698:     if ($ok_response) {
 6699:         return 'ok';
 6700:     } else {
 6701:         return $response;
 6702:     }
 6703: }
 6704: 
 6705: sub auto_instcode_defaults {
 6706:     my ($domain,$returnhash,$code_order) = @_;
 6707:     my @homeservers;
 6708: 
 6709:     my %servers = &get_servers($domain,'library');
 6710:     foreach my $tryserver (keys(%servers)) {
 6711: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 6712: 	    push(@homeservers,$tryserver);
 6713: 	}
 6714:     }
 6715: 
 6716:     my $response;
 6717:     foreach my $server (@homeservers) {
 6718:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 6719:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 6720: 	
 6721: 	foreach my $pair (split(/\&/,$response)) {
 6722: 	    my ($name,$value)=split(/\=/,$pair);
 6723: 	    if ($name eq 'code_order') {
 6724: 		@{$code_order} = split(/\&/,&unescape($value));
 6725: 	    } else {
 6726: 		$returnhash->{&unescape($name)}=&unescape($value);
 6727: 	    }
 6728: 	}
 6729: 	return 'ok';
 6730:     }
 6731: 
 6732:     return $response;
 6733: }
 6734: 
 6735: sub auto_possible_instcodes {
 6736:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 6737:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 6738:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 6739:         return;
 6740:     }
 6741:     my (@homeservers,$uhome);
 6742:     if (defined(&domain($domain,'primary'))) {
 6743:         $uhome=&domain($domain,'primary');
 6744:         push(@homeservers,&domain($domain,'primary'));
 6745:     } else {
 6746:         my %servers = &get_servers($domain,'library');
 6747:         foreach my $tryserver (keys(%servers)) {
 6748:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 6749:                 push(@homeservers,$tryserver);
 6750:             }
 6751:         }
 6752:     }
 6753:     my $response;
 6754:     foreach my $server (@homeservers) {
 6755:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 6756:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 6757:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 6758:             split(':',$response);
 6759:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 6760:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 6761:         foreach my $item (split('&',$cat_title)) {   
 6762:             my ($name,$value)=split('=',$item);
 6763:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 6764:         }
 6765:         foreach my $item (split('&',$cat_order)) {
 6766:             my ($name,$value)=split('=',$item);
 6767:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 6768:         }
 6769:         return 'ok';
 6770:     }
 6771:     return $response;
 6772: }
 6773: 
 6774: sub auto_courserequest_checks {
 6775:     my ($dom) = @_;
 6776:     my ($homeserver,%validations);
 6777:     if ($dom =~ /^$match_domain$/) {
 6778:         $homeserver = &domain($dom,'primary');
 6779:     }
 6780:     unless ($homeserver eq 'no_host') {
 6781:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 6782:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 6783:             my @items = split(/&/,$response);
 6784:             foreach my $item (@items) {
 6785:                 my ($key,$value) = split('=',$item);
 6786:                 $validations{&unescape($key)} = &thaw_unescape($value);
 6787:             }
 6788:         }
 6789:     }
 6790:     return %validations; 
 6791: }
 6792: 
 6793: sub auto_courserequest_validation {
 6794:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
 6795:     my ($homeserver,$response);
 6796:     if ($dom =~ /^$match_domain$/) {
 6797:         $homeserver = &domain($dom,'primary');
 6798:     }
 6799:     unless ($homeserver eq 'no_host') {  
 6800:           
 6801:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 6802:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 6803:                                     ':'.&escape($instcode).':'.&escape($instseclist),
 6804:                                     $homeserver));
 6805:     }
 6806:     return $response;
 6807: }
 6808: 
 6809: sub auto_validate_class_sec {
 6810:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 6811:     my $homeserver = &homeserver($cnum,$cdom);
 6812:     my $ownerlist;
 6813:     if (ref($owners) eq 'ARRAY') {
 6814:         $ownerlist = join(',',@{$owners});
 6815:     } else {
 6816:         $ownerlist = $owners;
 6817:     }
 6818:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 6819:                         &escape($ownerlist).':'.$cdom,$homeserver);
 6820:     return $response;
 6821: }
 6822: 
 6823: # ------------------------------------------------------- Course Group routines
 6824: 
 6825: sub get_coursegroups {
 6826:     my ($cdom,$cnum,$group,$namespace) = @_;
 6827:     return(&dump($namespace,$cdom,$cnum,$group));
 6828: }
 6829: 
 6830: sub modify_coursegroup {
 6831:     my ($cdom,$cnum,$groupsettings) = @_;
 6832:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 6833: }
 6834: 
 6835: sub toggle_coursegroup_status {
 6836:     my ($cdom,$cnum,$group,$action) = @_;
 6837:     my ($from_namespace,$to_namespace);
 6838:     if ($action eq 'delete') {
 6839:         $from_namespace = 'coursegroups';
 6840:         $to_namespace = 'deleted_groups';
 6841:     } else {
 6842:         $from_namespace = 'deleted_groups';
 6843:         $to_namespace = 'coursegroups';
 6844:     }
 6845:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 6846:     if (my $tmp = &error(%curr_group)) {
 6847:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 6848:         return ('read error',$tmp);
 6849:     } else {
 6850:         my %savedsettings = %curr_group; 
 6851:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 6852:         my $deloutcome;
 6853:         if ($result eq 'ok') {
 6854:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 6855:         } else {
 6856:             return ('write error',$result);
 6857:         }
 6858:         if ($deloutcome eq 'ok') {
 6859:             return 'ok';
 6860:         } else {
 6861:             return ('delete error',$deloutcome);
 6862:         }
 6863:     }
 6864: }
 6865: 
 6866: sub modify_group_roles {
 6867:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 6868:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 6869:     my $role = 'gr/'.&escape($userprivs);
 6870:     my ($uname,$udom) = split(/:/,$user);
 6871:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 6872:     if ($result eq 'ok') {
 6873:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 6874:     }
 6875:     return $result;
 6876: }
 6877: 
 6878: sub modify_coursegroup_membership {
 6879:     my ($cdom,$cnum,$membership) = @_;
 6880:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 6881:     return $result;
 6882: }
 6883: 
 6884: sub get_active_groups {
 6885:     my ($udom,$uname,$cdom,$cnum) = @_;
 6886:     my $now = time;
 6887:     my %groups = ();
 6888:     foreach my $key (keys(%env)) {
 6889:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 6890:             my ($start,$end) = split(/\./,$env{$key});
 6891:             if (($end!=0) && ($end<$now)) { next; }
 6892:             if (($start!=0) && ($start>$now)) { next; }
 6893:             if ($1 eq $cdom && $2 eq $cnum) {
 6894:                 $groups{$3} = $env{$key} ;
 6895:             }
 6896:         }
 6897:     }
 6898:     return %groups;
 6899: }
 6900: 
 6901: sub get_group_membership {
 6902:     my ($cdom,$cnum,$group) = @_;
 6903:     return(&dump('groupmembership',$cdom,$cnum,$group));
 6904: }
 6905: 
 6906: sub get_users_groups {
 6907:     my ($udom,$uname,$courseid) = @_;
 6908:     my @usersgroups;
 6909:     my $cachetime=1800;
 6910: 
 6911:     my $hashid="$udom:$uname:$courseid";
 6912:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 6913:     if (defined($cached)) {
 6914:         @usersgroups = split(/:/,$grouplist);
 6915:     } else {  
 6916:         $grouplist = '';
 6917:         my $courseurl = &courseid_to_courseurl($courseid);
 6918:         my $extra = &freeze_escape({'skipcheck' => 1});
 6919:         my %roleshash = &dump('roles',$udom,$uname,$courseurl,undef,$extra);
 6920:         my $access_end = $env{'course.'.$courseid.
 6921:                               '.default_enrollment_end_date'};
 6922:         my $now = time;
 6923:         foreach my $key (keys(%roleshash)) {
 6924:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 6925:                 my $group = $1;
 6926:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 6927:                     my $start = $2;
 6928:                     my $end = $1;
 6929:                     if ($start == -1) { next; } # deleted from group
 6930:                     if (($start!=0) && ($start>$now)) { next; }
 6931:                     if (($end!=0) && ($end<$now)) {
 6932:                         if ($access_end && $access_end < $now) {
 6933:                             if ($access_end - $end < 86400) {
 6934:                                 push(@usersgroups,$group);
 6935:                             }
 6936:                         }
 6937:                         next;
 6938:                     }
 6939:                     push(@usersgroups,$group);
 6940:                 }
 6941:             }
 6942:         }
 6943:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 6944:         $grouplist = join(':',@usersgroups);
 6945:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 6946:     }
 6947:     return @usersgroups;
 6948: }
 6949: 
 6950: sub devalidate_getgroups_cache {
 6951:     my ($udom,$uname,$cdom,$cnum)=@_;
 6952:     my $courseid = $cdom.'_'.$cnum;
 6953: 
 6954:     my $hashid="$udom:$uname:$courseid";
 6955:     &devalidate_cache_new('getgroups',$hashid);
 6956: }
 6957: 
 6958: # ------------------------------------------------------------------ Plain Text
 6959: 
 6960: sub plaintext {
 6961:     my ($short,$type,$cid,$forcedefault) = @_;
 6962:     if ($short =~ m{^cr/}) {
 6963: 	return (split('/',$short))[-1];
 6964:     }
 6965:     if (!defined($cid)) {
 6966:         $cid = $env{'request.course.id'};
 6967:     }
 6968:     my %rolenames = (
 6969:                       Course    => 'std',
 6970:                       Community => 'alt1',
 6971:                     );
 6972:     if ($cid ne '') {
 6973:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 6974:             unless ($forcedefault) {
 6975:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 6976:                 &Apache::lonlocal::mt_escape(\$roletext);
 6977:                 return &Apache::lonlocal::mt($roletext);
 6978:             }
 6979:         }
 6980:     }
 6981:     if ((defined($type)) && (defined($rolenames{$type})) &&
 6982:         (defined($rolenames{$type})) && 
 6983:         (defined($prp{$short}{$rolenames{$type}}))) {
 6984:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 6985:     } elsif ($cid ne '') {
 6986:         my $crstype = $env{'course.'.$cid.'.type'};
 6987:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
 6988:             (defined($prp{$short}{$rolenames{$crstype}}))) {
 6989:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
 6990:         }
 6991:     }
 6992:     return &Apache::lonlocal::mt($prp{$short}{'std'});
 6993: }
 6994: 
 6995: # ----------------------------------------------------------------- Assign Role
 6996: 
 6997: sub assignrole {
 6998:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 6999:         $context)=@_;
 7000:     my $mrole;
 7001:     if ($role =~ /^cr\//) {
 7002:         my $cwosec=$url;
 7003:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 7004: 	unless (&allowed('ccr',$cwosec)) {
 7005:            my $refused = 1;
 7006:            if ($context eq 'requestcourses') {
 7007:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 7008:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
 7009:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
 7010:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 7011:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 7012:                            if ($crsenv{'internal.courseowner'} eq
 7013:                                $env{'user.name'}.':'.$env{'user.domain'}) {
 7014:                                $refused = '';
 7015:                            }
 7016:                        }
 7017:                    }
 7018:                }
 7019:            }
 7020:            if ($refused) {
 7021:                &logthis('Refused custom assignrole: '.
 7022:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
 7023:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
 7024:                return 'refused';
 7025:            }
 7026:         }
 7027:         $mrole='cr';
 7028:     } elsif ($role =~ /^gr\//) {
 7029:         my $cwogrp=$url;
 7030:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 7031:         unless (&allowed('mdg',$cwogrp)) {
 7032:             &logthis('Refused group assignrole: '.
 7033:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 7034:                     $env{'user.name'}.' at '.$env{'user.domain'});
 7035:             return 'refused';
 7036:         }
 7037:         $mrole='gr';
 7038:     } else {
 7039:         my $cwosec=$url;
 7040:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 7041:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 7042:             my $refused;
 7043:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 7044:                 if (!(&allowed('c'.$role,$url))) {
 7045:                     $refused = 1;
 7046:                 }
 7047:             } else {
 7048:                 $refused = 1;
 7049:             }
 7050:             if ($refused) {
 7051:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 7052:                 if (!$selfenroll && $context eq 'course') {
 7053:                     my %crsenv;
 7054:                     if ($role eq 'cc' || $role eq 'co') {
 7055:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 7056:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
 7057:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
 7058:                                 if ($crsenv{'internal.courseowner'} eq 
 7059:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 7060:                                     $refused = '';
 7061:                                 }
 7062:                             }
 7063:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
 7064:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
 7065:                                 if ($crsenv{'internal.courseowner'} eq 
 7066:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 7067:                                     $refused = '';
 7068:                                 }
 7069:                             }
 7070:                         }
 7071:                     }
 7072:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7073:                     $refused = '';
 7074:                 } elsif ($context eq 'requestcourses') {
 7075:                     my @possroles = ('st','ta','ep','in','cc','co');
 7076:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
 7077:                         my $wrongcc;
 7078:                         if ($cnum =~ /^$match_community$/) {
 7079:                             $wrongcc = 1 if ($role eq 'cc');
 7080:                         } else {
 7081:                             $wrongcc = 1 if ($role eq 'co');
 7082:                         }
 7083:                         unless ($wrongcc) {
 7084:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 7085:                             if ($crsenv{'internal.courseowner'} eq 
 7086:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
 7087:                                 $refused = '';
 7088:                             }
 7089:                         }
 7090:                     }
 7091:                 }
 7092:                 if ($refused) {
 7093:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 7094:                              ' '.$role.' '.$end.' '.$start.' by '.
 7095: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 7096:                     return 'refused';
 7097:                 }
 7098:             }
 7099:         } elsif ($role eq 'au') {
 7100:             if ($url ne '/'.$udom.'/') {
 7101:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
 7102:                          ' to assign author role for '.$uname.':'.$udom.
 7103:                          ' in domain: '.$url.' refused (wrong domain).');
 7104:                 return 'refused';
 7105:             }
 7106:         }
 7107:         $mrole=$role;
 7108:     }
 7109:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 7110:                 "$udom:$uname:$url".'_'."$mrole=$role";
 7111:     if ($end) { $command.='_'.$end; }
 7112:     if ($start) {
 7113: 	if ($end) { 
 7114:            $command.='_'.$start; 
 7115:         } else {
 7116:            $command.='_0_'.$start;
 7117:         }
 7118:     }
 7119:     my $origstart = $start;
 7120:     my $origend = $end;
 7121:     my $delflag;
 7122: # actually delete
 7123:     if ($deleteflag) {
 7124: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 7125: # modify command to delete the role
 7126:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 7127:                 "$udom:$uname:$url".'_'."$mrole";
 7128: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 7129: # set start and finish to negative values for userrolelog
 7130:            $start=-1;
 7131:            $end=-1;
 7132:            $delflag = 1;
 7133:         }
 7134:     }
 7135: # send command
 7136:     my $answer=&reply($command,&homeserver($uname,$udom));
 7137: # log new user role if status is ok
 7138:     if ($answer eq 'ok') {
 7139: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 7140: # for course roles, perform group memberships changes triggered by role change.
 7141:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
 7142:         unless ($role =~ /^gr/) {
 7143:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 7144:                                              $origstart,$selfenroll,$context);
 7145:         }
 7146:         if ($role eq 'cc') {
 7147:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
 7148:         }
 7149:     }
 7150:     return $answer;
 7151: }
 7152: 
 7153: sub autoupdate_coowners {
 7154:     my ($url,$end,$start,$uname,$udom) = @_;
 7155:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
 7156:     if (($cdom ne '') && ($cnum ne '')) {
 7157:         my $now = time;
 7158:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
 7159:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
 7160:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
 7161:             my $instcode = $coursehash{'internal.coursecode'};
 7162:             if ($instcode ne '') {
 7163:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
 7164:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
 7165:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
 7166:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
 7167:                         if ($result eq 'valid') {
 7168:                             if ($coursehash{'internal.co-owners'}) {
 7169:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 7170:                                     push(@newcoowners,$coowner);
 7171:                                 }
 7172:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
 7173:                                     push(@newcoowners,$uname.':'.$udom);
 7174:                                 }
 7175:                                 @newcoowners = sort(@newcoowners);
 7176:                             } else {
 7177:                                 push(@newcoowners,$uname.':'.$udom);
 7178:                             }
 7179:                         } else {
 7180:                             if ($coursehash{'internal.co-owners'}) {
 7181:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 7182:                                     unless ($coowner eq $uname.':'.$udom) {
 7183:                                         push(@newcoowners,$coowner);
 7184:                                     }
 7185:                                 }
 7186:                                 unless (@newcoowners > 0) {
 7187:                                     $delcoowners = 1;
 7188:                                     $coowners = '';
 7189:                                 }
 7190:                             }
 7191:                         }
 7192:                         if (@newcoowners || $delcoowners) {
 7193:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
 7194:                                             $delcoowners,@newcoowners);
 7195:                         }
 7196:                     }
 7197:                 }
 7198:             }
 7199:         }
 7200:     }
 7201: }
 7202: 
 7203: sub store_coowners {
 7204:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
 7205:     my $cid = $cdom.'_'.$cnum;
 7206:     my ($coowners,$delresult,$putresult);
 7207:     if (@newcoowners) {
 7208:         $coowners = join(',',@newcoowners);
 7209:         my %coownershash = (
 7210:                             'internal.co-owners' => $coowners,
 7211:                            );
 7212:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
 7213:         if ($putresult eq 'ok') {
 7214:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
 7215:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
 7216:             }
 7217:         }
 7218:     }
 7219:     if ($delcoowners) {
 7220:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
 7221:         if ($delresult eq 'ok') {
 7222:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
 7223:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
 7224:             }
 7225:         }
 7226:     }
 7227:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
 7228:         my %crsinfo =
 7229:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 7230:         if (ref($crsinfo{$cid}) eq 'HASH') {
 7231:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
 7232:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
 7233:         }
 7234:     }
 7235: }
 7236: 
 7237: # -------------------------------------------------- Modify user authentication
 7238: # Overrides without validation
 7239: 
 7240: sub modifyuserauth {
 7241:     my ($udom,$uname,$umode,$upass)=@_;
 7242:     my $uhome=&homeserver($uname,$udom);
 7243:     unless (&allowed('mau',$udom)) { return 'refused'; }
 7244:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 7245:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 7246:              ' in domain '.$env{'request.role.domain'});  
 7247:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 7248: 		     &escape($upass),$uhome);
 7249:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 7250:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 7251:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 7252:     &log($udom,,$uname,$uhome,
 7253:         'Authentication changed by '.$env{'user.domain'}.', '.
 7254:                                      $env{'user.name'}.', '.$umode.
 7255:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 7256:     unless ($reply eq 'ok') {
 7257:         &logthis('Authentication mode error: '.$reply);
 7258: 	return 'error: '.$reply;
 7259:     }   
 7260:     return 'ok';
 7261: }
 7262: 
 7263: # --------------------------------------------------------------- Modify a user
 7264: 
 7265: sub modifyuser {
 7266:     my ($udom,    $uname, $uid,
 7267:         $umode,   $upass, $first,
 7268:         $middle,  $last,  $gene,
 7269:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
 7270:     $udom= &LONCAPA::clean_domain($udom);
 7271:     $uname=&LONCAPA::clean_username($uname);
 7272:     my $showcandelete = 'none';
 7273:     if (ref($candelete) eq 'ARRAY') {
 7274:         if (@{$candelete} > 0) {
 7275:             $showcandelete = join(', ',@{$candelete});
 7276:         }
 7277:     }
 7278:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 7279:              $umode.', '.$first.', '.$middle.', '.
 7280: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
 7281:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 7282:                                      ' desiredhome not specified'). 
 7283:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 7284:              ' in domain '.$env{'request.role.domain'});
 7285:     my $uhome=&homeserver($uname,$udom,'true');
 7286:     my $newuser;
 7287:     if ($uhome eq 'no_host') {
 7288:         $newuser = 1;
 7289:     }
 7290: # ----------------------------------------------------------------- Create User
 7291:     if (($uhome eq 'no_host') && 
 7292: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 7293:         my $unhome='';
 7294:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 7295:             $unhome = $desiredhome;
 7296: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 7297: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 7298:         } else { # load balancing routine for determining $unhome
 7299:             my $loadm=10000000;
 7300: 	    my %servers = &get_servers($udom,'library');
 7301: 	    foreach my $tryserver (keys(%servers)) {
 7302: 		my $answer=reply('load',$tryserver);
 7303: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 7304: 		    $loadm=$answer;
 7305: 		    $unhome=$tryserver;
 7306: 		}
 7307: 	    }
 7308:         }
 7309:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 7310: 	    return 'error: unable to find a home server for '.$uname.
 7311:                    ' in domain '.$udom;
 7312:         }
 7313:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 7314:                          &escape($upass),$unhome);
 7315: 	unless ($reply eq 'ok') {
 7316:             return 'error: '.$reply;
 7317:         }   
 7318:         $uhome=&homeserver($uname,$udom,'true');
 7319:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 7320: 	    return 'error: unable verify users home machine.';
 7321:         }
 7322:     }   # End of creation of new user
 7323: # ---------------------------------------------------------------------- Add ID
 7324:     if ($uid) {
 7325:        $uid=~tr/A-Z/a-z/;
 7326:        my %uidhash=&idrget($udom,$uname);
 7327:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 7328:          && (!$forceid)) {
 7329: 	  unless ($uid eq $uidhash{$uname}) {
 7330: 	      return 'error: user id "'.$uid.'" does not match '.
 7331:                   'current user id "'.$uidhash{$uname}.'".';
 7332:           }
 7333:        } else {
 7334: 	  &idput($udom,($uname => $uid));
 7335:        }
 7336:     }
 7337: # -------------------------------------------------------------- Add names, etc
 7338:     my @tmp=&get('environment',
 7339: 		   ['firstname','middlename','lastname','generation','id',
 7340:                     'permanentemail','inststatus'],
 7341: 		   $udom,$uname);
 7342:     my (%names,%oldnames);
 7343:     if ($tmp[0] =~ m/^error:.*/) { 
 7344:         %names=(); 
 7345:     } else {
 7346:         %names = @tmp;
 7347:         %oldnames = %names;
 7348:     }
 7349: #
 7350: # If name, email and/or uid are blank (e.g., because an uploaded file
 7351: # of users did not contain them), do not overwrite existing values
 7352: # unless field is in $candelete array ref.  
 7353: #
 7354: 
 7355:     my @fields = ('firstname','middlename','lastname','generation',
 7356:                   'permanentemail','id');
 7357:     my %newvalues;
 7358:     if (ref($candelete) eq 'ARRAY') {
 7359:         foreach my $field (@fields) {
 7360:             if (grep(/^\Q$field\E$/,@{$candelete})) {
 7361:                 if ($field eq 'firstname') {
 7362:                     $names{$field} = $first;
 7363:                 } elsif ($field eq 'middlename') {
 7364:                     $names{$field} = $middle;
 7365:                 } elsif ($field eq 'lastname') {
 7366:                     $names{$field} = $last;
 7367:                 } elsif ($field eq 'generation') { 
 7368:                     $names{$field} = $gene;
 7369:                 } elsif ($field eq 'permanentemail') {
 7370:                     $names{$field} = $email;
 7371:                 } elsif ($field eq 'id') {
 7372:                     $names{$field}  = $uid;
 7373:                 }
 7374:             }
 7375:         }
 7376:     }
 7377:     if ($first)  { $names{'firstname'}  = $first; }
 7378:     if (defined($middle)) { $names{'middlename'} = $middle; }
 7379:     if ($last)   { $names{'lastname'}   = $last; }
 7380:     if (defined($gene))   { $names{'generation'} = $gene; }
 7381:     if ($email) {
 7382:        $email=~s/[^\w\@\.\-\,]//gs;
 7383:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 7384:     }
 7385:     if ($uid) { $names{'id'}  = $uid; }
 7386:     if (defined($inststatus)) {
 7387:         $names{'inststatus'} = '';
 7388:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
 7389:         if (ref($usertypes) eq 'HASH') {
 7390:             my @okstatuses; 
 7391:             foreach my $item (split(/:/,$inststatus)) {
 7392:                 if (defined($usertypes->{$item})) {
 7393:                     push(@okstatuses,$item);  
 7394:                 }
 7395:             }
 7396:             if (@okstatuses) {
 7397:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
 7398:             }
 7399:         }
 7400:     }
 7401:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
 7402:                  $umode.', '.$first.', '.$middle.', '.
 7403:                  $last.', '.$gene.', '.$email.', '.$inststatus;
 7404:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 7405:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 7406:     } else {
 7407:         $logmsg .= ' during self creation';
 7408:     }
 7409:     my $changed;
 7410:     if ($newuser) {
 7411:         $changed = 1;
 7412:     } else {
 7413:         foreach my $field (@fields) {
 7414:             if ($names{$field} ne $oldnames{$field}) {
 7415:                 $changed = 1;
 7416:                 last;
 7417:             }
 7418:         }
 7419:     }
 7420:     unless ($changed) {
 7421:         $logmsg = 'No changes in user information needed for: '.$logmsg;
 7422:         &logthis($logmsg);
 7423:         return 'ok';
 7424:     }
 7425:     my $reply = &put('environment', \%names, $udom,$uname);
 7426:     if ($reply ne 'ok') { 
 7427:         return 'error: '.$reply;
 7428:     }
 7429:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
 7430:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
 7431:     }
 7432:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 7433:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 7434:     $logmsg = 'Success modifying user '.$logmsg;
 7435:     &logthis($logmsg);
 7436:     return 'ok';
 7437: }
 7438: 
 7439: # -------------------------------------------------------------- Modify student
 7440: 
 7441: sub modifystudent {
 7442:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 7443:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 7444:         $selfenroll,$context,$inststatus)=@_;
 7445:     if (!$cid) {
 7446: 	unless ($cid=$env{'request.course.id'}) {
 7447: 	    return 'not_in_class';
 7448: 	}
 7449:     }
 7450: # --------------------------------------------------------------- Make the user
 7451:     my $reply=&modifyuser
 7452: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 7453:          $desiredhome,$email,$inststatus);
 7454:     unless ($reply eq 'ok') { return $reply; }
 7455:     # This will cause &modify_student_enrollment to get the uid from the
 7456:     # students environment
 7457:     $uid = undef if (!$forceid);
 7458:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 7459: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
 7460:     return $reply;
 7461: }
 7462: 
 7463: sub modify_student_enrollment {
 7464:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
 7465:     my ($cdom,$cnum,$chome);
 7466:     if (!$cid) {
 7467: 	unless ($cid=$env{'request.course.id'}) {
 7468: 	    return 'not_in_class';
 7469: 	}
 7470: 	$cdom=$env{'course.'.$cid.'.domain'};
 7471: 	$cnum=$env{'course.'.$cid.'.num'};
 7472:     } else {
 7473: 	($cdom,$cnum)=split(/_/,$cid);
 7474:     }
 7475:     $chome=$env{'course.'.$cid.'.home'};
 7476:     if (!$chome) {
 7477: 	$chome=&homeserver($cnum,$cdom);
 7478:     }
 7479:     if (!$chome) { return 'unknown_course'; }
 7480:     # Make sure the user exists
 7481:     my $uhome=&homeserver($uname,$udom);
 7482:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 7483: 	return 'error: no such user';
 7484:     }
 7485:     # Get student data if we were not given enough information
 7486:     if (!defined($first)  || $first  eq '' || 
 7487:         !defined($last)   || $last   eq '' || 
 7488:         !defined($uid)    || $uid    eq '' || 
 7489:         !defined($middle) || $middle eq '' || 
 7490:         !defined($gene)   || $gene   eq '') {
 7491:         # They did not supply us with enough data to enroll the student, so
 7492:         # we need to pick up more information.
 7493:         my %tmp = &get('environment',
 7494:                        ['firstname','middlename','lastname', 'generation','id']
 7495:                        ,$udom,$uname);
 7496: 
 7497:         #foreach my $key (keys(%tmp)) {
 7498:         #    &logthis("key $key = ".$tmp{$key});
 7499:         #}
 7500:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 7501:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 7502:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 7503:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 7504:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 7505:     }
 7506:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 7507:     my $reply=cput('classlist',
 7508: 		   {"$uname:$udom" => 
 7509: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
 7510: 		   $cdom,$cnum);
 7511:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
 7512: 	return 'error: '.$reply;
 7513:     } else {
 7514: 	&devalidate_getsection_cache($udom,$uname,$cid);
 7515:     }
 7516:     # Add student role to user
 7517:     my $uurl='/'.$cid;
 7518:     $uurl=~s/\_/\//g;
 7519:     if ($usec) {
 7520: 	$uurl.='/'.$usec;
 7521:     }
 7522:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
 7523: }
 7524: 
 7525: sub format_name {
 7526:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 7527:     my $name;
 7528:     if ($first ne 'lastname') {
 7529: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 7530:     } else {
 7531: 	if ($lastname=~/\S/) {
 7532: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 7533: 	    $name=~s/\s+,/,/;
 7534: 	} else {
 7535: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 7536: 	}
 7537:     }
 7538:     $name=~s/^\s+//;
 7539:     $name=~s/\s+$//;
 7540:     $name=~s/\s+/ /g;
 7541:     return $name;
 7542: }
 7543: 
 7544: # ------------------------------------------------- Write to course preferences
 7545: 
 7546: sub writecoursepref {
 7547:     my ($courseid,%prefs)=@_;
 7548:     $courseid=~s/^\///;
 7549:     $courseid=~s/\_/\//g;
 7550:     my ($cdomain,$cnum)=split(/\//,$courseid);
 7551:     my $chome=homeserver($cnum,$cdomain);
 7552:     if (($chome eq '') || ($chome eq 'no_host')) { 
 7553: 	return 'error: no such course';
 7554:     }
 7555:     my $cstring='';
 7556:     foreach my $pref (keys(%prefs)) {
 7557: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 7558:     }
 7559:     $cstring=~s/\&$//;
 7560:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 7561: }
 7562: 
 7563: # ---------------------------------------------------------- Make/modify course
 7564: 
 7565: sub createcourse {
 7566:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 7567:         $course_owner,$crstype,$cnum,$context,$category)=@_;
 7568:     $url=&declutter($url);
 7569:     my $cid='';
 7570:     if ($context eq 'requestcourses') {
 7571:         my $can_create = 0;
 7572:         my ($ownername,$ownerdom) = split(':',$course_owner);
 7573:         if ($udom eq $ownerdom) {
 7574:             if (&usertools_access($ownername,$ownerdom,$category,undef,
 7575:                                   $context)) {
 7576:                 $can_create = 1;
 7577:             }
 7578:         } else {
 7579:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
 7580:                                            $category);
 7581:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
 7582:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
 7583:                 if (@curr > 0) {
 7584:                     my @options = qw(approval validate autolimit);
 7585:                     my $optregex = join('|',@options);
 7586:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
 7587:                         $can_create = 1;
 7588:                     }
 7589:                 }
 7590:             }
 7591:         }
 7592:         if ($can_create) {
 7593:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
 7594:                 unless (&allowed('ccc',$udom)) {
 7595:                     return 'refused'; 
 7596:                 }
 7597:             }
 7598:         } else {
 7599:             return 'refused';
 7600:         }
 7601:     } elsif (!&allowed('ccc',$udom)) {
 7602:         return 'refused';
 7603:     }
 7604: # --------------------------------------------------------------- Get Unique ID
 7605:     my $uname;
 7606:     if ($cnum =~ /^$match_courseid$/) {
 7607:         my $chome=&homeserver($cnum,$udom,'true');
 7608:         if (($chome eq '') || ($chome eq 'no_host')) {
 7609:             $uname = $cnum;
 7610:         } else {
 7611:             $uname = &generate_coursenum($udom,$crstype);
 7612:         }
 7613:     } else {
 7614:         $uname = &generate_coursenum($udom,$crstype);
 7615:     }
 7616:     return $uname if ($uname =~ /^error/);
 7617: # -------------------------------------------------- Check supplied server name
 7618:     if (!defined($course_server)) {
 7619:         if (defined(&domain($udom,'primary'))) {
 7620:             $course_server = &domain($udom,'primary');
 7621:         } else {
 7622:             $course_server = $env{'user.home'}; 
 7623:         }
 7624:     }
 7625:     my %host_servers =
 7626:         &Apache::lonnet::get_servers($udom,'library');
 7627:     unless ($host_servers{$course_server}) {
 7628:         return 'error: invalid home server for course: '.$course_server;
 7629:     }
 7630: # ------------------------------------------------------------- Make the course
 7631:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 7632:                       $course_server);
 7633:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 7634:     my $uhome=&homeserver($uname,$udom,'true');
 7635:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 7636: 	return 'error: no such course';
 7637:     }
 7638: # ----------------------------------------------------------------- Course made
 7639: # log existence
 7640:     my $now = time;
 7641:     my $newcourse = {
 7642:                     $udom.'_'.$uname => {
 7643:                                      description => $description,
 7644:                                      inst_code   => $inst_code,
 7645:                                      owner       => $course_owner,
 7646:                                      type        => $crstype,
 7647:                                      creator     => $env{'user.name'}.':'.
 7648:                                                     $env{'user.domain'},
 7649:                                      created     => $now,
 7650:                                      context     => $context,
 7651:                                                 },
 7652:                     };
 7653:     &courseidput($udom,$newcourse,$uhome,'notime');
 7654: # set toplevel url
 7655:     my $topurl=$url;
 7656:     unless ($nonstandard) {
 7657: # ------------------------------------------ For standard courses, make top url
 7658:         my $mapurl=&clutter($url);
 7659:         if ($mapurl eq '/res/') { $mapurl=''; }
 7660:         $env{'form.initmap'}=(<<ENDINITMAP);
 7661: <map>
 7662: <resource id="1" type="start"></resource>
 7663: <resource id="2" src="$mapurl"></resource>
 7664: <resource id="3" type="finish"></resource>
 7665: <link index="1" from="1" to="2"></link>
 7666: <link index="2" from="2" to="3"></link>
 7667: </map>
 7668: ENDINITMAP
 7669:         $topurl=&declutter(
 7670:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 7671:                           );
 7672:     }
 7673: # ----------------------------------------------------------- Write preferences
 7674:     &writecoursepref($udom.'_'.$uname,
 7675:                      ('description'              => $description,
 7676:                       'url'                      => $topurl,
 7677:                       'internal.creator'         => $env{'user.name'}.':'.
 7678:                                                     $env{'user.domain'},
 7679:                       'internal.created'         => $now,
 7680:                       'internal.creationcontext' => $context)
 7681:                     );
 7682:     return '/'.$udom.'/'.$uname;
 7683: }
 7684: 
 7685: # ------------------------------------------------------------------- Create ID
 7686: sub generate_coursenum {
 7687:     my ($udom,$crstype) = @_;
 7688:     my $domdesc = &domain($udom);
 7689:     return 'error: invalid domain' if ($domdesc eq '');
 7690:     my $first;
 7691:     if ($crstype eq 'Community') {
 7692:         $first = '0';
 7693:     } else {
 7694:         $first = int(1+rand(9)); 
 7695:     } 
 7696:     my $uname=$first.
 7697:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 7698:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
 7699:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 7700: # ----------------------------------------------- Make sure that does not exist
 7701:     my $uhome=&homeserver($uname,$udom,'true');
 7702:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
 7703:         if ($crstype eq 'Community') {
 7704:             $first = '0';
 7705:         } else {
 7706:             $first = int(1+rand(9));
 7707:         }
 7708:         $uname=$first.
 7709:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 7710:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
 7711:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 7712:         $uhome=&homeserver($uname,$udom,'true');
 7713:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
 7714:             return 'error: unable to generate unique course-ID';
 7715:         }
 7716:     }
 7717:     return $uname;
 7718: }
 7719: 
 7720: sub is_course {
 7721:     my ($cdom,$cnum) = @_;
 7722:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
 7723: 				undef,'.');
 7724:     if (exists($courses{$cdom.'_'.$cnum})) {
 7725:         return 1;
 7726:     }
 7727:     return 0;
 7728: }
 7729: 
 7730: sub store_userdata {
 7731:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
 7732:     my $result;
 7733:     if ($datakey ne '') {
 7734:         if (ref($storehash) eq 'HASH') {
 7735:             if ($udom eq '' || $uname eq '') {
 7736:                 $udom = $env{'user.domain'};
 7737:                 $uname = $env{'user.name'};
 7738:             }
 7739:             my $uhome=&homeserver($uname,$udom);
 7740:             if (($uhome eq '') || ($uhome eq 'no_host')) {
 7741:                 $result = 'error: no_host';
 7742:             } else {
 7743:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
 7744:                 $storehash->{'host'} = $perlvar{'lonHostID'};
 7745: 
 7746:                 my $namevalue='';
 7747:                 foreach my $key (keys(%{$storehash})) {
 7748:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 7749:                 }
 7750:                 $namevalue=~s/\&$//;
 7751:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
 7752:                                   $namevalue,$uhome);
 7753:             }
 7754:         } else {
 7755:             $result = 'error: data to store was not a hash reference'; 
 7756:         }
 7757:     } else {
 7758:         $result= 'error: invalid requestkey'; 
 7759:     }
 7760:     return $result;
 7761: }
 7762: 
 7763: # ---------------------------------------------------------- Assign Custom Role
 7764: 
 7765: sub assigncustomrole {
 7766:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
 7767:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 7768:                        $end,$start,$deleteflag,$selfenroll,$context);
 7769: }
 7770: 
 7771: # ----------------------------------------------------------------- Revoke Role
 7772: 
 7773: sub revokerole {
 7774:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
 7775:     my $now=time;
 7776:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
 7777: }
 7778: 
 7779: # ---------------------------------------------------------- Revoke Custom Role
 7780: 
 7781: sub revokecustomrole {
 7782:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
 7783:     my $now=time;
 7784:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 7785:            $deleteflag,$selfenroll,$context);
 7786: }
 7787: 
 7788: # ------------------------------------------------------------ Disk usage
 7789: sub diskusage {
 7790:     my ($udom,$uname,$directorypath,$getpropath)=@_;
 7791:     $directorypath =~ s/\/$//;
 7792:     my $listing=&reply('du2:'.&escape($directorypath).':'
 7793:                        .&escape($getpropath).':'.&escape($uname).':'
 7794:                        .&escape($udom),homeserver($uname,$udom));
 7795:     if ($listing eq 'unknown_cmd') {
 7796:         if ($getpropath) {
 7797:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
 7798:         }
 7799:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
 7800:     }
 7801:     return $listing;
 7802: }
 7803: 
 7804: sub is_locked {
 7805:     my ($file_name, $domain, $user, $which) = @_;
 7806:     my @check;
 7807:     my $is_locked;
 7808:     push (@check,$file_name);
 7809:     my %locked = &get('file_permissions',\@check,
 7810: 		      $env{'user.domain'},$env{'user.name'});
 7811:     my ($tmp)=keys(%locked);
 7812:     if ($tmp=~/^error:/) { undef(%locked); }
 7813:     
 7814:     if (ref($locked{$file_name}) eq 'ARRAY') {
 7815:         $is_locked = 'false';
 7816:         foreach my $entry (@{$locked{$file_name}}) {
 7817:            if (ref($entry) eq 'ARRAY') {
 7818:                $is_locked = 'true';
 7819:                if (ref($which) eq 'ARRAY') {
 7820:                    push(@{$which},$entry);
 7821:                } else {
 7822:                    last;
 7823:                }
 7824:            }
 7825:        }
 7826:     } else {
 7827:         $is_locked = 'false';
 7828:     }
 7829:     return $is_locked;
 7830: }
 7831: 
 7832: sub declutter_portfile {
 7833:     my ($file) = @_;
 7834:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 7835:     return $file;
 7836: }
 7837: 
 7838: # ------------------------------------------------------------- Mark as Read Only
 7839: 
 7840: sub mark_as_readonly {
 7841:     my ($domain,$user,$files,$what) = @_;
 7842:     my %current_permissions = &dump('file_permissions',$domain,$user);
 7843:     my ($tmp)=keys(%current_permissions);
 7844:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 7845:     foreach my $file (@{$files}) {
 7846: 	$file = &declutter_portfile($file);
 7847:         push(@{$current_permissions{$file}},$what);
 7848:     }
 7849:     &put('file_permissions',\%current_permissions,$domain,$user);
 7850:     return;
 7851: }
 7852: 
 7853: # ------------------------------------------------------------Save Selected Files
 7854: 
 7855: sub save_selected_files {
 7856:     my ($user, $path, @files) = @_;
 7857:     my $filename = $user."savedfiles";
 7858:     my @other_files = &files_not_in_path($user, $path);
 7859:     open (OUT, '>'.$tmpdir.$filename);
 7860:     foreach my $file (@files) {
 7861:         print (OUT $env{'form.currentpath'}.$file."\n");
 7862:     }
 7863:     foreach my $file (@other_files) {
 7864:         print (OUT $file."\n");
 7865:     }
 7866:     close (OUT);
 7867:     return 'ok';
 7868: }
 7869: 
 7870: sub clear_selected_files {
 7871:     my ($user) = @_;
 7872:     my $filename = $user."savedfiles";
 7873:     open (OUT, '>'.LONCAPA::tempdir().$filename);
 7874:     print (OUT undef);
 7875:     close (OUT);
 7876:     return ("ok");    
 7877: }
 7878: 
 7879: sub files_in_path {
 7880:     my ($user, $path) = @_;
 7881:     my $filename = $user."savedfiles";
 7882:     my %return_files;
 7883:     open (IN, '<'.LONCAPA::tempdir().$filename);
 7884:     while (my $line_in = <IN>) {
 7885:         chomp ($line_in);
 7886:         my @paths_and_file = split (m!/!, $line_in);
 7887:         my $file_part = pop (@paths_and_file);
 7888:         my $path_part = join ('/', @paths_and_file);
 7889:         $path_part.='/';
 7890:         my $path_and_file = $path_part.$file_part;
 7891:         if ($path_part eq $path) {
 7892:             $return_files{$file_part}= 'selected';
 7893:         }
 7894:     }
 7895:     close (IN);
 7896:     return (\%return_files);
 7897: }
 7898: 
 7899: # called in portfolio select mode, to show files selected NOT in current directory
 7900: sub files_not_in_path {
 7901:     my ($user, $path) = @_;
 7902:     my $filename = $user."savedfiles";
 7903:     my @return_files;
 7904:     my $path_part;
 7905:     open(IN, '<'.LONCAPA::.$filename);
 7906:     while (my $line = <IN>) {
 7907:         #ok, I know it's clunky, but I want it to work
 7908:         my @paths_and_file = split(m|/|, $line);
 7909:         my $file_part = pop(@paths_and_file);
 7910:         chomp($file_part);
 7911:         my $path_part = join('/', @paths_and_file);
 7912:         $path_part .= '/';
 7913:         my $path_and_file = $path_part.$file_part;
 7914:         if ($path_part ne $path) {
 7915:             push(@return_files, ($path_and_file));
 7916:         }
 7917:     }
 7918:     close(OUT);
 7919:     return (@return_files);
 7920: }
 7921: 
 7922: #----------------------------------------------Get portfolio file permissions
 7923: 
 7924: sub get_portfile_permissions {
 7925:     my ($domain,$user) = @_;
 7926:     my %current_permissions = &dump('file_permissions',$domain,$user);
 7927:     my ($tmp)=keys(%current_permissions);
 7928:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 7929:     return \%current_permissions;
 7930: }
 7931: 
 7932: #---------------------------------------------Get portfolio file access controls
 7933: 
 7934: sub get_access_controls {
 7935:     my ($current_permissions,$group,$file) = @_;
 7936:     my %access;
 7937:     my $real_file = $file;
 7938:     $file =~ s/\.meta$//;
 7939:     if (defined($file)) {
 7940:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 7941:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 7942:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 7943:             }
 7944:         }
 7945:     } else {
 7946:         foreach my $key (keys(%{$current_permissions})) {
 7947:             if ($key =~ /\0accesscontrol$/) {
 7948:                 if (defined($group)) {
 7949:                     if ($key !~ m-^\Q$group\E/-) {
 7950:                         next;
 7951:                     }
 7952:                 }
 7953:                 my ($fullpath) = split(/\0/,$key);
 7954:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 7955:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 7956:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 7957:                     }
 7958:                 }
 7959:             }
 7960:         }
 7961:     }
 7962:     return %access;
 7963: }
 7964: 
 7965: sub modify_access_controls {
 7966:     my ($file_name,$changes,$domain,$user)=@_;
 7967:     my ($outcome,$deloutcome);
 7968:     my %store_permissions;
 7969:     my %new_values;
 7970:     my %new_control;
 7971:     my %translation;
 7972:     my @deletions = ();
 7973:     my $now = time;
 7974:     if (exists($$changes{'activate'})) {
 7975:         if (ref($$changes{'activate'}) eq 'HASH') {
 7976:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 7977:             my $numnew = scalar(@newitems);
 7978:             for (my $i=0; $i<$numnew; $i++) {
 7979:                 my $newkey = $newitems[$i];
 7980:                 my $newid = &Apache::loncommon::get_cgi_id();
 7981:                 if ($newkey =~ /^\d+:/) { 
 7982:                     $newkey =~ s/^(\d+)/$newid/;
 7983:                     $translation{$1} = $newid;
 7984:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 7985:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 7986:                     $translation{$1} = $newid;
 7987:                 }
 7988:                 $new_values{$file_name."\0".$newkey} = 
 7989:                                           $$changes{'activate'}{$newitems[$i]};
 7990:                 $new_control{$newkey} = $now;
 7991:             }
 7992:         }
 7993:     }
 7994:     my %todelete;
 7995:     my %changed_items;
 7996:     foreach my $action ('delete','update') {
 7997:         if (exists($$changes{$action})) {
 7998:             if (ref($$changes{$action}) eq 'HASH') {
 7999:                 foreach my $key (keys(%{$$changes{$action}})) {
 8000:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 8001:                     if ($action eq 'delete') { 
 8002:                         $todelete{$itemnum} = 1;
 8003:                     } else {
 8004:                         $changed_items{$itemnum} = $key;
 8005:                     }
 8006:                 }
 8007:             }
 8008:         }
 8009:     }
 8010:     # get lock on access controls for file.
 8011:     my $lockhash = {
 8012:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 8013:                                                        ':'.$env{'user.domain'},
 8014:                    }; 
 8015:     my $tries = 0;
 8016:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 8017:    
 8018:     while (($gotlock ne 'ok') && $tries <3) {
 8019:         $tries ++;
 8020:         sleep 1;
 8021:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 8022:     }
 8023:     if ($gotlock eq 'ok') {
 8024:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 8025:         my ($tmp)=keys(%curr_permissions);
 8026:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 8027:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 8028:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 8029:             if (ref($curr_controls) eq 'HASH') {
 8030:                 foreach my $control_item (keys(%{$curr_controls})) {
 8031:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 8032:                     if (defined($todelete{$itemnum})) {
 8033:                         push(@deletions,$file_name."\0".$control_item);
 8034:                     } else {
 8035:                         if (defined($changed_items{$itemnum})) {
 8036:                             $new_control{$changed_items{$itemnum}} = $now;
 8037:                             push(@deletions,$file_name."\0".$control_item);
 8038:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 8039:                         } else {
 8040:                             $new_control{$control_item} = $$curr_controls{$control_item};
 8041:                         }
 8042:                     }
 8043:                 }
 8044:             }
 8045:         }
 8046:         my ($group);
 8047:         if (&is_course($domain,$user)) {
 8048:             ($group,my $file) = split(/\//,$file_name,2);
 8049:         }
 8050:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 8051:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 8052:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 8053:         #  remove lock
 8054:         my @del_lock = ($file_name."\0".'locked_access_records');
 8055:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 8056:         my $sqlresult =
 8057:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
 8058:                                     $group);
 8059:     } else {
 8060:         $outcome = "error: could not obtain lockfile\n";  
 8061:     }
 8062:     return ($outcome,$deloutcome,\%new_values,\%translation);
 8063: }
 8064: 
 8065: sub make_public_indefinitely {
 8066:     my ($requrl) = @_;
 8067:     my $now = time;
 8068:     my $action = 'activate';
 8069:     my $aclnum = 0;
 8070:     if (&is_portfolio_url($requrl)) {
 8071:         my (undef,$udom,$unum,$file_name,$group) =
 8072:             &parse_portfolio_url($requrl);
 8073:         my $current_perms = &get_portfile_permissions($udom,$unum);
 8074:         my %access_controls = &get_access_controls($current_perms,
 8075:                                                    $group,$file_name);
 8076:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 8077:             my ($num,$scope,$end,$start) = 
 8078:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 8079:             if ($scope eq 'public') {
 8080:                 if ($start <= $now && $end == 0) {
 8081:                     $action = 'none';
 8082:                 } else {
 8083:                     $action = 'update';
 8084:                     $aclnum = $num;
 8085:                 }
 8086:                 last;
 8087:             }
 8088:         }
 8089:         if ($action eq 'none') {
 8090:              return 'ok';
 8091:         } else {
 8092:             my %changes;
 8093:             my $newend = 0;
 8094:             my $newstart = $now;
 8095:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 8096:             $changes{$action}{$newkey} = {
 8097:                 type => 'public',
 8098:                 time => {
 8099:                     start => $newstart,
 8100:                     end   => $newend,
 8101:                 },
 8102:             };
 8103:             my ($outcome,$deloutcome,$new_values,$translation) =
 8104:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 8105:             return $outcome;
 8106:         }
 8107:     } else {
 8108:         return 'invalid';
 8109:     }
 8110: }
 8111: 
 8112: #------------------------------------------------------Get Marked as Read Only
 8113: 
 8114: sub get_marked_as_readonly {
 8115:     my ($domain,$user,$what,$group) = @_;
 8116:     my $current_permissions = &get_portfile_permissions($domain,$user);
 8117:     my @readonly_files;
 8118:     my $cmp1=$what;
 8119:     if (ref($what)) { $cmp1=join('',@{$what}) };
 8120:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 8121:         if (defined($group)) {
 8122:             if ($file_name !~ m-^\Q$group\E/-) {
 8123:                 next;
 8124:             }
 8125:         }
 8126:         if (ref($value) eq "ARRAY"){
 8127:             foreach my $stored_what (@{$value}) {
 8128:                 my $cmp2=$stored_what;
 8129:                 if (ref($stored_what) eq 'ARRAY') {
 8130:                     $cmp2=join('',@{$stored_what});
 8131:                 }
 8132:                 if ($cmp1 eq $cmp2) {
 8133:                     push(@readonly_files, $file_name);
 8134:                     last;
 8135:                 } elsif (!defined($what)) {
 8136:                     push(@readonly_files, $file_name);
 8137:                     last;
 8138:                 }
 8139:             }
 8140:         }
 8141:     }
 8142:     return @readonly_files;
 8143: }
 8144: #-----------------------------------------------------------Get Marked as Read Only Hash
 8145: 
 8146: sub get_marked_as_readonly_hash {
 8147:     my ($current_permissions,$group,$what) = @_;
 8148:     my %readonly_files;
 8149:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 8150:         if (defined($group)) {
 8151:             if ($file_name !~ m-^\Q$group\E/-) {
 8152:                 next;
 8153:             }
 8154:         }
 8155:         if (ref($value) eq "ARRAY"){
 8156:             foreach my $stored_what (@{$value}) {
 8157:                 if (ref($stored_what) eq 'ARRAY') {
 8158:                     foreach my $lock_descriptor(@{$stored_what}) {
 8159:                         if ($lock_descriptor eq 'graded') {
 8160:                             $readonly_files{$file_name} = 'graded';
 8161:                         } elsif ($lock_descriptor eq 'handback') {
 8162:                             $readonly_files{$file_name} = 'handback';
 8163:                         } else {
 8164:                             if (!exists($readonly_files{$file_name})) {
 8165:                                 $readonly_files{$file_name} = 'locked';
 8166:                             }
 8167:                         }
 8168:                     }
 8169:                 } 
 8170:             }
 8171:         } 
 8172:     }
 8173:     return %readonly_files;
 8174: }
 8175: # ------------------------------------------------------------ Unmark as Read Only
 8176: 
 8177: sub unmark_as_readonly {
 8178:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 8179:     # for portfolio submissions, $what contains [$symb,$crsid] 
 8180:     my ($domain,$user,$what,$file_name,$group) = @_;
 8181:     $file_name = &declutter_portfile($file_name);
 8182:     my $symb_crs = $what;
 8183:     if (ref($what)) { $symb_crs=join('',@$what); }
 8184:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 8185:     my ($tmp)=keys(%current_permissions);
 8186:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 8187:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 8188:     foreach my $file (@readonly_files) {
 8189: 	my $clean_file = &declutter_portfile($file);
 8190: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 8191: 	my $current_locks = $current_permissions{$file};
 8192:         my @new_locks;
 8193:         my @del_keys;
 8194:         if (ref($current_locks) eq "ARRAY"){
 8195:             foreach my $locker (@{$current_locks}) {
 8196:                 my $compare=$locker;
 8197:                 if (ref($locker) eq 'ARRAY') {
 8198:                     $compare=join('',@{$locker});
 8199:                     if ($compare ne $symb_crs) {
 8200:                         push(@new_locks, $locker);
 8201:                     }
 8202:                 }
 8203:             }
 8204:             if (scalar(@new_locks) > 0) {
 8205:                 $current_permissions{$file} = \@new_locks;
 8206:             } else {
 8207:                 push(@del_keys, $file);
 8208:                 &del('file_permissions',\@del_keys, $domain, $user);
 8209:                 delete($current_permissions{$file});
 8210:             }
 8211:         }
 8212:     }
 8213:     &put('file_permissions',\%current_permissions,$domain,$user);
 8214:     return;
 8215: }
 8216: 
 8217: # ------------------------------------------------------------ Directory lister
 8218: 
 8219: sub dirlist {
 8220:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
 8221:     $uri=~s/^\///;
 8222:     $uri=~s/\/$//;
 8223:     my ($udom, $uname);
 8224:     if ($getuserdir) {
 8225:         $udom = $userdomain;
 8226:         $uname = $username;
 8227:     } else {
 8228:         (undef,$udom,$uname)=split(/\//,$uri);
 8229:         if(defined($userdomain)) {
 8230:             $udom = $userdomain;
 8231:         }
 8232:         if(defined($username)) {
 8233:             $uname = $username;
 8234:         }
 8235:     }
 8236:     my ($dirRoot,$listing,@listing_results);
 8237: 
 8238:     $dirRoot = $perlvar{'lonDocRoot'};
 8239:     if (defined($getpropath)) {
 8240:         $dirRoot = &propath($udom,$uname);
 8241:         $dirRoot =~ s/\/$//;
 8242:     } elsif (defined($getuserdir)) {
 8243:         my $subdir=$uname.'__';
 8244:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 8245:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
 8246:                    ."/$udom/$subdir/$uname";
 8247:     } elsif (defined($alternateRoot)) {
 8248:         $dirRoot = $alternateRoot;
 8249:     }
 8250: 
 8251:     if($udom) {
 8252:         if($uname) {
 8253:             my $uhome = &homeserver($uname,$udom);
 8254:             if ($uhome eq 'no_host') {
 8255:                 return ([],'no_host');
 8256:             }
 8257:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
 8258:                               .$getuserdir.':'.&escape($dirRoot)
 8259:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
 8260:             if ($listing eq 'unknown_cmd') {
 8261:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
 8262:             } else {
 8263:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 8264:             }
 8265:             if ($listing eq 'unknown_cmd') {
 8266:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
 8267:                 @listing_results = split(/:/,$listing);
 8268:             } else {
 8269:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 8270:             }
 8271:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
 8272:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
 8273:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 8274:                 return ([],$listing);
 8275:             } else {
 8276:                 return (\@listing_results);
 8277:             }
 8278:         } elsif(!$alternateRoot) {
 8279:             my (%allusers,%listerror);
 8280: 	    my %servers = &get_servers($udom,'library');
 8281:  	    foreach my $tryserver (keys(%servers)) {
 8282:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
 8283:                                   &escape($udom),$tryserver);
 8284:                 if ($listing eq 'unknown_cmd') {
 8285: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 8286: 				      $udom, $tryserver);
 8287:                 } else {
 8288:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
 8289:                 }
 8290: 		if ($listing eq 'unknown_cmd') {
 8291: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 8292: 				      $udom, $tryserver);
 8293: 		    @listing_results = split(/:/,$listing);
 8294: 		} else {
 8295: 		    @listing_results =
 8296: 			map { &unescape($_); } split(/:/,$listing);
 8297: 		}
 8298:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
 8299:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
 8300:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 8301:                     $listerror{$tryserver} = $listing;
 8302:                 } else {
 8303: 		    foreach my $line (@listing_results) {
 8304: 			my ($entry) = split(/&/,$line,2);
 8305: 			$allusers{$entry} = 1;
 8306: 		    }
 8307: 		}
 8308:             }
 8309:             my @alluserslist=();
 8310:             foreach my $user (sort(keys(%allusers))) {
 8311:                 push(@alluserslist,$user.'&user');
 8312:             }
 8313:             return (\@alluserslist);
 8314:         } else {
 8315:             return ([],'missing username');
 8316:         }
 8317:     } elsif(!defined($getpropath)) {
 8318:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
 8319:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
 8320:         return (\@all_domains);
 8321:     } else {
 8322:         return ([],'missing domain');
 8323:     }
 8324: }
 8325: 
 8326: # --------------------------------------------- GetFileTimestamp
 8327: # This function utilizes dirlist and returns the date stamp for
 8328: # when it was last modified.  It will also return an error of -1
 8329: # if an error occurs
 8330: 
 8331: sub GetFileTimestamp {
 8332:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
 8333:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 8334:     $studentName   = &LONCAPA::clean_username($studentName);
 8335:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
 8336:                                     undef,$getuserdir);
 8337:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 8338:         return -1;
 8339:     }
 8340:     if (ref($fileref) eq 'ARRAY') {
 8341:         my @stats = split('&',$fileref->[0]);
 8342:         # @stats contains first the filename, then the stat output
 8343:         return $stats[10]; # so this is 10 instead of 9.
 8344:     } else {
 8345:         return -1;
 8346:     }
 8347: }
 8348: 
 8349: sub stat_file {
 8350:     my ($uri) = @_;
 8351:     $uri = &clutter_with_no_wrapper($uri);
 8352: 
 8353:     my ($udom,$uname,$file);
 8354:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 8355: 	($udom,$uname,$file) =
 8356: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 8357: 	$file = 'userfiles/'.$file;
 8358:     }
 8359:     if ($uri =~ m-^/res/-) {
 8360: 	($udom,$uname) = 
 8361: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 8362: 	$file = $uri;
 8363:     }
 8364: 
 8365:     if (!$udom || !$uname || !$file) {
 8366: 	# unable to handle the uri
 8367: 	return ();
 8368:     }
 8369:     my $getpropath;
 8370:     if ($file =~ /^userfiles\//) {
 8371:         $getpropath = 1;
 8372:     }
 8373:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
 8374:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 8375:         return ();
 8376:     } else {
 8377:         if (ref($listref) eq 'ARRAY') {
 8378:             my @stats = split('&',$listref->[0]);
 8379: 	    shift(@stats); #filename is first
 8380: 	    return @stats;
 8381:         }
 8382:     }
 8383:     return ();
 8384: }
 8385: 
 8386: # -------------------------------------------------------- Value of a Condition
 8387: 
 8388: # gets the value of a specific preevaluated condition
 8389: #    stored in the string  $env{user.state.<cid>}
 8390: # or looks up a condition reference in the bighash and if if hasn't
 8391: # already been evaluated recurses into docondval to get the value of
 8392: # the condition, then memoizing it to 
 8393: #   $env{user.state.<cid>.<condition>}
 8394: sub directcondval {
 8395:     my $number=shift;
 8396:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 8397: 	&Apache::lonuserstate::evalstate();
 8398:     }
 8399:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 8400: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 8401:     } elsif ($number =~ /^_/) {
 8402: 	my $sub_condition;
 8403: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8404: 		&GDBM_READER(),0640)) {
 8405: 	    $sub_condition=$bighash{'conditions'.$number};
 8406: 	    untie(%bighash);
 8407: 	}
 8408: 	my $value = &docondval($sub_condition);
 8409: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
 8410: 	return $value;
 8411:     }
 8412:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 8413:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 8414:     } else {
 8415:        return 2;
 8416:     }
 8417: }
 8418: 
 8419: # get the collection of conditions for this resource
 8420: sub condval {
 8421:     my $condidx=shift;
 8422:     my $allpathcond='';
 8423:     foreach my $cond (split(/\|/,$condidx)) {
 8424: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 8425: 	    $allpathcond.=
 8426: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 8427: 	}
 8428:     }
 8429:     $allpathcond=~s/\|$//;
 8430:     return &docondval($allpathcond);
 8431: }
 8432: 
 8433: #evaluates an expression of conditions
 8434: sub docondval {
 8435:     my ($allpathcond) = @_;
 8436:     my $result=0;
 8437:     if ($env{'request.course.id'}
 8438: 	&& defined($allpathcond)) {
 8439: 	my $operand='|';
 8440: 	my @stack;
 8441: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 8442: 	    if ($chunk eq '(') {
 8443: 		push @stack,($operand,$result);
 8444: 	    } elsif ($chunk eq ')') {
 8445: 		my $before=pop @stack;
 8446: 		if (pop @stack eq '&') {
 8447: 		    $result=$result>$before?$before:$result;
 8448: 		} else {
 8449: 		    $result=$result>$before?$result:$before;
 8450: 		}
 8451: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 8452: 		$operand=$chunk;
 8453: 	    } else {
 8454: 		my $new=directcondval($chunk);
 8455: 		if ($operand eq '&') {
 8456: 		    $result=$result>$new?$new:$result;
 8457: 		} else {
 8458: 		    $result=$result>$new?$result:$new;
 8459: 		}
 8460: 	    }
 8461: 	}
 8462:     }
 8463:     return $result;
 8464: }
 8465: 
 8466: # ---------------------------------------------------- Devalidate courseresdata
 8467: 
 8468: sub devalidatecourseresdata {
 8469:     my ($coursenum,$coursedomain)=@_;
 8470:     my $hashid=$coursenum.':'.$coursedomain;
 8471:     &devalidate_cache_new('courseres',$hashid);
 8472: }
 8473: 
 8474: 
 8475: # --------------------------------------------------- Course Resourcedata Query
 8476: #
 8477: #  Parameters:
 8478: #      $coursenum    - Number of the course.
 8479: #      $coursedomain - Domain at which the course was created.
 8480: #  Returns:
 8481: #     A hash of the course parameters along (I think) with timestamps
 8482: #     and version info.
 8483: 
 8484: sub get_courseresdata {
 8485:     my ($coursenum,$coursedomain)=@_;
 8486:     my $coursehom=&homeserver($coursenum,$coursedomain);
 8487:     my $hashid=$coursenum.':'.$coursedomain;
 8488:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 8489:     my %dumpreply;
 8490:     unless (defined($cached)) {
 8491: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 8492: 	$result=\%dumpreply;
 8493: 	my ($tmp) = keys(%dumpreply);
 8494: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 8495: 	    &do_cache_new('courseres',$hashid,$result,600);
 8496: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 8497: 	    return $tmp;
 8498: 	} elsif ($tmp =~ /^(error)/) {
 8499: 	    $result=undef;
 8500: 	    &do_cache_new('courseres',$hashid,$result,600);
 8501: 	}
 8502:     }
 8503:     return $result;
 8504: }
 8505: 
 8506: sub devalidateuserresdata {
 8507:     my ($uname,$udom)=@_;
 8508:     my $hashid="$udom:$uname";
 8509:     &devalidate_cache_new('userres',$hashid);
 8510: }
 8511: 
 8512: sub get_userresdata {
 8513:     my ($uname,$udom)=@_;
 8514:     #most student don\'t have any data set, check if there is some data
 8515:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 8516: 
 8517:     my $hashid="$udom:$uname";
 8518:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 8519:     if (!defined($cached)) {
 8520: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 8521: 	$result=\%resourcedata;
 8522: 	&do_cache_new('userres',$hashid,$result,600);
 8523:     }
 8524:     my ($tmp)=keys(%$result);
 8525:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 8526: 	return $result;
 8527:     }
 8528:     #error 2 occurs when the .db doesn't exist
 8529:     if ($tmp!~/error: 2 /) {
 8530: 	&logthis("<font color=\"blue\">WARNING:".
 8531: 		 " Trying to get resource data for ".
 8532: 		 $uname." at ".$udom.": ".
 8533: 		 $tmp."</font>");
 8534:     } elsif ($tmp=~/error: 2 /) {
 8535: 	#&EXT_cache_set($udom,$uname);
 8536: 	&do_cache_new('userres',$hashid,undef,600);
 8537: 	undef($tmp); # not really an error so don't send it back
 8538:     }
 8539:     return $tmp;
 8540: }
 8541: #----------------------------------------------- resdata - return resource data
 8542: #  Purpose:
 8543: #    Return resource data for either users or for a course.
 8544: #  Parameters:
 8545: #     $name      - Course/user name.
 8546: #     $domain    - Name of the domain the user/course is registered on.
 8547: #     $type      - Type of thing $name is (must be 'course' or 'user'
 8548: #     @which     - Array of names of resources desired.
 8549: #  Returns:
 8550: #     The value of the first reasource in @which that is found in the
 8551: #     resource hash.
 8552: #  Exceptional Conditions:
 8553: #     If the $type passed in is not valid (not the string 'course' or 
 8554: #     'user', an undefined  reference is returned.
 8555: #     If none of the resources are found, an undef is returned
 8556: sub resdata {
 8557:     my ($name,$domain,$type,@which)=@_;
 8558:     my $result;
 8559:     if ($type eq 'course') {
 8560: 	$result=&get_courseresdata($name,$domain);
 8561:     } elsif ($type eq 'user') {
 8562: 	$result=&get_userresdata($name,$domain);
 8563:     }
 8564:     if (!ref($result)) { return $result; }    
 8565:     foreach my $item (@which) {
 8566: 	if (defined($result->{$item->[0]})) {
 8567: 	    return [$result->{$item->[0]},$item->[1]];
 8568: 	}
 8569:     }
 8570:     return undef;
 8571: }
 8572: 
 8573: #
 8574: # EXT resource caching routines
 8575: #
 8576: 
 8577: sub clear_EXT_cache_status {
 8578:     &delenv('cache.EXT.');
 8579: }
 8580: 
 8581: sub EXT_cache_status {
 8582:     my ($target_domain,$target_user) = @_;
 8583:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 8584:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 8585:         # We know already the user has no data
 8586:         return 1;
 8587:     } else {
 8588:         return 0;
 8589:     }
 8590: }
 8591: 
 8592: sub EXT_cache_set {
 8593:     my ($target_domain,$target_user) = @_;
 8594:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 8595:     #&appenv({$cachename => time});
 8596: }
 8597: 
 8598: # --------------------------------------------------------- Value of a Variable
 8599: sub EXT {
 8600: 
 8601:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
 8602:     unless ($varname) { return ''; }
 8603:     #get real user name/domain, courseid and symb
 8604:     my $courseid;
 8605:     my $publicuser;
 8606:     if ($symbparm) {
 8607: 	$symbparm=&get_symb_from_alias($symbparm);
 8608:     }
 8609:     if (!($uname && $udom)) {
 8610:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 8611:       if (!$symbparm) {	$symbparm=$cursymb; }
 8612:     } else {
 8613: 	$courseid=$env{'request.course.id'};
 8614:     }
 8615:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 8616:     my $rest;
 8617:     if (defined($therest[0])) {
 8618:        $rest=join('.',@therest);
 8619:     } else {
 8620:        $rest='';
 8621:     }
 8622: 
 8623:     my $qualifierrest=$qualifier;
 8624:     if ($rest) { $qualifierrest.='.'.$rest; }
 8625:     my $spacequalifierrest=$space;
 8626:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 8627:     if ($realm eq 'user') {
 8628: # --------------------------------------------------------------- user.resource
 8629: 	if ($space eq 'resource') {
 8630: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 8631: 		  || defined($Apache::lonhomework::parsing_a_task))
 8632: 		 &&
 8633: 		 ($symbparm eq &symbread()) ) {	
 8634: 		# if we are in the middle of processing the resource the
 8635: 		# get the value we are planning on committing
 8636:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 8637:                     return $Apache::lonhomework::results{$qualifierrest};
 8638:                 } else {
 8639:                     return $Apache::lonhomework::history{$qualifierrest};
 8640:                 }
 8641: 	    } else {
 8642: 		my %restored;
 8643: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 8644: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 8645: 		} else {
 8646: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 8647: 		}
 8648: 		return $restored{$qualifierrest};
 8649: 	    }
 8650: # ----------------------------------------------------------------- user.access
 8651:         } elsif ($space eq 'access') {
 8652: 	    # FIXME - not supporting calls for a specific user
 8653:             return &allowed($qualifier,$rest);
 8654: # ------------------------------------------ user.preferences, user.environment
 8655:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 8656: 	    if (($uname eq $env{'user.name'}) &&
 8657: 		($udom eq $env{'user.domain'})) {
 8658: 		return $env{join('.',('environment',$qualifierrest))};
 8659: 	    } else {
 8660: 		my %returnhash;
 8661: 		if (!$publicuser) {
 8662: 		    %returnhash=&userenvironment($udom,$uname,
 8663: 						 $qualifierrest);
 8664: 		}
 8665: 		return $returnhash{$qualifierrest};
 8666: 	    }
 8667: # ----------------------------------------------------------------- user.course
 8668:         } elsif ($space eq 'course') {
 8669: 	    # FIXME - not supporting calls for a specific user
 8670:             return $env{join('.',('request.course',$qualifier))};
 8671: # ------------------------------------------------------------------- user.role
 8672:         } elsif ($space eq 'role') {
 8673: 	    # FIXME - not supporting calls for a specific user
 8674:             my ($role,$where)=split(/\./,$env{'request.role'});
 8675:             if ($qualifier eq 'value') {
 8676: 		return $role;
 8677:             } elsif ($qualifier eq 'extent') {
 8678:                 return $where;
 8679:             }
 8680: # ----------------------------------------------------------------- user.domain
 8681:         } elsif ($space eq 'domain') {
 8682:             return $udom;
 8683: # ------------------------------------------------------------------- user.name
 8684:         } elsif ($space eq 'name') {
 8685:             return $uname;
 8686: # ---------------------------------------------------- Any other user namespace
 8687:         } else {
 8688: 	    my %reply;
 8689: 	    if (!$publicuser) {
 8690: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 8691: 	    }
 8692: 	    return $reply{$qualifierrest};
 8693:         }
 8694:     } elsif ($realm eq 'query') {
 8695: # ---------------------------------------------- pull stuff out of query string
 8696:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 8697: 						[$spacequalifierrest]);
 8698: 	return $env{'form.'.$spacequalifierrest}; 
 8699:    } elsif ($realm eq 'request') {
 8700: # ------------------------------------------------------------- request.browser
 8701:         if ($space eq 'browser') {
 8702: 	    if ($qualifier eq 'textremote') {
 8703: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
 8704: 		    return 1;
 8705: 		} else {
 8706: 		    return 0;
 8707: 		}
 8708: 	    } else {
 8709: 		return $env{'browser.'.$qualifier};
 8710: 	    }
 8711: # ------------------------------------------------------------ request.filename
 8712:         } else {
 8713:             return $env{'request.'.$spacequalifierrest};
 8714:         }
 8715:     } elsif ($realm eq 'course') {
 8716: # ---------------------------------------------------------- course.description
 8717:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 8718:     } elsif ($realm eq 'resource') {
 8719: 
 8720: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 8721: 	    if (!$symbparm) { $symbparm=&symbread(); }
 8722: 	}
 8723: 
 8724: 	if ($space eq 'title') {
 8725: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 8726: 	    return &gettitle($symbparm);
 8727: 	}
 8728: 	
 8729: 	if ($space eq 'map') {
 8730: 	    my ($map) = &decode_symb($symbparm);
 8731: 	    return &symbread($map);
 8732: 	}
 8733: 	if ($space eq 'filename') {
 8734: 	    if ($symbparm) {
 8735: 		return &clutter((&decode_symb($symbparm))[2]);
 8736: 	    }
 8737: 	    return &hreflocation('',$env{'request.filename'});
 8738: 	}
 8739: 
 8740: 	my ($section, $group, @groups);
 8741: 	my ($courselevelm,$courselevel);
 8742: 	if ($symbparm && defined($courseid) && 
 8743: 	    $courseid eq $env{'request.course.id'}) {
 8744: 
 8745: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 8746: 
 8747: # ----------------------------------------------------- Cascading lookup scheme
 8748: 	    my $symbp=$symbparm;
 8749: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 8750: 
 8751: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 8752: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 8753: 
 8754: 	    if (($env{'user.name'} eq $uname) &&
 8755: 		($env{'user.domain'} eq $udom)) {
 8756: 		$section=$env{'request.course.sec'};
 8757:                 @groups = split(/:/,$env{'request.course.groups'});  
 8758:                 @groups=&sort_course_groups($courseid,@groups); 
 8759: 	    } else {
 8760: 		if (! defined($usection)) {
 8761: 		    $section=&getsection($udom,$uname,$courseid);
 8762: 		} else {
 8763: 		    $section = $usection;
 8764: 		}
 8765:                 @groups = &get_users_groups($udom,$uname,$courseid);
 8766: 	    }
 8767: 
 8768: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 8769: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 8770: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 8771: 
 8772: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 8773: 	    my $courselevelr=$courseid.'.'.$symbparm;
 8774: 	    $courselevelm=$courseid.'.'.$mapparm;
 8775: 
 8776: # ----------------------------------------------------------- first, check user
 8777: 
 8778: 	    my $userreply=&resdata($uname,$udom,'user',
 8779: 				       ([$courselevelr,'resource'],
 8780: 					[$courselevelm,'map'     ],
 8781: 					[$courselevel, 'course'  ]));
 8782: 	    if (defined($userreply)) { return &get_reply($userreply); }
 8783: 
 8784: # ------------------------------------------------ second, check some of course
 8785:             my $coursereply;
 8786:             if (@groups > 0) {
 8787:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 8788:                                        $mapparm,$spacequalifierrest);
 8789:                 if (defined($coursereply)) { return &get_reply($coursereply); }
 8790:             }
 8791: 
 8792: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 8793: 				  $env{'course.'.$courseid.'.domain'},
 8794: 				  'course',
 8795: 				  ([$seclevelr,   'resource'],
 8796: 				   [$seclevelm,   'map'     ],
 8797: 				   [$seclevel,    'course'  ],
 8798: 				   [$courselevelr,'resource']));
 8799: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 8800: 
 8801: # ------------------------------------------------------ third, check map parms
 8802: 	    my %parmhash=();
 8803: 	    my $thisparm='';
 8804: 	    if (tie(%parmhash,'GDBM_File',
 8805: 		    $env{'request.course.fn'}.'_parms.db',
 8806: 		    &GDBM_READER(),0640)) {
 8807: 		$thisparm=$parmhash{$symbparm};
 8808: 		untie(%parmhash);
 8809: 	    }
 8810: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
 8811: 	}
 8812: # ------------------------------------------ fourth, look in resource metadata
 8813: 
 8814: 	$spacequalifierrest=~s/\./\_/;
 8815: 	my $filename;
 8816: 	if (!$symbparm) { $symbparm=&symbread(); }
 8817: 	if ($symbparm) {
 8818: 	    $filename=(&decode_symb($symbparm))[2];
 8819: 	} else {
 8820: 	    $filename=$env{'request.filename'};
 8821: 	}
 8822: 	my $metadata=&metadata($filename,$spacequalifierrest);
 8823: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 8824: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 8825: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 8826: 
 8827: # ---------------------------------------------- fourth, look in rest of course
 8828: 	if ($symbparm && defined($courseid) && 
 8829: 	    $courseid eq $env{'request.course.id'}) {
 8830: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 8831: 				     $env{'course.'.$courseid.'.domain'},
 8832: 				     'course',
 8833: 				     ([$courselevelm,'map'   ],
 8834: 				      [$courselevel, 'course']));
 8835: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 8836: 	}
 8837: # ------------------------------------------------------------------ Cascade up
 8838: 	unless ($space eq '0') {
 8839: 	    my @parts=split(/_/,$space);
 8840: 	    my $id=pop(@parts);
 8841: 	    my $part=join('_',@parts);
 8842: 	    if ($part eq '') { $part='0'; }
 8843: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 8844: 				 $symbparm,$udom,$uname,$section,1);
 8845: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
 8846: 	}
 8847: 	if ($recurse) { return undef; }
 8848: 	my $pack_def=&packages_tab_default($filename,$varname);
 8849: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
 8850: # ---------------------------------------------------- Any other user namespace
 8851:     } elsif ($realm eq 'environment') {
 8852: # ----------------------------------------------------------------- environment
 8853: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 8854: 	    return $env{'environment.'.$spacequalifierrest};
 8855: 	} else {
 8856: 	    if ($uname eq 'anonymous' && $udom eq '') {
 8857: 		return '';
 8858: 	    }
 8859: 	    my %returnhash=&userenvironment($udom,$uname,
 8860: 					    $spacequalifierrest);
 8861: 	    return $returnhash{$spacequalifierrest};
 8862: 	}
 8863:     } elsif ($realm eq 'system') {
 8864: # ----------------------------------------------------------------- system.time
 8865: 	if ($space eq 'time') {
 8866: 	    return time;
 8867:         }
 8868:     } elsif ($realm eq 'server') {
 8869: # ----------------------------------------------------------------- system.time
 8870: 	if ($space eq 'name') {
 8871: 	    return $ENV{'SERVER_NAME'};
 8872:         }
 8873:     }
 8874:     return '';
 8875: }
 8876: 
 8877: sub get_reply {
 8878:     my ($reply_value) = @_;
 8879:     if (ref($reply_value) eq 'ARRAY') {
 8880:         if (wantarray) {
 8881: 	    return @$reply_value;
 8882:         }
 8883:         return $reply_value->[0];
 8884:     } else {
 8885:         return $reply_value;
 8886:     }
 8887: }
 8888: 
 8889: sub check_group_parms {
 8890:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
 8891:     my @groupitems = ();
 8892:     my $resultitem;
 8893:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
 8894:     foreach my $group (@{$groups}) {
 8895:         foreach my $level (@levels) {
 8896:              my $item = $courseid.'.['.$group.'].'.$level->[0];
 8897:              push(@groupitems,[$item,$level->[1]]);
 8898:         }
 8899:     }
 8900:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
 8901:                             $env{'course.'.$courseid.'.domain'},
 8902:                                      'course',@groupitems);
 8903:     return $coursereply;
 8904: }
 8905: 
 8906: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
 8907:     my ($courseid,@groups) = @_;
 8908:     @groups = sort(@groups);
 8909:     return @groups;
 8910: }
 8911: 
 8912: sub packages_tab_default {
 8913:     my ($uri,$varname)=@_;
 8914:     my (undef,$part,$name)=split(/\./,$varname);
 8915: 
 8916:     my (@extension,@specifics,$do_default);
 8917:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
 8918: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 8919: 	if ($pack_type eq 'default') {
 8920: 	    $do_default=1;
 8921: 	} elsif ($pack_type eq 'extension') {
 8922: 	    push(@extension,[$package,$pack_type,$pack_part]);
 8923: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
 8924: 	    # only look at packages defaults for packages that this id is
 8925: 	    push(@specifics,[$package,$pack_type,$pack_part]);
 8926: 	}
 8927:     }
 8928:     # first look for a package that matches the requested part id
 8929:     foreach my $package (@specifics) {
 8930: 	my (undef,$pack_type,$pack_part)=@{$package};
 8931: 	next if ($pack_part ne $part);
 8932: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 8933: 	    return $packagetab{"$pack_type&$name&default"};
 8934: 	}
 8935:     }
 8936:     # look for any possible matching non extension_ package
 8937:     foreach my $package (@specifics) {
 8938: 	my (undef,$pack_type,$pack_part)=@{$package};
 8939: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 8940: 	    return $packagetab{"$pack_type&$name&default"};
 8941: 	}
 8942: 	if ($pack_type eq 'part') { $pack_part='0'; }
 8943: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
 8944: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
 8945: 	}
 8946:     }
 8947:     # look for any posible extension_ match
 8948:     foreach my $package (@extension) {
 8949: 	my ($package,$pack_type)=@{$package};
 8950: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 8951: 	    return $packagetab{"$pack_type&$name&default"};
 8952: 	}
 8953: 	if (defined($packagetab{$package."&$name&default"})) {
 8954: 	    return $packagetab{$package."&$name&default"};
 8955: 	}
 8956:     }
 8957:     # look for a global default setting
 8958:     if ($do_default && defined($packagetab{"default&$name&default"})) {
 8959: 	return $packagetab{"default&$name&default"};
 8960:     }
 8961:     return undef;
 8962: }
 8963: 
 8964: sub add_prefix_and_part {
 8965:     my ($prefix,$part)=@_;
 8966:     my $keyroot;
 8967:     if (defined($prefix) && $prefix !~ /^__/) {
 8968: 	# prefix that has a part already
 8969: 	$keyroot=$prefix;
 8970:     } elsif (defined($prefix)) {
 8971: 	# prefix that is missing a part
 8972: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 8973:     } else {
 8974: 	# no prefix at all
 8975: 	if (defined($part)) { $keyroot='_'.$part; }
 8976:     }
 8977:     return $keyroot;
 8978: }
 8979: 
 8980: # ---------------------------------------------------------------- Get metadata
 8981: 
 8982: my %metaentry;
 8983: my %importedpartids;
 8984: sub metadata {
 8985:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 8986:     $uri=&declutter($uri);
 8987:     # if it is a non metadata possible uri return quickly
 8988:     if (($uri eq '') || 
 8989: 	(($uri =~ m|^/*adm/|) && 
 8990: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
 8991:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
 8992: 	return undef;
 8993:     }
 8994:     if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) 
 8995: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
 8996: 	return undef;
 8997:     }
 8998:     my $filename=$uri;
 8999:     $uri=~s/\.meta$//;
 9000: #
 9001: # Is the metadata already cached?
 9002: # Look at timestamp of caching
 9003: # Everything is cached by the main uri, libraries are never directly cached
 9004: #
 9005:     if (!defined($liburi)) {
 9006: 	my ($result,$cached)=&is_cached_new('meta',$uri);
 9007: 	if (defined($cached)) { return $result->{':'.$what}; }
 9008:     }
 9009:     {
 9010: # Imported parts would go here
 9011:         my %importedids=();
 9012:         my @origfileimportpartids=();
 9013:         my $importedparts=0;
 9014: #
 9015: # Is this a recursive call for a library?
 9016: #
 9017: #	if (! exists($metacache{$uri})) {
 9018: #	    $metacache{$uri}={};
 9019: #	}
 9020: 	my $cachetime = 60*60;
 9021:         if ($liburi) {
 9022: 	    $liburi=&declutter($liburi);
 9023:             $filename=$liburi;
 9024:         } else {
 9025: 	    &devalidate_cache_new('meta',$uri);
 9026: 	    undef(%metaentry);
 9027: 	}
 9028:         my %metathesekeys=();
 9029:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 9030: 	my $metastring;
 9031: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
 9032: 	    my $which = &hreflocation('','/'.($liburi || $uri));
 9033: 	    $metastring = 
 9034: 		&Apache::lonnet::ssi_body($which,
 9035: 					  ('grade_target' => 'meta'));
 9036: 	    $cachetime = 1; # only want this cached in the child not long term
 9037: 	} elsif (($uri !~ m -^(editupload)/-) && 
 9038:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
 9039: 	    my $file=&filelocation('',&clutter($filename));
 9040: 	    #push(@{$metaentry{$uri.'.file'}},$file);
 9041: 	    $metastring=&getfile($file);
 9042: 	}
 9043:         my $parser=HTML::LCParser->new(\$metastring);
 9044:         my $token;
 9045:         undef %metathesekeys;
 9046:         while ($token=$parser->get_token) {
 9047: 	    if ($token->[0] eq 'S') {
 9048: 		if (defined($token->[2]->{'package'})) {
 9049: #
 9050: # This is a package - get package info
 9051: #
 9052: 		    my $package=$token->[2]->{'package'};
 9053: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 9054: 		    if (defined($token->[2]->{'id'})) { 
 9055: 			$keyroot.='_'.$token->[2]->{'id'}; 
 9056: 		    }
 9057: 		    if ($metaentry{':packages'}) {
 9058: 			$metaentry{':packages'}.=','.$package.$keyroot;
 9059: 		    } else {
 9060: 			$metaentry{':packages'}=$package.$keyroot;
 9061: 		    }
 9062: 		    foreach my $pack_entry (keys(%packagetab)) {
 9063: 			my $part=$keyroot;
 9064: 			$part=~s/^\_//;
 9065: 			if ($pack_entry=~/^\Q$package\E\&/ || 
 9066: 			    $pack_entry=~/^\Q$package\E_0\&/) {
 9067: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
 9068: 			    # ignore package.tab specified default values
 9069:                             # here &package_tab_default() will fetch those
 9070: 			    if ($subp eq 'default') { next; }
 9071: 			    my $value=$packagetab{$pack_entry};
 9072: 			    my $unikey;
 9073: 			    if ($pack =~ /_0$/) {
 9074: 				$unikey='parameter_0_'.$name;
 9075: 				$part=0;
 9076: 			    } else {
 9077: 				$unikey='parameter'.$keyroot.'_'.$name;
 9078: 			    }
 9079: 			    if ($subp eq 'display') {
 9080: 				$value.=' [Part: '.$part.']';
 9081: 			    }
 9082: 			    $metaentry{':'.$unikey.'.part'}=$part;
 9083: 			    $metathesekeys{$unikey}=1;
 9084: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 9085: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
 9086: 			    }
 9087: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
 9088: 				$metaentry{':'.$unikey}=
 9089: 				    $metaentry{':'.$unikey.'.default'};
 9090: 			    }
 9091: 			}
 9092: 		    }
 9093: 		} else {
 9094: #
 9095: # This is not a package - some other kind of start tag
 9096: #
 9097: 		    my $entry=$token->[1];
 9098: 		    my $unikey='';
 9099: 
 9100: 		    if ($entry eq 'import') {
 9101: #
 9102: # Importing a library here
 9103: #
 9104:                         my $location=$parser->get_text('/import');
 9105:                         my $dir=$filename;
 9106:                         $dir=~s|[^/]*$||;
 9107:                         $location=&filelocation($dir,$location);
 9108:                        
 9109:                         my $importmode=$token->[2]->{'importmode'};
 9110:                         if ($importmode eq 'problem') {
 9111: # Import as problem/response
 9112:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 9113:                         } elsif ($importmode eq 'part') {
 9114: # Import as part(s)
 9115:                            $importedparts=1;
 9116: # We need to get the original file and the imported file to get the part order correct
 9117: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
 9118: # Load and inspect original file
 9119:                            if ($#origfileimportpartids<0) {
 9120:                               undef(%importedpartids);
 9121:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
 9122:                               my $origfile=&getfile($origfilelocation);
 9123:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
 9124:                            }
 9125: 
 9126: # Load and inspect imported file
 9127:                            my $impfile=&getfile($location);
 9128:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
 9129:                            if ($#impfilepartids>=0) {
 9130: # This problem had parts
 9131:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
 9132:                            } else {
 9133: # Importing by turning a single problem into a problem part
 9134: # It gets the import-tags ID as part-ID
 9135:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
 9136:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
 9137:                            }
 9138:                         } else {
 9139: # Normal import
 9140:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 9141:                            if (defined($token->[2]->{'id'})) {
 9142:                               $unikey.='_'.$token->[2]->{'id'};
 9143:                            }
 9144:                         }
 9145: 
 9146: 			if ($depthcount<20) {
 9147: 			    my $metadata = 
 9148: 				&metadata($uri,'keys', $location,$unikey,
 9149: 					  $depthcount+1);
 9150: 			    foreach my $meta (split(',',$metadata)) {
 9151: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
 9152: 				$metathesekeys{$meta}=1;
 9153: 			    }
 9154: 			
 9155:                         }
 9156: 		    } else {
 9157: #
 9158: # Not importing, some other kind of non-package, non-library start tag
 9159: # 
 9160:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
 9161:                         if (defined($token->[2]->{'id'})) {
 9162:                             $unikey.='_'.$token->[2]->{'id'};
 9163:                         }
 9164: 			if (defined($token->[2]->{'name'})) { 
 9165: 			    $unikey.='_'.$token->[2]->{'name'}; 
 9166: 			}
 9167: 			$metathesekeys{$unikey}=1;
 9168: 			foreach my $param (@{$token->[3]}) {
 9169: 			    $metaentry{':'.$unikey.'.'.$param} =
 9170: 				$token->[2]->{$param};
 9171: 			}
 9172: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
 9173: 			my $default=$metaentry{':'.$unikey.'.default'};
 9174: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
 9175: 		 # only ws inside the tag, and not in default, so use default
 9176: 		 # as value
 9177: 			    $metaentry{':'.$unikey}=$default;
 9178: 			} elsif ( $internaltext =~ /\S/ ) {
 9179: 		  # something interesting inside the tag
 9180: 			    $metaentry{':'.$unikey}=$internaltext;
 9181: 			} else {
 9182: 		  # no interesting values, don't set a default
 9183: 			}
 9184: # end of not-a-package not-a-library import
 9185: 		    }
 9186: # end of not-a-package start tag
 9187: 		}
 9188: # the next is the end of "start tag"
 9189: 	    }
 9190: 	}
 9191: 	my ($extension) = ($uri =~ /\.(\w+)$/);
 9192: 	$extension = lc($extension);
 9193: 	if ($extension eq 'htm') { $extension='html'; }
 9194: 
 9195: 	foreach my $key (keys(%packagetab)) {
 9196: 	    #no specific packages #how's our extension
 9197: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
 9198: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
 9199: 					 \%metathesekeys);
 9200: 	}
 9201: 
 9202: 	if (!exists($metaentry{':packages'})
 9203: 	    || $packagetab{"import_defaults&extension_$extension"}) {
 9204: 	    foreach my $key (keys(%packagetab)) {
 9205: 		#no specific packages well let's get default then
 9206: 		if ($key!~/^default&/) { next; }
 9207: 		&metadata_create_package_def($uri,$key,'default',
 9208: 					     \%metathesekeys);
 9209: 	    }
 9210: 	}
 9211: # are there custom rights to evaluate
 9212: 	if ($metaentry{':copyright'} eq 'custom') {
 9213: 
 9214:     #
 9215:     # Importing a rights file here
 9216:     #
 9217: 	    unless ($depthcount) {
 9218: 		my $location=$metaentry{':customdistributionfile'};
 9219: 		my $dir=$filename;
 9220: 		$dir=~s|[^/]*$||;
 9221: 		$location=&filelocation($dir,$location);
 9222: 		my $rights_metadata =
 9223: 		    &metadata($uri,'keys',$location,'_rights',
 9224: 			      $depthcount+1);
 9225: 		foreach my $rights (split(',',$rights_metadata)) {
 9226: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
 9227: 		    $metathesekeys{$rights}=1;
 9228: 		}
 9229: 	    }
 9230: 	}
 9231: 	# uniqifiy package listing
 9232: 	my %seen;
 9233: 	my @uniq_packages =
 9234: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
 9235: 	$metaentry{':packages'} = join(',',@uniq_packages);
 9236: 
 9237:         if ($importedparts) {
 9238: # We had imported parts and need to rebuild partorder
 9239:            $metaentry{':partorder'}='';
 9240:            $metathesekeys{'partorder'}=1;
 9241:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
 9242:                if ($origfileimportpartids[$index] eq 'part') {
 9243: # original part, part of the problem
 9244:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
 9245:                } else {
 9246: # we have imported parts at this position
 9247:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
 9248:                }
 9249:            }
 9250:            $metaentry{':partorder'}=~s/^\,//;
 9251:         }
 9252: 
 9253: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
 9254: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
 9255: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
 9256: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
 9257: # this is the end of "was not already recently cached
 9258:     }
 9259:     return $metaentry{':'.$what};
 9260: }
 9261: 
 9262: sub metadata_create_package_def {
 9263:     my ($uri,$key,$package,$metathesekeys)=@_;
 9264:     my ($pack,$name,$subp)=split(/\&/,$key);
 9265:     if ($subp eq 'default') { next; }
 9266:     
 9267:     if (defined($metaentry{':packages'})) {
 9268: 	$metaentry{':packages'}.=','.$package;
 9269:     } else {
 9270: 	$metaentry{':packages'}=$package;
 9271:     }
 9272:     my $value=$packagetab{$key};
 9273:     my $unikey;
 9274:     $unikey='parameter_0_'.$name;
 9275:     $metaentry{':'.$unikey.'.part'}=0;
 9276:     $$metathesekeys{$unikey}=1;
 9277:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 9278: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
 9279:     }
 9280:     if (defined($metaentry{':'.$unikey.'.default'})) {
 9281: 	$metaentry{':'.$unikey}=
 9282: 	    $metaentry{':'.$unikey.'.default'};
 9283:     }
 9284: }
 9285: 
 9286: sub metadata_generate_part0 {
 9287:     my ($metadata,$metacache,$uri) = @_;
 9288:     my %allnames;
 9289:     foreach my $metakey (keys(%$metadata)) {
 9290: 	if ($metakey=~/^parameter\_(.*)/) {
 9291: 	  my $part=$$metacache{':'.$metakey.'.part'};
 9292: 	  my $name=$$metacache{':'.$metakey.'.name'};
 9293: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
 9294: 	    $allnames{$name}=$part;
 9295: 	  }
 9296: 	}
 9297:     }
 9298:     foreach my $name (keys(%allnames)) {
 9299:       $$metadata{"parameter_0_$name"}=1;
 9300:       my $key=":parameter_0_$name";
 9301:       $$metacache{"$key.part"}='0';
 9302:       $$metacache{"$key.name"}=$name;
 9303:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
 9304: 					   $allnames{$name}.'_'.$name.
 9305: 					   '.type'};
 9306:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
 9307: 			     '.display'};
 9308:       my $expr='[Part: '.$allnames{$name}.']';
 9309:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
 9310:       $$metacache{"$key.display"}=$olddis;
 9311:     }
 9312: }
 9313: 
 9314: # ------------------------------------------------------ Devalidate title cache
 9315: 
 9316: sub devalidate_title_cache {
 9317:     my ($url)=@_;
 9318:     if (!$env{'request.course.id'}) { return; }
 9319:     my $symb=&symbread($url);
 9320:     if (!$symb) { return; }
 9321:     my $key=$env{'request.course.id'}."\0".$symb;
 9322:     &devalidate_cache_new('title',$key);
 9323: }
 9324: 
 9325: # ------------------------------------------------- Get the title of a course
 9326: 
 9327: sub current_course_title {
 9328:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
 9329: }
 9330: # ------------------------------------------------- Get the title of a resource
 9331: 
 9332: sub gettitle {
 9333:     my $urlsymb=shift;
 9334:     my $symb=&symbread($urlsymb);
 9335:     if ($symb) {
 9336: 	my $key=$env{'request.course.id'}."\0".$symb;
 9337: 	my ($result,$cached)=&is_cached_new('title',$key);
 9338: 	if (defined($cached)) { 
 9339: 	    return $result;
 9340: 	}
 9341: 	my ($map,$resid,$url)=&decode_symb($symb);
 9342: 	my $title='';
 9343: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
 9344: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
 9345: 	} else {
 9346: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9347: 		    &GDBM_READER(),0640)) {
 9348: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
 9349: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
 9350: 		untie(%bighash);
 9351: 	    }
 9352: 	}
 9353: 	$title=~s/\&colon\;/\:/gs;
 9354: 	if ($title) {
 9355: 	    return &do_cache_new('title',$key,$title,600);
 9356: 	}
 9357: 	$urlsymb=$url;
 9358:     }
 9359:     my $title=&metadata($urlsymb,'title');
 9360:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
 9361:     return $title;
 9362: }
 9363: 
 9364: sub get_slot {
 9365:     my ($which,$cnum,$cdom)=@_;
 9366:     if (!$cnum || !$cdom) {
 9367: 	(undef,my $courseid)=&whichuser();
 9368: 	$cdom=$env{'course.'.$courseid.'.domain'};
 9369: 	$cnum=$env{'course.'.$courseid.'.num'};
 9370:     }
 9371:     my $key=join("\0",'slots',$cdom,$cnum,$which);
 9372:     my %slotinfo;
 9373:     if (exists($remembered{$key})) {
 9374: 	$slotinfo{$which} = $remembered{$key};
 9375:     } else {
 9376: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
 9377: 	&Apache::lonhomework::showhash(%slotinfo);
 9378: 	my ($tmp)=keys(%slotinfo);
 9379: 	if ($tmp=~/^error:/) { return (); }
 9380: 	$remembered{$key} = $slotinfo{$which};
 9381:     }
 9382:     if (ref($slotinfo{$which}) eq 'HASH') {
 9383: 	return %{$slotinfo{$which}};
 9384:     }
 9385:     return $slotinfo{$which};
 9386: }
 9387: # ------------------------------------------------- Update symbolic store links
 9388: 
 9389: sub symblist {
 9390:     my ($mapname,%newhash)=@_;
 9391:     $mapname=&deversion(&declutter($mapname));
 9392:     my %hash;
 9393:     if (($env{'request.course.fn'}) && (%newhash)) {
 9394:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 9395:                       &GDBM_WRCREAT(),0640)) {
 9396: 	    foreach my $url (keys(%newhash)) {
 9397: 		next if ($url eq 'last_known'
 9398: 			 && $env{'form.no_update_last_known'});
 9399: 		$hash{declutter($url)}=&encode_symb($mapname,
 9400: 						    $newhash{$url}->[1],
 9401: 						    $newhash{$url}->[0]);
 9402:             }
 9403:             if (untie(%hash)) {
 9404: 		return 'ok';
 9405:             }
 9406:         }
 9407:     }
 9408:     return 'error';
 9409: }
 9410: 
 9411: # --------------------------------------------------------------- Verify a symb
 9412: 
 9413: sub symbverify {
 9414:     my ($symb,$thisurl)=@_;
 9415:     my $thisfn=$thisurl;
 9416:     $thisfn=&declutter($thisfn);
 9417: # direct jump to resource in page or to a sequence - will construct own symbs
 9418:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
 9419: # check URL part
 9420:     my ($map,$resid,$url)=&decode_symb($symb);
 9421: 
 9422:     unless ($url eq $thisfn) { return 0; }
 9423: 
 9424:     $symb=&symbclean($symb);
 9425:     $thisurl=&deversion($thisurl);
 9426:     $thisfn=&deversion($thisfn);
 9427: 
 9428:     my %bighash;
 9429:     my $okay=0;
 9430: 
 9431:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9432:                             &GDBM_READER(),0640)) {
 9433:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
 9434:             $thisurl =~ s/\?.+$//;
 9435:         }
 9436:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
 9437:         unless ($ids) {
 9438:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
 9439:             $ids=$bighash{$idkey};
 9440:         }
 9441:         if ($ids) {
 9442: # ------------------------------------------------------------------- Has ID(s)
 9443: 	    foreach my $id (split(/\,/,$ids)) {
 9444: 	       my ($mapid,$resid)=split(/\./,$id);
 9445:                if ($thisfn =~ m{^/adm/wrapper/ext/}) {
 9446:                    $symb =~ s/\?.+$//;
 9447:                }
 9448:                if (
 9449:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
 9450:    eq $symb) { 
 9451: 		   if (($env{'request.role.adv'}) ||
 9452: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
 9453:                        ($thisurl eq '/adm/navmaps')) {
 9454: 		       $okay=1; 
 9455: 		   }
 9456: 	       }
 9457: 	   }
 9458:         }
 9459: 	untie(%bighash);
 9460:     }
 9461:     return $okay;
 9462: }
 9463: 
 9464: # --------------------------------------------------------------- Clean-up symb
 9465: 
 9466: sub symbclean {
 9467:     my $symb=shift;
 9468:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 9469: # remove version from map
 9470:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
 9471: 
 9472: # remove version from URL
 9473:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
 9474: 
 9475: # remove wrapper
 9476: 
 9477:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
 9478:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
 9479:     return $symb;
 9480: }
 9481: 
 9482: # ---------------------------------------------- Split symb to find map and url
 9483: 
 9484: sub encode_symb {
 9485:     my ($map,$resid,$url)=@_;
 9486:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
 9487: }
 9488: 
 9489: sub decode_symb {
 9490:     my $symb=shift;
 9491:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 9492:     my ($map,$resid,$url)=split(/___/,$symb);
 9493:     return (&fixversion($map),$resid,&fixversion($url));
 9494: }
 9495: 
 9496: sub fixversion {
 9497:     my $fn=shift;
 9498:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
 9499:     my %bighash;
 9500:     my $uri=&clutter($fn);
 9501:     my $key=$env{'request.course.id'}.'_'.$uri;
 9502: # is this cached?
 9503:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
 9504:     if (defined($cached)) { return $result; }
 9505: # unfortunately not cached, or expired
 9506:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9507: 	    &GDBM_READER(),0640)) {
 9508:  	if ($bighash{'version_'.$uri}) {
 9509:  	    my $version=$bighash{'version_'.$uri};
 9510:  	    unless (($version eq 'mostrecent') || 
 9511: 		    ($version==&getversion($uri))) {
 9512:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
 9513:  	    }
 9514:  	}
 9515:  	untie %bighash;
 9516:     }
 9517:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
 9518: }
 9519: 
 9520: sub deversion {
 9521:     my $url=shift;
 9522:     $url=~s/\.\d+\.(\w+)$/\.$1/;
 9523:     return $url;
 9524: }
 9525: 
 9526: # ------------------------------------------------------ Return symb list entry
 9527: 
 9528: sub symbread {
 9529:     my ($thisfn,$donotrecurse)=@_;
 9530:     my $cache_str='request.symbread.cached.'.$thisfn;
 9531:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
 9532: # no filename provided? try from environment
 9533:     unless ($thisfn) {
 9534:         if ($env{'request.symb'}) {
 9535: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
 9536: 	}
 9537: 	$thisfn=$env{'request.filename'};
 9538:     }
 9539:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 9540: # is that filename actually a symb? Verify, clean, and return
 9541:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
 9542: 	if (&symbverify($thisfn,$1)) {
 9543: 	    return $env{$cache_str}=&symbclean($thisfn);
 9544: 	}
 9545:     }
 9546:     $thisfn=declutter($thisfn);
 9547:     my %hash;
 9548:     my %bighash;
 9549:     my $syval='';
 9550:     if (($env{'request.course.fn'}) && ($thisfn)) {
 9551:         my $targetfn = $thisfn;
 9552:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
 9553:             $targetfn = 'adm/wrapper/'.$thisfn;
 9554:         }
 9555: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
 9556: 	    $targetfn=$1;
 9557: 	}
 9558:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 9559:                       &GDBM_READER(),0640)) {
 9560: 	    $syval=$hash{$targetfn};
 9561:             untie(%hash);
 9562:         }
 9563: # ---------------------------------------------------------- There was an entry
 9564:         if ($syval) {
 9565: 	    #unless ($syval=~/\_\d+$/) {
 9566: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
 9567: 		    #&appenv({'request.ambiguous' => $thisfn});
 9568: 		    #return $env{$cache_str}='';
 9569: 		#}    
 9570: 		#$syval.=$1;
 9571: 	    #}
 9572:         } else {
 9573: # ------------------------------------------------------- Was not in symb table
 9574:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9575:                             &GDBM_READER(),0640)) {
 9576: # ---------------------------------------------- Get ID(s) for current resource
 9577:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
 9578:               unless ($ids) { 
 9579:                  $ids=$bighash{'ids_/'.$thisfn};
 9580:               }
 9581:               unless ($ids) {
 9582: # alias?
 9583: 		  $ids=$bighash{'mapalias_'.$thisfn};
 9584:               }
 9585:               if ($ids) {
 9586: # ------------------------------------------------------------------- Has ID(s)
 9587:                  my @possibilities=split(/\,/,$ids);
 9588:                  if ($#possibilities==0) {
 9589: # ----------------------------------------------- There is only one possibility
 9590: 		     my ($mapid,$resid)=split(/\./,$ids);
 9591: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
 9592: 						    $resid,$thisfn);
 9593:                  } elsif (!$donotrecurse) {
 9594: # ------------------------------------------ There is more than one possibility
 9595:                      my $realpossible=0;
 9596:                      foreach my $id (@possibilities) {
 9597: 			 my $file=$bighash{'src_'.$id};
 9598:                          if (&allowed('bre',$file)) {
 9599:          		    my ($mapid,$resid)=split(/\./,$id);
 9600:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
 9601: 				$realpossible++;
 9602:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
 9603: 						    $resid,$thisfn);
 9604:                             }
 9605: 			 }
 9606:                      }
 9607: 		     if ($realpossible!=1) { $syval=''; }
 9608:                  } else {
 9609:                      $syval='';
 9610:                  }
 9611: 	      }
 9612:               untie(%bighash)
 9613:            }
 9614:         }
 9615:         if ($syval) {
 9616: 	    return $env{$cache_str}=$syval;
 9617:         }
 9618:     }
 9619:     &appenv({'request.ambiguous' => $thisfn});
 9620:     return $env{$cache_str}='';
 9621: }
 9622: 
 9623: # ---------------------------------------------------------- Return random seed
 9624: 
 9625: sub numval {
 9626:     my $txt=shift;
 9627:     $txt=~tr/A-J/0-9/;
 9628:     $txt=~tr/a-j/0-9/;
 9629:     $txt=~tr/K-T/0-9/;
 9630:     $txt=~tr/k-t/0-9/;
 9631:     $txt=~tr/U-Z/0-5/;
 9632:     $txt=~tr/u-z/0-5/;
 9633:     $txt=~s/\D//g;
 9634:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
 9635:     return int($txt);
 9636: }
 9637: 
 9638: sub numval2 {
 9639:     my $txt=shift;
 9640:     $txt=~tr/A-J/0-9/;
 9641:     $txt=~tr/a-j/0-9/;
 9642:     $txt=~tr/K-T/0-9/;
 9643:     $txt=~tr/k-t/0-9/;
 9644:     $txt=~tr/U-Z/0-5/;
 9645:     $txt=~tr/u-z/0-5/;
 9646:     $txt=~s/\D//g;
 9647:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 9648:     my $total;
 9649:     foreach my $val (@txts) { $total+=$val; }
 9650:     if ($_64bit) { if ($total > 2**32) { return -1; } }
 9651:     return int($total);
 9652: }
 9653: 
 9654: sub numval3 {
 9655:     use integer;
 9656:     my $txt=shift;
 9657:     $txt=~tr/A-J/0-9/;
 9658:     $txt=~tr/a-j/0-9/;
 9659:     $txt=~tr/K-T/0-9/;
 9660:     $txt=~tr/k-t/0-9/;
 9661:     $txt=~tr/U-Z/0-5/;
 9662:     $txt=~tr/u-z/0-5/;
 9663:     $txt=~s/\D//g;
 9664:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 9665:     my $total;
 9666:     foreach my $val (@txts) { $total+=$val; }
 9667:     if ($_64bit) { $total=(($total<<32)>>32); }
 9668:     return $total;
 9669: }
 9670: 
 9671: sub digest {
 9672:     my ($data)=@_;
 9673:     my $digest=&Digest::MD5::md5($data);
 9674:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
 9675:     my ($e,$f);
 9676:     {
 9677:         use integer;
 9678:         $e=($a+$b);
 9679:         $f=($c+$d);
 9680:         if ($_64bit) {
 9681:             $e=(($e<<32)>>32);
 9682:             $f=(($f<<32)>>32);
 9683:         }
 9684:     }
 9685:     if (wantarray) {
 9686: 	return ($e,$f);
 9687:     } else {
 9688: 	my $g;
 9689: 	{
 9690: 	    use integer;
 9691: 	    $g=($e+$f);
 9692: 	    if ($_64bit) {
 9693: 		$g=(($g<<32)>>32);
 9694: 	    }
 9695: 	}
 9696: 	return $g;
 9697:     }
 9698: }
 9699: 
 9700: sub latest_rnd_algorithm_id {
 9701:     return '64bit5';
 9702: }
 9703: 
 9704: sub get_rand_alg {
 9705:     my ($courseid)=@_;
 9706:     if (!$courseid) { $courseid=(&whichuser())[1]; }
 9707:     if ($courseid) {
 9708: 	return $env{"course.$courseid.rndseed"};
 9709:     }
 9710:     return &latest_rnd_algorithm_id();
 9711: }
 9712: 
 9713: sub validCODE {
 9714:     my ($CODE)=@_;
 9715:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
 9716:     return 0;
 9717: }
 9718: 
 9719: sub getCODE {
 9720:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
 9721:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
 9722: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
 9723: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
 9724: 	return $Apache::lonhomework::history{'resource.CODE'};
 9725:     }
 9726:     return undef;
 9727: }
 9728: #
 9729: #  Determines the random seed for a specific context:
 9730: #
 9731: # parameters:
 9732: #   symb      - in course context the symb for the seed.
 9733: #   course_id - The course id of the form domain_coursenum.
 9734: #   domain    - Domain for the user.
 9735: #   course    - Course for the user.
 9736: #   cenv      - environment of the course.
 9737: #
 9738: # NOTE:
 9739: #   All parameters are picked out of the environment if missing
 9740: #   or not defined.
 9741: #   If a symb cannot be determined the current time is used instead.
 9742: #
 9743: #  For a given well defined symb, courside, domain, username,
 9744: #  and course environment, the seed is reproducible.
 9745: #
 9746: sub rndseed {
 9747:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
 9748:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
 9749:     if (!defined($symb)) {
 9750: 	unless ($symb=$wsymb) { return time; }
 9751:     }
 9752:     if (!$courseid) { $courseid=$wcourseid; }
 9753:     if (!$domain) { $domain=$wdomain; }
 9754:     if (!$username) { $username=$wusername }
 9755: 
 9756:     my $which;
 9757:     if (defined($cenv->{'rndseed'})) {
 9758: 	$which = $cenv->{'rndseed'};
 9759:     } else {
 9760: 	$which =&get_rand_alg($courseid);
 9761:     }
 9762: 
 9763:     if (defined(&getCODE())) {
 9764: 
 9765: 	if ($which eq '64bit5') {
 9766: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
 9767: 	} elsif ($which eq '64bit4') {
 9768: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
 9769: 	} else {
 9770: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
 9771: 	}
 9772:     } elsif ($which eq '64bit5') {
 9773: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
 9774:     } elsif ($which eq '64bit4') {
 9775: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
 9776:     } elsif ($which eq '64bit3') {
 9777: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
 9778:     } elsif ($which eq '64bit2') {
 9779: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
 9780:     } elsif ($which eq '64bit') {
 9781: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
 9782:     }
 9783:     return &rndseed_32bit($symb,$courseid,$domain,$username);
 9784: }
 9785: 
 9786: sub rndseed_32bit {
 9787:     my ($symb,$courseid,$domain,$username)=@_;
 9788:     {
 9789: 	use integer;
 9790: 	my $symbchck=unpack("%32C*",$symb) << 27;
 9791: 	my $symbseed=numval($symb) << 22;
 9792: 	my $namechck=unpack("%32C*",$username) << 17;
 9793: 	my $nameseed=numval($username) << 12;
 9794: 	my $domainseed=unpack("%32C*",$domain) << 7;
 9795: 	my $courseseed=unpack("%32C*",$courseid);
 9796: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
 9797: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 9798: 	#&logthis("rndseed :$num:$symb");
 9799: 	if ($_64bit) { $num=(($num<<32)>>32); }
 9800: 	return $num;
 9801:     }
 9802: }
 9803: 
 9804: sub rndseed_64bit {
 9805:     my ($symb,$courseid,$domain,$username)=@_;
 9806:     {
 9807: 	use integer;
 9808: 	my $symbchck=unpack("%32S*",$symb) << 21;
 9809: 	my $symbseed=numval($symb) << 10;
 9810: 	my $namechck=unpack("%32S*",$username);
 9811: 	
 9812: 	my $nameseed=numval($username) << 21;
 9813: 	my $domainseed=unpack("%32S*",$domain) << 10;
 9814: 	my $courseseed=unpack("%32S*",$courseid);
 9815: 	
 9816: 	my $num1=$symbchck+$symbseed+$namechck;
 9817: 	my $num2=$nameseed+$domainseed+$courseseed;
 9818: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 9819: 	#&logthis("rndseed :$num:$symb");
 9820: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 9821: 	return "$num1,$num2";
 9822:     }
 9823: }
 9824: 
 9825: sub rndseed_64bit2 {
 9826:     my ($symb,$courseid,$domain,$username)=@_;
 9827:     {
 9828: 	use integer;
 9829: 	# strings need to be an even # of cahracters long, it it is odd the
 9830:         # last characters gets thrown away
 9831: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 9832: 	my $symbseed=numval($symb) << 10;
 9833: 	my $namechck=unpack("%32S*",$username.' ');
 9834: 	
 9835: 	my $nameseed=numval($username) << 21;
 9836: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 9837: 	my $courseseed=unpack("%32S*",$courseid.' ');
 9838: 	
 9839: 	my $num1=$symbchck+$symbseed+$namechck;
 9840: 	my $num2=$nameseed+$domainseed+$courseseed;
 9841: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 9842: 	#&logthis("rndseed :$num:$symb");
 9843: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 9844: 	return "$num1,$num2";
 9845:     }
 9846: }
 9847: 
 9848: sub rndseed_64bit3 {
 9849:     my ($symb,$courseid,$domain,$username)=@_;
 9850:     {
 9851: 	use integer;
 9852: 	# strings need to be an even # of cahracters long, it it is odd the
 9853:         # last characters gets thrown away
 9854: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 9855: 	my $symbseed=numval2($symb) << 10;
 9856: 	my $namechck=unpack("%32S*",$username.' ');
 9857: 	
 9858: 	my $nameseed=numval2($username) << 21;
 9859: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 9860: 	my $courseseed=unpack("%32S*",$courseid.' ');
 9861: 	
 9862: 	my $num1=$symbchck+$symbseed+$namechck;
 9863: 	my $num2=$nameseed+$domainseed+$courseseed;
 9864: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 9865: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 9866: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 9867: 	
 9868: 	return "$num1:$num2";
 9869:     }
 9870: }
 9871: 
 9872: sub rndseed_64bit4 {
 9873:     my ($symb,$courseid,$domain,$username)=@_;
 9874:     {
 9875: 	use integer;
 9876: 	# strings need to be an even # of cahracters long, it it is odd the
 9877:         # last characters gets thrown away
 9878: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 9879: 	my $symbseed=numval3($symb) << 10;
 9880: 	my $namechck=unpack("%32S*",$username.' ');
 9881: 	
 9882: 	my $nameseed=numval3($username) << 21;
 9883: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 9884: 	my $courseseed=unpack("%32S*",$courseid.' ');
 9885: 	
 9886: 	my $num1=$symbchck+$symbseed+$namechck;
 9887: 	my $num2=$nameseed+$domainseed+$courseseed;
 9888: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 9889: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 9890: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 9891: 	
 9892: 	return "$num1:$num2";
 9893:     }
 9894: }
 9895: 
 9896: sub rndseed_64bit5 {
 9897:     my ($symb,$courseid,$domain,$username)=@_;
 9898:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
 9899:     return "$num1:$num2";
 9900: }
 9901: 
 9902: sub rndseed_CODE_64bit {
 9903:     my ($symb,$courseid,$domain,$username)=@_;
 9904:     {
 9905: 	use integer;
 9906: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 9907: 	my $symbseed=numval2($symb);
 9908: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 9909: 	my $CODEseed=numval(&getCODE());
 9910: 	my $courseseed=unpack("%32S*",$courseid.' ');
 9911: 	my $num1=$symbseed+$CODEchck;
 9912: 	my $num2=$CODEseed+$courseseed+$symbchck;
 9913: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 9914: 	#&logthis("rndseed :$num1:$num2:$symb");
 9915: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 9916: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 9917: 	return "$num1:$num2";
 9918:     }
 9919: }
 9920: 
 9921: sub rndseed_CODE_64bit4 {
 9922:     my ($symb,$courseid,$domain,$username)=@_;
 9923:     {
 9924: 	use integer;
 9925: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 9926: 	my $symbseed=numval3($symb);
 9927: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 9928: 	my $CODEseed=numval3(&getCODE());
 9929: 	my $courseseed=unpack("%32S*",$courseid.' ');
 9930: 	my $num1=$symbseed+$CODEchck;
 9931: 	my $num2=$CODEseed+$courseseed+$symbchck;
 9932: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 9933: 	#&logthis("rndseed :$num1:$num2:$symb");
 9934: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 9935: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 9936: 	return "$num1:$num2";
 9937:     }
 9938: }
 9939: 
 9940: sub rndseed_CODE_64bit5 {
 9941:     my ($symb,$courseid,$domain,$username)=@_;
 9942:     my $code = &getCODE();
 9943:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
 9944:     return "$num1:$num2";
 9945: }
 9946: 
 9947: sub setup_random_from_rndseed {
 9948:     my ($rndseed)=@_;
 9949:     if ($rndseed =~/([,:])/) {
 9950: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
 9951: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
 9952:     } else {
 9953: 	&Math::Random::random_set_seed_from_phrase($rndseed);
 9954:     }
 9955: }
 9956: 
 9957: sub latest_receipt_algorithm_id {
 9958:     return 'receipt3';
 9959: }
 9960: 
 9961: sub recunique {
 9962:     my $fucourseid=shift;
 9963:     my $unique;
 9964:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
 9965: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 9966: 	$unique=$env{"course.$fucourseid.internal.encseed"};
 9967:     } else {
 9968: 	$unique=$perlvar{'lonReceipt'};
 9969:     }
 9970:     return unpack("%32C*",$unique);
 9971: }
 9972: 
 9973: sub recprefix {
 9974:     my $fucourseid=shift;
 9975:     my $prefix;
 9976:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
 9977: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 9978: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
 9979:     } else {
 9980: 	$prefix=$perlvar{'lonHostID'};
 9981:     }
 9982:     return unpack("%32C*",$prefix);
 9983: }
 9984: 
 9985: sub ireceipt {
 9986:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
 9987: 
 9988:     my $return =&recprefix($fucourseid).'-';
 9989: 
 9990:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
 9991: 	$env{'request.state'} eq 'construct') {
 9992: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
 9993: 	return $return;
 9994:     }
 9995: 
 9996:     my $cuname=unpack("%32C*",$funame);
 9997:     my $cudom=unpack("%32C*",$fudom);
 9998:     my $cucourseid=unpack("%32C*",$fucourseid);
 9999:     my $cusymb=unpack("%32C*",$fusymb);
10000:     my $cunique=&recunique($fucourseid);
10001:     my $cpart=unpack("%32S*",$part);
10002:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
10003: 
10004: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
10005: 			       
10006: 	$return.= ($cunique%$cuname+
10007: 		   $cunique%$cudom+
10008: 		   $cusymb%$cuname+
10009: 		   $cusymb%$cudom+
10010: 		   $cucourseid%$cuname+
10011: 		   $cucourseid%$cudom+
10012: 		   $cpart%$cuname+
10013: 		   $cpart%$cudom);
10014:     } else {
10015: 	$return.= ($cunique%$cuname+
10016: 		   $cunique%$cudom+
10017: 		   $cusymb%$cuname+
10018: 		   $cusymb%$cudom+
10019: 		   $cucourseid%$cuname+
10020: 		   $cucourseid%$cudom);
10021:     }
10022:     return $return;
10023: }
10024: 
10025: sub receipt {
10026:     my ($part)=@_;
10027:     my ($symb,$courseid,$domain,$name) = &whichuser();
10028:     return &ireceipt($name,$domain,$courseid,$symb,$part);
10029: }
10030: 
10031: sub whichuser {
10032:     my ($passedsymb)=@_;
10033:     my ($symb,$courseid,$domain,$name,$publicuser);
10034:     if (defined($env{'form.grade_symb'})) {
10035: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
10036: 	my $allowed=&allowed('vgr',$tmp_courseid);
10037: 	if (!$allowed &&
10038: 	    exists($env{'request.course.sec'}) &&
10039: 	    $env{'request.course.sec'} !~ /^\s*$/) {
10040: 	    $allowed=&allowed('vgr',$tmp_courseid.
10041: 			      '/'.$env{'request.course.sec'});
10042: 	}
10043: 	if ($allowed) {
10044: 	    ($symb)=&get_env_multiple('form.grade_symb');
10045: 	    $courseid=$tmp_courseid;
10046: 	    ($domain)=&get_env_multiple('form.grade_domain');
10047: 	    ($name)=&get_env_multiple('form.grade_username');
10048: 	    return ($symb,$courseid,$domain,$name,$publicuser);
10049: 	}
10050:     }
10051:     if (!$passedsymb) {
10052: 	$symb=&symbread();
10053:     } else {
10054: 	$symb=$passedsymb;
10055:     }
10056:     $courseid=$env{'request.course.id'};
10057:     $domain=$env{'user.domain'};
10058:     $name=$env{'user.name'};
10059:     if ($name eq 'public' && $domain eq 'public') {
10060: 	if (!defined($env{'form.username'})) {
10061: 	    $env{'form.username'}.=time.rand(10000000);
10062: 	}
10063: 	$name.=$env{'form.username'};
10064:     }
10065:     return ($symb,$courseid,$domain,$name,$publicuser);
10066: 
10067: }
10068: 
10069: # ------------------------------------------------------------ Serves up a file
10070: # returns either the contents of the file or 
10071: # -1 if the file doesn't exist
10072: #
10073: # if the target is a file that was uploaded via DOCS, 
10074: # a check will be made to see if a current copy exists on the local server,
10075: # if it does this will be served, otherwise a copy will be retrieved from
10076: # the home server for the course and stored in /home/httpd/html/userfiles on
10077: # the local server.   
10078: 
10079: sub getfile {
10080:     my ($file) = @_;
10081:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
10082:     &repcopy($file);
10083:     return &readfile($file);
10084: }
10085: 
10086: sub repcopy_userfile {
10087:     my ($file)=@_;
10088:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
10089:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
10090:     my ($cdom,$cnum,$filename) = 
10091: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
10092:     my $uri="/uploaded/$cdom/$cnum/$filename";
10093:     if (-e "$file") {
10094: # we already have a local copy, check it out
10095: 	my @fileinfo = stat($file);
10096: 	my $rtncode;
10097: 	my $info;
10098: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
10099: 	if ($lwpresp ne 'ok') {
10100: # there is no such file anymore, even though we had a local copy
10101: 	    if ($rtncode eq '404') {
10102: 		unlink($file);
10103: 	    }
10104: 	    return -1;
10105: 	}
10106: 	if ($info < $fileinfo[9]) {
10107: # nice, the file we have is up-to-date, just say okay
10108: 	    return 'ok';
10109: 	} else {
10110: # the file is outdated, get rid of it
10111: 	    unlink($file);
10112: 	}
10113:     }
10114: # one way or the other, at this point, we don't have the file
10115: # construct the correct path for the file
10116:     my @parts = ($cdom,$cnum); 
10117:     if ($filename =~ m|^(.+)/[^/]+$|) {
10118: 	push @parts, split(/\//,$1);
10119:     }
10120:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
10121:     foreach my $part (@parts) {
10122: 	$path .= '/'.$part;
10123: 	if (!-e $path) {
10124: 	    mkdir($path,0770);
10125: 	}
10126:     }
10127: # now the path exists for sure
10128: # get a user agent
10129:     my $ua=new LWP::UserAgent;
10130:     my $transferfile=$file.'.in.transfer';
10131: # FIXME: this should flock
10132:     if (-e $transferfile) { return 'ok'; }
10133:     my $request;
10134:     $uri=~s/^\///;
10135:     my $homeserver = &homeserver($cnum,$cdom);
10136:     my $protocol = $protocol{$homeserver};
10137:     $protocol = 'http' if ($protocol ne 'https');
10138:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
10139:     my $response=$ua->request($request,$transferfile);
10140: # did it work?
10141:     if ($response->is_error()) {
10142: 	unlink($transferfile);
10143: 	&logthis("Userfile repcopy failed for $uri");
10144: 	return -1;
10145:     }
10146: # worked, rename the transfer file
10147:     rename($transferfile,$file);
10148:     return 'ok';
10149: }
10150: 
10151: sub tokenwrapper {
10152:     my $uri=shift;
10153:     $uri=~s|^https?\://([^/]+)||;
10154:     $uri=~s|^/||;
10155:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
10156:     my $token=$1;
10157:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
10158:     if ($udom && $uname && $file) {
10159: 	$file=~s|(\?\.*)*$||;
10160:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
10161:         my $homeserver = &homeserver($uname,$udom);
10162:         my $protocol = $protocol{$homeserver};
10163:         $protocol = 'http' if ($protocol ne 'https');
10164:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
10165:                (($uri=~/\?/)?'&':'?').'token='.$token.
10166:                                '&tokenissued='.$perlvar{'lonHostID'};
10167:     } else {
10168:         return '/adm/notfound.html';
10169:     }
10170: }
10171: 
10172: # call with reqtype HEAD: get last modification time
10173: # call with reqtype GET: get the file contents
10174: # Do not call this with reqtype GET for large files! It loads everything into memory
10175: #
10176: sub getuploaded {
10177:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
10178:     $uri=~s/^\///;
10179:     my $homeserver = &homeserver($cnum,$cdom);
10180:     my $protocol = $protocol{$homeserver};
10181:     $protocol = 'http' if ($protocol ne 'https');
10182:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
10183:     my $ua=new LWP::UserAgent;
10184:     my $request=new HTTP::Request($reqtype,$uri);
10185:     my $response=$ua->request($request);
10186:     $$rtncode = $response->code;
10187:     if (! $response->is_success()) {
10188: 	return 'failed';
10189:     }      
10190:     if ($reqtype eq 'HEAD') {
10191: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
10192:     } elsif ($reqtype eq 'GET') {
10193: 	$$info = $response->content;
10194:     }
10195:     return 'ok';
10196: }
10197: 
10198: sub readfile {
10199:     my $file = shift;
10200:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
10201:     my $fh;
10202:     open($fh,"<$file");
10203:     my $a='';
10204:     while (my $line = <$fh>) { $a .= $line; }
10205:     return $a;
10206: }
10207: 
10208: sub filelocation {
10209:     my ($dir,$file) = @_;
10210:     my $location;
10211:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
10212: 
10213:     if ($file =~ m-^/adm/-) {
10214: 	$file=~s-^/adm/wrapper/-/-;
10215: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
10216:     }
10217: 
10218:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
10219:         $location = $file;
10220:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
10221:         my ($udom,$uname,$filename)=
10222:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
10223:         my $home=&homeserver($uname,$udom);
10224:         my $is_me=0;
10225:         my @ids=&current_machine_ids();
10226:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
10227:         if ($is_me) {
10228:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
10229:         } else {
10230:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
10231:   	      $udom.'/'.$uname.'/'.$filename;
10232:         }
10233:     } elsif ($file =~ m-^/adm/-) {
10234: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
10235:     } else {
10236:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
10237:         $file=~s:^/(res|priv)/:/:;
10238:         my $space=$1;
10239:         if ( !( $file =~ m:^/:) ) {
10240:             $location = $dir. '/'.$file;
10241:         } else {
10242:             $location = '/home/httpd/html/'.$space.$file;
10243:         }
10244:     }
10245:     $location=~s://+:/:g; # remove duplicate /
10246:     while ($location=~m{/\.\./}) {
10247: 	if ($location =~ m{/[^/]+/\.\./}) {
10248: 	    $location=~ s{/[^/]+/\.\./}{/}g;
10249: 	} else {
10250: 	    $location=~ s{/\.\./}{/}g;
10251: 	}
10252:     } #remove dir/..
10253:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
10254:     return $location;
10255: }
10256: 
10257: sub hreflocation {
10258:     my ($dir,$file)=@_;
10259:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
10260: 	$file=filelocation($dir,$file);
10261:     } elsif ($file=~m-^/adm/-) {
10262: 	$file=~s-^/adm/wrapper/-/-;
10263: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
10264:     }
10265:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
10266: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
10267:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
10268: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
10269: 	    -/uploaded/$1/$2/-x;
10270:     }
10271:     if ($file=~ m{^/userfiles/}) {
10272: 	$file =~ s{^/userfiles/}{/uploaded/};
10273:     }
10274:     return $file;
10275: }
10276: 
10277: 
10278: 
10279: 
10280: 
10281: sub current_machine_domains {
10282:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
10283: }
10284: 
10285: sub machine_domains {
10286:     my ($hostname) = @_;
10287:     my @domains;
10288:     my %hostname = &all_hostnames();
10289:     while( my($id, $name) = each(%hostname)) {
10290: #	&logthis("-$id-$name-$hostname-");
10291: 	if ($hostname eq $name) {
10292: 	    push(@domains,&host_domain($id));
10293: 	}
10294:     }
10295:     return @domains;
10296: }
10297: 
10298: sub current_machine_ids {
10299:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
10300: }
10301: 
10302: sub machine_ids {
10303:     my ($hostname) = @_;
10304:     $hostname ||= &hostname($perlvar{'lonHostID'});
10305:     my @ids;
10306:     my %name_to_host = &all_names();
10307:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
10308: 	return @{ $name_to_host{$hostname} };
10309:     }
10310:     return;
10311: }
10312: 
10313: sub additional_machine_domains {
10314:     my @domains;
10315:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
10316:     while( my $line = <$fh>) {
10317:         $line =~ s/\s//g;
10318:         push(@domains,$line);
10319:     }
10320:     return @domains;
10321: }
10322: 
10323: sub default_login_domain {
10324:     my $domain = $perlvar{'lonDefDomain'};
10325:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
10326:     foreach my $posdom (&current_machine_domains(),
10327:                         &additional_machine_domains()) {
10328:         if (lc($posdom) eq lc($testdomain)) {
10329:             $domain=$posdom;
10330:             last;
10331:         }
10332:     }
10333:     return $domain;
10334: }
10335: 
10336: # ------------------------------------------------------------- Declutters URLs
10337: 
10338: sub declutter {
10339:     my $thisfn=shift;
10340:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
10341:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
10342:     $thisfn=~s/^\///;
10343:     $thisfn=~s|^adm/wrapper/||;
10344:     $thisfn=~s|^adm/coursedocs/showdoc/||;
10345:     $thisfn=~s/^res\///;
10346:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
10347:         $thisfn=~s/\?.+$//;
10348:     }
10349:     return $thisfn;
10350: }
10351: 
10352: # ------------------------------------------------------------- Clutter up URLs
10353: 
10354: sub clutter {
10355:     my $thisfn='/'.&declutter(shift);
10356:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
10357: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
10358:        $thisfn='/res'.$thisfn; 
10359:     }
10360:     if ($thisfn !~m|^/adm|) {
10361: 	if ($thisfn =~ m|^/ext/|) {
10362: 	    $thisfn='/adm/wrapper'.$thisfn;
10363: 	} else {
10364: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
10365: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
10366: 	    if ($embstyle eq 'ssi'
10367: 		|| ($embstyle eq 'hdn')
10368: 		|| ($embstyle eq 'rat')
10369: 		|| ($embstyle eq 'prv')
10370: 		|| ($embstyle eq 'ign')) {
10371: 		#do nothing with these
10372: 	    } elsif (($embstyle eq 'img') 
10373: 		|| ($embstyle eq 'emb')
10374: 		|| ($embstyle eq 'wrp')) {
10375: 		$thisfn='/adm/wrapper'.$thisfn;
10376: 	    } elsif ($embstyle eq 'unk'
10377: 		     && $thisfn!~/\.(sequence|page)$/) {
10378: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
10379: 	    } else {
10380: #		&logthis("Got a blank emb style");
10381: 	    }
10382: 	}
10383:     }
10384:     return $thisfn;
10385: }
10386: 
10387: sub clutter_with_no_wrapper {
10388:     my $uri = &clutter(shift);
10389:     if ($uri =~ m-^/adm/-) {
10390: 	$uri =~ s-^/adm/wrapper/-/-;
10391: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
10392:     }
10393:     return $uri;
10394: }
10395: 
10396: sub freeze_escape {
10397:     my ($value)=@_;
10398:     if (ref($value)) {
10399: 	$value=&nfreeze($value);
10400: 	return '__FROZEN__'.&escape($value);
10401:     }
10402:     return &escape($value);
10403: }
10404: 
10405: 
10406: sub thaw_unescape {
10407:     my ($value)=@_;
10408:     if ($value =~ /^__FROZEN__/) {
10409: 	substr($value,0,10,undef);
10410: 	$value=&unescape($value);
10411: 	return &thaw($value);
10412:     }
10413:     return &unescape($value);
10414: }
10415: 
10416: sub correct_line_ends {
10417:     my ($result)=@_;
10418:     $$result =~s/\r\n/\n/mg;
10419:     $$result =~s/\r/\n/mg;
10420: }
10421: # ================================================================ Main Program
10422: 
10423: sub goodbye {
10424:    &logthis("Starting Shut down");
10425: #not converted to using infrastruture and probably shouldn't be
10426:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
10427: #converted
10428: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
10429:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
10430: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
10431: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
10432: #1.1 only
10433: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
10434: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
10435: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
10436: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
10437:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
10438:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
10439:    &logthis(sprintf("%-20s is %s",'hits',$hits));
10440:    &flushcourselogs();
10441:    &logthis("Shutting down");
10442: }
10443: 
10444: sub get_dns {
10445:     my ($url,$func,$ignore_cache) = @_;
10446:     if (!$ignore_cache) {
10447: 	my ($content,$cached)=
10448: 	    &Apache::lonnet::is_cached_new('dns',$url);
10449: 	if ($cached) {
10450: 	    &$func($content);
10451: 	    return;
10452: 	}
10453:     }
10454: 
10455:     my %alldns;
10456:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
10457:     foreach my $dns (<$config>) {
10458: 	next if ($dns !~ /^\^(\S*)/x);
10459:         my $line = $1;
10460:         my ($host,$protocol) = split(/:/,$line);
10461:         if ($protocol ne 'https') {
10462:             $protocol = 'http';
10463:         }
10464: 	$alldns{$host} = $protocol;
10465:     }
10466:     while (%alldns) {
10467: 	my ($dns) = keys(%alldns);
10468: 	my $ua=new LWP::UserAgent;
10469:         $ua->timeout(30);
10470: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
10471: 	my $response=$ua->request($request);
10472:         delete($alldns{$dns});
10473: 	next if ($response->is_error());
10474: 	my @content = split("\n",$response->content);
10475: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
10476: 	&$func(\@content);
10477: 	return;
10478:     }
10479:     close($config);
10480:     my $which = (split('/',$url))[3];
10481:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
10482:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
10483:     my @content = <$config>;
10484:     &$func(\@content);
10485:     return;
10486: }
10487: # ------------------------------------------------------------ Read domain file
10488: {
10489:     my $loaded;
10490:     my %domain;
10491: 
10492:     sub parse_domain_tab {
10493: 	my ($lines) = @_;
10494: 	foreach my $line (@$lines) {
10495: 	    next if ($line =~ /^(\#|\s*$ )/x);
10496: 
10497: 	    chomp($line);
10498: 	    my ($name,@elements) = split(/:/,$line,9);
10499: 	    my %this_domain;
10500: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
10501: 			       'lang_def', 'city', 'longi', 'lati',
10502: 			       'primary') {
10503: 		$this_domain{$field} = shift(@elements);
10504: 	    }
10505: 	    $domain{$name} = \%this_domain;
10506: 	}
10507:     }
10508: 
10509:     sub reset_domain_info {
10510: 	undef($loaded);
10511: 	undef(%domain);
10512:     }
10513: 
10514:     sub load_domain_tab {
10515: 	my ($ignore_cache) = @_;
10516: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
10517: 	my $fh;
10518: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
10519: 	    my @lines = <$fh>;
10520: 	    &parse_domain_tab(\@lines);
10521: 	}
10522: 	close($fh);
10523: 	$loaded = 1;
10524:     }
10525: 
10526:     sub domain {
10527: 	&load_domain_tab() if (!$loaded);
10528: 
10529: 	my ($name,$what) = @_;
10530: 	return if ( !exists($domain{$name}) );
10531: 
10532: 	if (!$what) {
10533: 	    return $domain{$name}{'description'};
10534: 	}
10535: 	return $domain{$name}{$what};
10536:     }
10537: 
10538:     sub domain_info {
10539:         &load_domain_tab() if (!$loaded);
10540:         return %domain;
10541:     }
10542: 
10543: }
10544: 
10545: 
10546: # ------------------------------------------------------------- Read hosts file
10547: {
10548:     my %hostname;
10549:     my %hostdom;
10550:     my %libserv;
10551:     my $loaded;
10552:     my %name_to_host;
10553:     my %internetdom;
10554:     my %LC_dns_serv;
10555: 
10556:     sub parse_hosts_tab {
10557: 	my ($file) = @_;
10558: 	foreach my $configline (@$file) {
10559: 	    next if ($configline =~ /^(\#|\s*$ )/x);
10560:             chomp($configline);
10561: 	    if ($configline =~ /^\^/) {
10562:                 if ($configline =~ /^\^([\w.\-]+)/) {
10563:                     $LC_dns_serv{$1} = 1;
10564:                 }
10565:                 next;
10566:             }
10567: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
10568: 	    $name=~s/\s//g;
10569: 	    if ($id && $domain && $role && $name) {
10570: 		$hostname{$id}=$name;
10571: 		push(@{$name_to_host{$name}}, $id);
10572: 		$hostdom{$id}=$domain;
10573: 		if ($role eq 'library') { $libserv{$id}=$name; }
10574:                 if (defined($protocol)) {
10575:                     if ($protocol eq 'https') {
10576:                         $protocol{$id} = $protocol;
10577:                     } else {
10578:                         $protocol{$id} = 'http'; 
10579:                     }
10580:                 } else {
10581:                     $protocol{$id} = 'http';
10582:                 }
10583:                 if (defined($intdom)) {
10584:                     $internetdom{$id} = $intdom;
10585:                 }
10586: 	    }
10587: 	}
10588:     }
10589:     
10590:     sub reset_hosts_info {
10591: 	&purge_remembered();
10592: 	&reset_domain_info();
10593: 	&reset_hosts_ip_info();
10594: 	undef(%name_to_host);
10595: 	undef(%hostname);
10596: 	undef(%hostdom);
10597: 	undef(%libserv);
10598: 	undef($loaded);
10599:     }
10600: 
10601:     sub load_hosts_tab {
10602: 	my ($ignore_cache) = @_;
10603: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
10604: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
10605: 	my @config = <$config>;
10606: 	&parse_hosts_tab(\@config);
10607: 	close($config);
10608: 	$loaded=1;
10609:     }
10610: 
10611:     sub hostname {
10612: 	&load_hosts_tab() if (!$loaded);
10613: 
10614: 	my ($lonid) = @_;
10615: 	return $hostname{$lonid};
10616:     }
10617: 
10618:     sub all_hostnames {
10619: 	&load_hosts_tab() if (!$loaded);
10620: 
10621: 	return %hostname;
10622:     }
10623: 
10624:     sub all_names {
10625: 	&load_hosts_tab() if (!$loaded);
10626: 
10627: 	return %name_to_host;
10628:     }
10629: 
10630:     sub all_host_domain {
10631:         &load_hosts_tab() if (!$loaded);
10632:         return %hostdom;
10633:     }
10634: 
10635:     sub is_library {
10636: 	&load_hosts_tab() if (!$loaded);
10637: 
10638: 	return exists($libserv{$_[0]});
10639:     }
10640: 
10641:     sub all_library {
10642: 	&load_hosts_tab() if (!$loaded);
10643: 
10644: 	return %libserv;
10645:     }
10646: 
10647:     sub unique_library {
10648: 	#2x reverse removes all hostnames that appear more than once
10649:         my %unique = reverse &all_library();
10650:         return reverse %unique;
10651:     }
10652: 
10653:     sub get_servers {
10654: 	&load_hosts_tab() if (!$loaded);
10655: 
10656: 	my ($domain,$type) = @_;
10657: 	my %possible_hosts = ($type eq 'library') ? %libserv
10658: 	                                          : %hostname;
10659: 	my %result;
10660: 	if (ref($domain) eq 'ARRAY') {
10661: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
10662: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
10663: 		    $result{$host} = $hostname;
10664: 		}
10665: 	    }
10666: 	} else {
10667: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
10668: 		if ($hostdom{$host} eq $domain) {
10669: 		    $result{$host} = $hostname;
10670: 		}
10671: 	    }
10672: 	}
10673: 	return %result;
10674:     }
10675: 
10676:     sub get_unique_servers {
10677:         my %unique = reverse &get_servers(@_);
10678: 	return reverse %unique;
10679:     }
10680: 
10681:     sub host_domain {
10682: 	&load_hosts_tab() if (!$loaded);
10683: 
10684: 	my ($lonid) = @_;
10685: 	return $hostdom{$lonid};
10686:     }
10687: 
10688:     sub all_domains {
10689: 	&load_hosts_tab() if (!$loaded);
10690: 
10691: 	my %seen;
10692: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
10693: 	return @uniq;
10694:     }
10695: 
10696:     sub internet_dom {
10697:         &load_hosts_tab() if (!$loaded);
10698: 
10699:         my ($lonid) = @_;
10700:         return $internetdom{$lonid};
10701:     }
10702: 
10703:     sub is_LC_dns {
10704:         &load_hosts_tab() if (!$loaded);
10705: 
10706:         my ($hostname) = @_;
10707:         return exists($LC_dns_serv{$hostname});
10708:     }
10709: 
10710: }
10711: 
10712: { 
10713:     my %iphost;
10714:     my %name_to_ip;
10715:     my %lonid_to_ip;
10716: 
10717:     sub get_hosts_from_ip {
10718: 	my ($ip) = @_;
10719: 	my %iphosts = &get_iphost();
10720: 	if (ref($iphosts{$ip})) {
10721: 	    return @{$iphosts{$ip}};
10722: 	}
10723: 	return;
10724:     }
10725:     
10726:     sub reset_hosts_ip_info {
10727: 	undef(%iphost);
10728: 	undef(%name_to_ip);
10729: 	undef(%lonid_to_ip);
10730:     }
10731: 
10732:     sub get_host_ip {
10733: 	my ($lonid) = @_;
10734: 	if (exists($lonid_to_ip{$lonid})) {
10735: 	    return $lonid_to_ip{$lonid};
10736: 	}
10737: 	my $name=&hostname($lonid);
10738:    	my $ip = gethostbyname($name);
10739: 	return if (!$ip || length($ip) ne 4);
10740: 	$ip=inet_ntoa($ip);
10741: 	$name_to_ip{$name}   = $ip;
10742: 	$lonid_to_ip{$lonid} = $ip;
10743: 	return $ip;
10744:     }
10745:     
10746:     sub get_iphost {
10747: 	my ($ignore_cache) = @_;
10748: 
10749: 	if (!$ignore_cache) {
10750: 	    if (%iphost) {
10751: 		return %iphost;
10752: 	    }
10753: 	    my ($ip_info,$cached)=
10754: 		&Apache::lonnet::is_cached_new('iphost','iphost');
10755: 	    if ($cached) {
10756: 		%iphost      = %{$ip_info->[0]};
10757: 		%name_to_ip  = %{$ip_info->[1]};
10758: 		%lonid_to_ip = %{$ip_info->[2]};
10759: 		return %iphost;
10760: 	    }
10761: 	}
10762: 
10763: 	# get yesterday's info for fallback
10764: 	my %old_name_to_ip;
10765: 	my ($ip_info,$cached)=
10766: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
10767: 	if ($cached) {
10768: 	    %old_name_to_ip = %{$ip_info->[1]};
10769: 	}
10770: 
10771: 	my %name_to_host = &all_names();
10772: 	foreach my $name (keys(%name_to_host)) {
10773: 	    my $ip;
10774: 	    if (!exists($name_to_ip{$name})) {
10775: 		$ip = gethostbyname($name);
10776: 		if (!$ip || length($ip) ne 4) {
10777: 		    if (defined($old_name_to_ip{$name})) {
10778: 			$ip = $old_name_to_ip{$name};
10779: 			&logthis("Can't find $name defaulting to old $ip");
10780: 		    } else {
10781: 			&logthis("Name $name no IP found");
10782: 			next;
10783: 		    }
10784: 		} else {
10785: 		    $ip=inet_ntoa($ip);
10786: 		}
10787: 		$name_to_ip{$name} = $ip;
10788: 	    } else {
10789: 		$ip = $name_to_ip{$name};
10790: 	    }
10791: 	    foreach my $id (@{ $name_to_host{$name} }) {
10792: 		$lonid_to_ip{$id} = $ip;
10793: 	    }
10794: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
10795: 	}
10796: 	&Apache::lonnet::do_cache_new('iphost','iphost',
10797: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
10798: 				      48*60*60);
10799: 
10800: 	return %iphost;
10801:     }
10802: 
10803:     #
10804:     #  Given a DNS returns the loncapa host name for that DNS 
10805:     # 
10806:     sub host_from_dns {
10807:         my ($dns) = @_;
10808:         my @hosts;
10809:         my $ip;
10810: 
10811:         if (exists($name_to_ip{$dns})) {
10812:             $ip = $name_to_ip{$dns};
10813:         }
10814:         if (!$ip) {
10815:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
10816:             if (length($ip) == 4) { 
10817: 	        $ip   = &IO::Socket::inet_ntoa($ip);
10818:             }
10819:         }
10820:         if ($ip) {
10821: 	    @hosts = get_hosts_from_ip($ip);
10822: 	    return $hosts[0];
10823:         }
10824:         return undef;
10825:     }
10826: 
10827:     sub get_internet_names {
10828:         my ($lonid) = @_;
10829:         return if ($lonid eq '');
10830:         my ($idnref,$cached)=
10831:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
10832:         if ($cached) {
10833:             return $idnref;
10834:         }
10835:         my $ip = &get_host_ip($lonid);
10836:         my @hosts = &get_hosts_from_ip($ip);
10837:         my %iphost = &get_iphost();
10838:         my (@idns,%seen);
10839:         foreach my $id (@hosts) {
10840:             my $dom = &host_domain($id);
10841:             my $prim_id = &domain($dom,'primary');
10842:             my $prim_ip = &get_host_ip($prim_id);
10843:             next if ($seen{$prim_ip});
10844:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
10845:                 foreach my $id (@{$iphost{$prim_ip}}) {
10846:                     my $intdom = &internet_dom($id);
10847:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
10848:                         push(@idns,$intdom);
10849:                     }
10850:                 }
10851:             }
10852:             $seen{$prim_ip} = 1;
10853:         }
10854:         return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
10855:     }
10856: 
10857: }
10858: 
10859: sub all_loncaparevs {
10860:     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);
10861: }
10862: 
10863: BEGIN {
10864: 
10865: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
10866:     unless ($readit) {
10867: {
10868:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
10869:     %perlvar = (%perlvar,%{$configvars});
10870: }
10871: 
10872: 
10873: # ------------------------------------------------------ Read spare server file
10874: {
10875:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
10876: 
10877:     while (my $configline=<$config>) {
10878:        chomp($configline);
10879:        if ($configline) {
10880: 	   my ($host,$type) = split(':',$configline,2);
10881: 	   if (!defined($type) || $type eq '') { $type = 'default' };
10882: 	   push(@{ $spareid{$type} }, $host);
10883:        }
10884:     }
10885:     close($config);
10886: }
10887: # ------------------------------------------------------------ Read permissions
10888: {
10889:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
10890: 
10891:     while (my $configline=<$config>) {
10892: 	chomp($configline);
10893: 	if ($configline) {
10894: 	    my ($role,$perm)=split(/ /,$configline);
10895: 	    if ($perm ne '') { $pr{$role}=$perm; }
10896: 	}
10897:     }
10898:     close($config);
10899: }
10900: 
10901: # -------------------------------------------- Read plain texts for permissions
10902: {
10903:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
10904: 
10905:     while (my $configline=<$config>) {
10906: 	chomp($configline);
10907: 	if ($configline) {
10908: 	    my ($short,@plain)=split(/:/,$configline);
10909:             %{$prp{$short}} = ();
10910: 	    if (@plain > 0) {
10911:                 $prp{$short}{'std'} = $plain[0];
10912:                 for (my $i=1; $i<@plain; $i++) {
10913:                     $prp{$short}{'alt'.$i} = $plain[$i];  
10914:                 }
10915:             }
10916: 	}
10917:     }
10918:     close($config);
10919: }
10920: 
10921: # ---------------------------------------------------------- Read package table
10922: {
10923:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
10924: 
10925:     while (my $configline=<$config>) {
10926: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
10927: 	chomp($configline);
10928: 	my ($short,$plain)=split(/:/,$configline);
10929: 	my ($pack,$name)=split(/\&/,$short);
10930: 	if ($plain ne '') {
10931: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
10932: 	    $packagetab{$short}=$plain; 
10933: 	}
10934:     }
10935:     close($config);
10936: }
10937: 
10938: # ---------------------------------------------------------- Read loncaparev table
10939: {
10940:     if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
10941:         if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
10942:             while (my $configline=<$config>) {
10943:                 chomp($configline);
10944:                 my ($hostid,$loncaparev)=split(/:/,$configline);
10945:                 $loncaparevs{$hostid}=$loncaparev;
10946:             }
10947:             close($config);
10948:         }
10949:     }
10950: }
10951: 
10952: # ---------------------------------------------------------- Read serverhostID table
10953: {
10954:     if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
10955:         if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
10956:             while (my $configline=<$config>) {
10957:                 chomp($configline);
10958:                 my ($name,$id)=split(/:/,$configline);
10959:                 $serverhomeIDs{$name}=$id;
10960:             }
10961:             close($config);
10962:         }
10963:     }
10964: }
10965: 
10966: {
10967:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
10968:     if (-e $file) {
10969:         my $parser = HTML::LCParser->new($file);
10970:         while (my $token = $parser->get_token()) {
10971:             if ($token->[0] eq 'S') {
10972:                 my $item = $token->[1];
10973:                 my $name = $token->[2]{'name'};
10974:                 my $value = $token->[2]{'value'};
10975:                 if ($item ne '' && $name ne '' && $value ne '') {
10976:                     my $release = $parser->get_text();
10977:                     $release =~ s/(^\s*|\s*$ )//gx;
10978:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
10979:                 }
10980:             }
10981:         }
10982:     }
10983: }
10984: 
10985: # ---------------------------------------------------------- Read managers table
10986: {
10987:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
10988:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
10989:             while (my $configline=<$config>) {
10990:                 chomp($configline);
10991:                 next if ($configline =~ /^\#/);
10992:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
10993:                     $managerstab{$configline} = 1;
10994:                 }
10995:             }
10996:             close($config);
10997:         }
10998:     }
10999: }
11000: 
11001: # ------------- set up temporary directory
11002: {
11003:     $tmpdir = LONCAPA::tempdir();
11004: 
11005: }
11006: 
11007: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
11008: 				'compress_threshold'=> 20_000,
11009:  			        });
11010: 
11011: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
11012: $dumpcount=0;
11013: $locknum=0;
11014: 
11015: &logtouch();
11016: &logthis('<font color="yellow">INFO: Read configuration</font>');
11017: $readit=1;
11018:     {
11019: 	use integer;
11020: 	my $test=(2**32)+1;
11021: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
11022: 	&logthis(" Detected 64bit platform ($_64bit)");
11023:     }
11024: }
11025: }
11026: 
11027: 1;
11028: __END__
11029: 
11030: =pod
11031: 
11032: =head1 NAME
11033: 
11034: Apache::lonnet - Subroutines to ask questions about things in the network.
11035: 
11036: =head1 SYNOPSIS
11037: 
11038: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
11039: 
11040:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
11041: 
11042: Common parameters:
11043: 
11044: =over 4
11045: 
11046: =item *
11047: 
11048: $uname : an internal username (if $cname expecting a course Id specifically)
11049: 
11050: =item *
11051: 
11052: $udom : a domain (if $cdom expecting a course's domain specifically)
11053: 
11054: =item *
11055: 
11056: $symb : a resource instance identifier
11057: 
11058: =item *
11059: 
11060: $namespace : the name of a .db file that contains the data needed or
11061: being set.
11062: 
11063: =back
11064: 
11065: =head1 OVERVIEW
11066: 
11067: lonnet provides subroutines which interact with the
11068: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
11069: about classes, users, and resources.
11070: 
11071: For many of these objects you can also use this to store data about
11072: them or modify them in various ways.
11073: 
11074: =head2 Symbs
11075: 
11076: To identify a specific instance of a resource, LON-CAPA uses symbols
11077: or "symbs"X<symb>. These identifiers are built from the URL of the
11078: map, the resource number of the resource in the map, and the URL of
11079: the resource itself. The latter is somewhat redundant, but might help
11080: if maps change.
11081: 
11082: An example is
11083: 
11084:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
11085: 
11086: The respective map entry is
11087: 
11088:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
11089:   title="Problem 2">
11090:  </resource>
11091: 
11092: Symbs are used by the random number generator, as well as to store and
11093: restore data specific to a certain instance of for example a problem.
11094: 
11095: =head2 Storing And Retrieving Data
11096: 
11097: X<store()>X<cstore()>X<restore()>Three of the most important functions
11098: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
11099: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
11100: is is the non-critical message twin of cstore. These functions are for
11101: handlers to store a perl hash to a user's permanent data space in an
11102: easy manner, and to retrieve it again on another call. It is expected
11103: that a handler would use this once at the beginning to retrieve data,
11104: and then again once at the end to send only the new data back.
11105: 
11106: The data is stored in the user's data directory on the user's
11107: homeserver under the ID of the course.
11108: 
11109: The hash that is returned by restore will have all of the previous
11110: value for all of the elements of the hash.
11111: 
11112: Example:
11113: 
11114:  #creating a hash
11115:  my %hash;
11116:  $hash{'foo'}='bar';
11117: 
11118:  #storing it
11119:  &Apache::lonnet::cstore(\%hash);
11120: 
11121:  #changing a value
11122:  $hash{'foo'}='notbar';
11123: 
11124:  #adding a new value
11125:  $hash{'bar'}='foo';
11126:  &Apache::lonnet::cstore(\%hash);
11127: 
11128:  #retrieving the hash
11129:  my %history=&Apache::lonnet::restore();
11130: 
11131:  #print the hash
11132:  foreach my $key (sort(keys(%history))) {
11133:    print("\%history{$key} = $history{$key}");
11134:  }
11135: 
11136: Will print out:
11137: 
11138:  %history{1:foo} = bar
11139:  %history{1:keys} = foo:timestamp
11140:  %history{1:timestamp} = 990455579
11141:  %history{2:bar} = foo
11142:  %history{2:foo} = notbar
11143:  %history{2:keys} = foo:bar:timestamp
11144:  %history{2:timestamp} = 990455580
11145:  %history{bar} = foo
11146:  %history{foo} = notbar
11147:  %history{timestamp} = 990455580
11148:  %history{version} = 2
11149: 
11150: Note that the special hash entries C<keys>, C<version> and
11151: C<timestamp> were added to the hash. C<version> will be equal to the
11152: total number of versions of the data that have been stored. The
11153: C<timestamp> attribute will be the UNIX time the hash was
11154: stored. C<keys> is available in every historical section to list which
11155: keys were added or changed at a specific historical revision of a
11156: hash.
11157: 
11158: B<Warning>: do not store the hash that restore returns directly. This
11159: will cause a mess since it will restore the historical keys as if the
11160: were new keys. I.E. 1:foo will become 1:1:foo etc.
11161: 
11162: Calling convention:
11163: 
11164:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
11165:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
11166: 
11167: For more detailed information, see lonnet specific documentation.
11168: 
11169: =head1 RETURN MESSAGES
11170: 
11171: =over 4
11172: 
11173: =item * B<con_lost>: unable to contact remote host
11174: 
11175: =item * B<con_delayed>: unable to contact remote host, message will be delivered
11176: when the connection is brought back up
11177: 
11178: =item * B<con_failed>: unable to contact remote host and unable to save message
11179: for later delivery
11180: 
11181: =item * B<error:>: an error a occurred, a description of the error follows the :
11182: 
11183: =item * B<no_such_host>: unable to fund a host associated with the user/domain
11184: that was requested
11185: 
11186: =back
11187: 
11188: =head1 PUBLIC SUBROUTINES
11189: 
11190: =head2 Session Environment Functions
11191: 
11192: =over 4
11193: 
11194: =item * 
11195: X<appenv()>
11196: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
11197: the user envirnoment file, and will be restored for each access this
11198: user makes during this session, also modifies the %env for the current
11199: process. Optional rolesarrayref - if defined contains a reference to an array
11200: of roles which are exempt from the restriction on modifying user.role entries 
11201: in the user's environment.db and in %env.    
11202: 
11203: =item *
11204: X<delenv()>
11205: B<delenv($delthis,$regexp)>: removes all items from the session
11206: environment file that begin with $delthis. If the 
11207: optional second arg - $regexp - is true, $delthis is treated as a 
11208: regular expression, otherwise \Q$delthis\E is used. 
11209: The values are also deleted from the current processes %env.
11210: 
11211: =item * get_env_multiple($name) 
11212: 
11213: gets $name from the %env hash, it seemlessly handles the cases where multiple
11214: values may be defined and end up as an array ref.
11215: 
11216: returns an array of values
11217: 
11218: =back
11219: 
11220: =head2 User Information
11221: 
11222: =over 4
11223: 
11224: =item *
11225: X<queryauthenticate()>
11226: B<queryauthenticate($uname,$udom)>: try to determine user's current 
11227: authentication scheme
11228: 
11229: =item *
11230: X<authenticate()>
11231: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
11232: authenticate user from domain's lib servers (first use the current
11233: one). C<$upass> should be the users password.
11234: $checkdefauth is optional (value is 1 if a check should be made to
11235:    authenticate user using default authentication method, and allow
11236:    account creation if username does not have account in the domain).
11237: $clientcancheckhost is optional (value is 1 if checking whether the
11238:    server can host will occur on the client side in lonauth.pm).   
11239: 
11240: =item *
11241: X<homeserver()>
11242: B<homeserver($uname,$udom)>: find the server which has
11243: the user's directory and files (there must be only one), this caches
11244: the answer, and also caches if there is a borken connection.
11245: 
11246: =item *
11247: X<idget()>
11248: B<idget($udom,@ids)>: find the usernames behind a list of IDs
11249: (IDs are a unique resource in a domain, there must be only 1 ID per
11250: username, and only 1 username per ID in a specific domain) (returns
11251: hash: id=>name,id=>name)
11252: 
11253: =item *
11254: X<idrget()>
11255: B<idrget($udom,@unames)>: find the IDs behind a list of
11256: usernames (returns hash: name=>id,name=>id)
11257: 
11258: =item *
11259: X<idput()>
11260: B<idput($udom,%ids)>: store away a list of names and associated IDs
11261: 
11262: =item *
11263: X<rolesinit()>
11264: B<rolesinit($udom,$username,$authhost)>: get user privileges
11265: 
11266: =item *
11267: X<getsection()>
11268: B<getsection($udom,$uname,$cname)>: finds the section of student in the
11269: course $cname, return section name/number or '' for "not in course"
11270: and '-1' for "no section"
11271: 
11272: =item *
11273: X<userenvironment()>
11274: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
11275: passed in @what from the requested user's environment, returns a hash
11276: 
11277: =item * 
11278: X<userlog_query()>
11279: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
11280: activity.log file. %filters defines filters applied when parsing the
11281: log file. These can be start or end timestamps, or the type of action
11282: - log to look for Login or Logout events, check for Checkin or
11283: Checkout, role for role selection. The response is in the form
11284: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
11285: escaped strings of the action recorded in the activity.log file.
11286: 
11287: =back
11288: 
11289: =head2 User Roles
11290: 
11291: =over 4
11292: 
11293: =item *
11294: 
11295: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
11296:  F: full access
11297:  U,I,K: authentication modes (cxx only)
11298:  '': forbidden
11299:  1: user needs to choose course
11300:  2: browse allowed
11301:  A: passphrase authentication needed
11302: 
11303: =item *
11304: 
11305: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
11306: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
11307: and course level
11308: 
11309: =item *
11310: 
11311: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
11312: (rolesplain.tab); plain text explanation of a user role term.
11313: $type is Course (default) or Community.
11314: If $forcedefault evaluates to true, text returned will be default 
11315: text for $type. Otherwise, if this is a course, the text returned 
11316: will be a custom name for the role (if defined in the course's 
11317: environment).  If no custom name is defined the default is returned.
11318:    
11319: =item *
11320: 
11321: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
11322: All arguments are optional. Returns a hash of a roles, either for
11323: co-author/assistant author roles for a user's Construction Space
11324: (default), or if $context is 'userroles', roles for the user himself,
11325: In the hash, keys are set to colon-separated $uname,$udom,$role, and
11326: (optionally) if $withsec is true, a fourth colon-separated item - $section.
11327: For each key, value is set to colon-separated start and end times for
11328: the role.  If no username and domain are specified, will default to
11329: current user/domain. Types, roles, and roledoms are references to arrays
11330: of role statuses (active, future or previous), roles 
11331: (e.g., cc,in, st etc.) and domains of the roles which can be used
11332: to restrict the list of roles reported. If no array ref is 
11333: provided for types, will default to return only active roles.
11334: 
11335: =back
11336: 
11337: =head2 User Modification
11338: 
11339: =over 4
11340: 
11341: =item *
11342: 
11343: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
11344: user for the level given by URL.  Optional start and end dates (leave empty
11345: string or zero for "no date")
11346: 
11347: =item *
11348: 
11349: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
11350: change a users, password, possible return values are: ok,
11351: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
11352: refused
11353: 
11354: =item *
11355: 
11356: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
11357: 
11358: =item *
11359: 
11360: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
11361:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
11362: 
11363: will update user information (firstname,middlename,lastname,generation,
11364: permanentemail), and if forceid is true, student/employee ID also.
11365: A user's institutional affiliation(s) can also be updated.
11366: User information fields will not be overwritten with empty entries 
11367: unless the field is included in the $candelete array reference.
11368: This array is included when a single user is modified via "Manage Users",
11369: or when Autoupdate.pl is run by cron in a domain.
11370: 
11371: =item *
11372: 
11373: modifystudent
11374: 
11375: modify a student's enrollment and identification information.
11376: The course id is resolved based on the current users environment.  
11377: This means the envoking user must be a course coordinator or otherwise
11378: associated with a course.
11379: 
11380: This call is essentially a wrapper for lonnet::modifyuser and
11381: lonnet::modify_student_enrollment
11382: 
11383: Inputs: 
11384: 
11385: =over 4
11386: 
11387: =item B<$udom> Student's loncapa domain
11388: 
11389: =item B<$uname> Student's loncapa login name
11390: 
11391: =item B<$uid> Student/Employee ID
11392: 
11393: =item B<$umode> Student's authentication mode
11394: 
11395: =item B<$upass> Student's password
11396: 
11397: =item B<$first> Student's first name
11398: 
11399: =item B<$middle> Student's middle name
11400: 
11401: =item B<$last> Student's last name
11402: 
11403: =item B<$gene> Student's generation
11404: 
11405: =item B<$usec> Student's section in course
11406: 
11407: =item B<$end> Unix time of the roles expiration
11408: 
11409: =item B<$start> Unix time of the roles start date
11410: 
11411: =item B<$forceid> If defined, allow $uid to be changed
11412: 
11413: =item B<$desiredhome> server to use as home server for student
11414: 
11415: =item B<$email> Student's permanent e-mail address
11416: 
11417: =item B<$type> Type of enrollment (auto or manual)
11418: 
11419: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
11420: 
11421: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
11422: 
11423: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
11424: 
11425: =item B<$context> role change context (shown in User Management Logs display in a course)
11426: 
11427: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
11428: 
11429: =back
11430: 
11431: =item *
11432: 
11433: modify_student_enrollment
11434: 
11435: Change a students enrollment status in a class.  The environment variable
11436: 'role.request.course' must be defined for this function to proceed.
11437: 
11438: Inputs:
11439: 
11440: =over 4
11441: 
11442: =item $udom, students domain
11443: 
11444: =item $uname, students name
11445: 
11446: =item $uid, students user id
11447: 
11448: =item $first, students first name
11449: 
11450: =item $middle
11451: 
11452: =item $last
11453: 
11454: =item $gene
11455: 
11456: =item $usec
11457: 
11458: =item $end
11459: 
11460: =item $start
11461: 
11462: =item $type
11463: 
11464: =item $locktype
11465: 
11466: =item $cid
11467: 
11468: =item $selfenroll
11469: 
11470: =item $context
11471: 
11472: =back
11473: 
11474: 
11475: =item *
11476: 
11477: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
11478: custom role; give a custom role to a user for the level given by URL.  Specify
11479: name and domain of role author, and role name
11480: 
11481: =item *
11482: 
11483: revokerole($udom,$uname,$url,$role) : revoke a role for url
11484: 
11485: =item *
11486: 
11487: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
11488: 
11489: =back
11490: 
11491: =head2 Course Infomation
11492: 
11493: =over 4
11494: 
11495: =item *
11496: 
11497: coursedescription($courseid,$options) : returns a hash of information about the
11498: specified course id, including all environment settings for the
11499: course, the description of the course will be in the hash under the
11500: key 'description'
11501: 
11502: $options is an optional parameter that if supplied is a hash reference that controls
11503: what how this function works.  It has the following key/values:
11504: 
11505: =over 4
11506: 
11507: =item freshen_cache
11508: 
11509: If defined, and the environment cache for the course is valid, it is 
11510: returned in the returned hash.
11511: 
11512: =item one_time
11513: 
11514: If defined, the last cache time is set to _now_
11515: 
11516: =item user
11517: 
11518: If defined, the supplied username is used instead of the current user.
11519: 
11520: 
11521: =back
11522: 
11523: =item *
11524: 
11525: resdata($name,$domain,$type,@which) : request for current parameter
11526: setting for a specific $type, where $type is either 'course' or 'user',
11527: @what should be a list of parameters to ask about. This routine caches
11528: answers for 5 minutes.
11529: 
11530: =item *
11531: 
11532: get_courseresdata($courseid, $domain) : dump the entire course resource
11533: data base, returning a hash that is keyed by the resource name and has
11534: values that are the resource value.  I believe that the timestamps and
11535: versions are also returned.
11536: 
11537: 
11538: =back
11539: 
11540: =head2 Course Modification
11541: 
11542: =over 4
11543: 
11544: =item *
11545: 
11546: writecoursepref($courseid,%prefs) : write preferences (environment
11547: database) for a course
11548: 
11549: =item *
11550: 
11551: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
11552: 
11553: =item *
11554: 
11555: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
11556: 
11557: =back
11558: 
11559: =head2 Resource Subroutines
11560: 
11561: =over 4
11562: 
11563: =item *
11564: 
11565: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
11566: 
11567: =item *
11568: 
11569: repcopy($filename) : subscribes to the requested file, and attempts to
11570: replicate from the owning library server, Might return
11571: 'unavailable', 'not_found', 'forbidden', 'ok', or
11572: 'bad_request', also attempts to grab the metadata for the
11573: resource. Expects the local filesystem pathname
11574: (/home/httpd/html/res/....)
11575: 
11576: =back
11577: 
11578: =head2 Resource Information
11579: 
11580: =over 4
11581: 
11582: =item *
11583: 
11584: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
11585: a vairety of different possible values, $varname should be a request
11586: string, and the other parameters can be used to specify who and what
11587: one is asking about.
11588: 
11589: Possible values for $varname are environment.lastname (or other item
11590: from the envirnment hash), user.name (or someother aspect about the
11591: user), resource.0.maxtries (or some other part and parameter of a
11592: resource)
11593: 
11594: =item *
11595: 
11596: directcondval($number) : get current value of a condition; reads from a state
11597: string
11598: 
11599: =item *
11600: 
11601: condval($condidx) : value of condition index based on state
11602: 
11603: =item *
11604: 
11605: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
11606: resource's metadata, $what should be either a specific key, or either
11607: 'keys' (to get a list of possible keys) or 'packages' to get a list of
11608: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
11609: 
11610: this function automatically caches all requests
11611: 
11612: =item *
11613: 
11614: metadata_query($query,$custom,$customshow) : make a metadata query against the
11615: network of library servers; returns file handle of where SQL and regex results
11616: will be stored for query
11617: 
11618: =item *
11619: 
11620: symbread($filename) : return symbolic list entry (filename argument optional);
11621: returns the data handle
11622: 
11623: =item *
11624: 
11625: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
11626: a possible symb for the URL in $thisfn, and if is an encryypted
11627: resource that the user accessed using /enc/ returns a 1 on success, 0
11628: on failure, user must be in a course, as it assumes the existance of
11629: the course initial hash, and uses $env('request.course.id'}
11630: 
11631: 
11632: =item *
11633: 
11634: symbclean($symb) : removes versions numbers from a symb, returns the
11635: cleaned symb
11636: 
11637: =item *
11638: 
11639: is_on_map($uri) : checks if the $uri is somewhere on the current
11640: course map, user must be in a course for it to work.
11641: 
11642: =item *
11643: 
11644: numval($salt) : return random seed value (addend for rndseed)
11645: 
11646: =item *
11647: 
11648: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
11649: a random seed, all arguments are optional, if they aren't sent it uses the
11650: environment to derive them. Note: if symb isn't sent and it can't get one
11651: from &symbread it will use the current time as its return value
11652: 
11653: =item *
11654: 
11655: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
11656: unfakeable, receipt
11657: 
11658: =item *
11659: 
11660: receipt() : API to ireceipt working off of env values; given out to users
11661: 
11662: =item *
11663: 
11664: countacc($url) : count the number of accesses to a given URL
11665: 
11666: =item *
11667: 
11668: 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
11669: 
11670: =item *
11671: 
11672: 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)
11673: 
11674: =item *
11675: 
11676: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
11677: 
11678: =item *
11679: 
11680: devalidate($symb) : devalidate temporary spreadsheet calculations,
11681: forcing spreadsheet to reevaluate the resource scores next time.
11682: 
11683: =back
11684: 
11685: =head2 Storing/Retreiving Data
11686: 
11687: =over 4
11688: 
11689: =item *
11690: 
11691: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
11692: for this url; hashref needs to be given and should be a \%hashname; the
11693: remaining args aren't required and if they aren't passed or are '' they will
11694: be derived from the env
11695: 
11696: =item *
11697: 
11698: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
11699: uses critical subroutine
11700: 
11701: =item *
11702: 
11703: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
11704: all args are optional
11705: 
11706: =item *
11707: 
11708: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
11709: dumps the complete (or key matching regexp) namespace into a hash
11710: ($udom, $uname, $regexp, $range are optional) for a namespace that is
11711: normally &store()ed into
11712: 
11713: $range should be either an integer '100' (give me the first 100
11714:                                            matching records)
11715:               or be  two integers sperated by a - with no spaces
11716:                  '30-50' (give me the 30th through the 50th matching
11717:                           records)
11718: 
11719: 
11720: =item *
11721: 
11722: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
11723: replaces a &store() version of data with a replacement set of data
11724: for a particular resource in a namespace passed in the $storehash hash 
11725: reference
11726: 
11727: =item *
11728: 
11729: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
11730: works very similar to store/cstore, but all data is stored in a
11731: temporary location and can be reset using tmpreset, $storehash should
11732: be a hash reference, returns nothing on success
11733: 
11734: =item *
11735: 
11736: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
11737: similar to restore, but all data is stored in a temporary location and
11738: can be reset using tmpreset. Returns a hash of values on success,
11739: error string otherwise.
11740: 
11741: =item *
11742: 
11743: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
11744: deltes all keys for $symb form the temporary storage hash.
11745: 
11746: =item *
11747: 
11748: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
11749: reference filled in from namesp ($udom and $uname are optional)
11750: 
11751: =item *
11752: 
11753: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
11754: namesp ($udom and $uname are optional)
11755: 
11756: =item *
11757: 
11758: dump($namespace,$udom,$uname,$regexp,$range) : 
11759: dumps the complete (or key matching regexp) namespace into a hash
11760: ($udom, $uname, $regexp, $range are optional)
11761: 
11762: $range should be either an integer '100' (give me the first 100
11763:                                            matching records)
11764:               or be  two integers sperated by a - with no spaces
11765:                  '30-50' (give me the 30th through the 50th matching
11766:                           records)
11767: =item *
11768: 
11769: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
11770: $store can be a scalar, an array reference, or if the amount to be 
11771: incremented is > 1, a hash reference.
11772: 
11773: ($udom and $uname are optional)
11774: 
11775: =item *
11776: 
11777: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
11778: ($udom and $uname are optional)
11779: 
11780: =item *
11781: 
11782: cput($namespace,$storehash,$udom,$uname) : critical put
11783: ($udom and $uname are optional)
11784: 
11785: =item *
11786: 
11787: newput($namespace,$storehash,$udom,$uname) :
11788: 
11789: Attempts to store the items in the $storehash, but only if they don't
11790: currently exist, if this succeeds you can be certain that you have 
11791: successfully created a new key value pair in the $namespace db.
11792: 
11793: 
11794: Args:
11795:  $namespace: name of database to store values to
11796:  $storehash: hashref to store to the db
11797:  $udom: (optional) domain of user containing the db
11798:  $uname: (optional) name of user caontaining the db
11799: 
11800: Returns:
11801:  'ok' -> succeeded in storing all keys of $storehash
11802:  'key_exists: <key>' -> failed to anything out of $storehash, as at
11803:                         least <key> already existed in the db (other
11804:                         requested keys may also already exist)
11805:  'error: <msg>' -> unable to tie the DB or other error occurred
11806:  'con_lost' -> unable to contact request server
11807:  'refused' -> action was not allowed by remote machine
11808: 
11809: 
11810: =item *
11811: 
11812: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
11813: reference filled in from namesp (encrypts the return communication)
11814: ($udom and $uname are optional)
11815: 
11816: =item *
11817: 
11818: log($udom,$name,$home,$message) : write to permanent log for user; use
11819: critical subroutine
11820: 
11821: =item *
11822: 
11823: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
11824: array reference filled in from namespace found in domain level on either
11825: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
11826: 
11827: =item *
11828: 
11829: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
11830: domain level either on specified domain server ($uhome) or primary domain 
11831: server ($udom and $uhome are optional)
11832: 
11833: =item * 
11834: 
11835: get_domain_defaults($target_domain) : returns hash with defaults for
11836: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
11837: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
11838: or localauth), initial password or a kerberos realm, language (e.g., en-us).
11839: Values are retrieved from cache (if current), or from domain's configuration.db
11840: (if available), or lastly from values in lonTabs/dns_domain,tab, 
11841: or lonTabs/domain.tab. 
11842: 
11843: %domdefaults = &get_auth_defaults($target_domain);
11844: 
11845: =back
11846: 
11847: =head2 Network Status Functions
11848: 
11849: =over 4
11850: 
11851: =item *
11852: 
11853: dirlist() : return directory list based on URI (first arg).
11854: 
11855: Inputs: 1 required, 5 optional.
11856: 
11857: =over
11858: 
11859: =item 
11860: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
11861: 
11862: =item
11863: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
11864: 
11865: =item
11866: $username -  username of user/course to be listed. Extracted from $uri if absent. 
11867: 
11868: =item
11869: $getpropath - boolean: 1 if prepend path using &propath(). 
11870: 
11871: =item
11872: $getuserdir - boolean: 1 if prepend path for "userfiles".
11873: 
11874: =item 
11875: $alternateRoot - path to prepend in place of path from $uri.
11876: 
11877: =back
11878: 
11879: Returns: Array of up to two items.
11880: 
11881: =over
11882: 
11883: a reference to an array of files/subdirectories
11884: 
11885: =over
11886: 
11887: Each element in the array of files/subdirectories is a & separated list of
11888: item name and the result of running stat on the item.  If dirlist was requested
11889: for a file instead of a directory, the item name will be ''. For a directory 
11890: listing, if the item is a metadata file, the element will end &N&M 
11891: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
11892: default copyright set (1).  
11893: 
11894: =back
11895: 
11896: a scalar containing error condition (if encountered).
11897: 
11898: =over
11899: 
11900: =item 
11901: no_host (no homeserver identified for $username:$domain).
11902: 
11903: =item 
11904: no_such_host (server contacted for listing not identified as valid host).
11905: 
11906: =item 
11907: con_lost (connection to remote server failed).
11908: 
11909: =item 
11910: refused (invalid $username:$domain received on lond side).
11911: 
11912: =item 
11913: no_such_dir (directory at specified path on lond side does not exist). 
11914: 
11915: =item 
11916: empty (directory at specified path on lond side is empty).
11917: 
11918: =over
11919: 
11920: This is currently not encountered because the &ls3, &ls2, 
11921: &ls (_handler) routines on the lond side do not filter out
11922: . and .. from a directory listing. 
11923: 
11924: =back
11925: 
11926: =back
11927: 
11928: =back
11929: 
11930: =item *
11931: 
11932: spareserver() : find server with least workload from spare.tab
11933: 
11934: 
11935: =item *
11936: 
11937: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
11938: if there is no corresponding loncapa host.
11939: 
11940: =back
11941: 
11942: 
11943: =head2 Apache Request
11944: 
11945: =over 4
11946: 
11947: =item *
11948: 
11949: ssi($url,%hash) : server side include, does a complete request cycle on url to
11950: localhost, posts hash
11951: 
11952: =back
11953: 
11954: =head2 Data to String to Data
11955: 
11956: =over 4
11957: 
11958: =item *
11959: 
11960: hash2str(%hash) : convert a hash into a string complete with escaping and '='
11961: and '&' separators, supports elements that are arrayrefs and hashrefs
11962: 
11963: =item *
11964: 
11965: hashref2str($hashref) : convert a hashref into a string complete with
11966: escaping and '=' and '&' separators, supports elements that are
11967: arrayrefs and hashrefs
11968: 
11969: =item *
11970: 
11971: arrayref2str($arrayref) : convert an arrayref into a string complete
11972: with escaping and '&' separators, supports elements that are arrayrefs
11973: and hashrefs
11974: 
11975: =item *
11976: 
11977: str2hash($string) : convert string to hash using unescaping and
11978: splitting on '=' and '&', supports elements that are arrayrefs and
11979: hashrefs
11980: 
11981: =item *
11982: 
11983: str2array($string) : convert string to hash using unescaping and
11984: splitting on '&', supports elements that are arrayrefs and hashrefs
11985: 
11986: =back
11987: 
11988: =head2 Logging Routines
11989: 
11990: 
11991: These routines allow one to make log messages in the lonnet.log and
11992: lonnet.perm logfiles.
11993: 
11994: =over 4
11995: 
11996: =item *
11997: 
11998: logtouch() : make sure the logfile, lonnet.log, exists
11999: 
12000: =item *
12001: 
12002: logthis() : append message to the normal lonnet.log file, it gets
12003: preiodically rolled over and deleted.
12004: 
12005: =item *
12006: 
12007: logperm() : append a permanent message to lonnet.perm.log, this log
12008: file never gets deleted by any automated portion of the system, only
12009: messages of critical importance should go in here.
12010: 
12011: 
12012: =back
12013: 
12014: =head2 General File Helper Routines
12015: 
12016: =over 4
12017: 
12018: =item *
12019: 
12020: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
12021: (a) files in /uploaded
12022:   (i) If a local copy of the file exists - 
12023:       compares modification date of local copy with last-modified date for 
12024:       definitive version stored on home server for course. If local copy is 
12025:       stale, requests a new version from the home server and stores it. 
12026:       If the original has been removed from the home server, then local copy 
12027:       is unlinked.
12028:   (ii) If local copy does not exist -
12029:       requests the file from the home server and stores it. 
12030:   
12031:   If $caller is 'uploadrep':  
12032:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
12033:     for request for files originally uploaded via DOCS. 
12034:      - returns 'ok' if fresh local copy now available, -1 otherwise.
12035:   
12036:   Otherwise:
12037:      This indicates a call from the content generation phase of the request.
12038:      -  returns the entire contents of the file or -1.
12039:      
12040: (b) files in /res
12041:    - returns the entire contents of a file or -1; 
12042:    it properly subscribes to and replicates the file if neccessary.
12043: 
12044: 
12045: =item *
12046: 
12047: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
12048:                   reference
12049: 
12050: returns either a stat() list of data about the file or an empty list
12051: if the file doesn't exist or couldn't find out about it (connection
12052: problems or user unknown)
12053: 
12054: =item *
12055: 
12056: filelocation($dir,$file) : returns file system location of a file
12057: based on URI; meant to be "fairly clean" absolute reference, $dir is a
12058: directory that relative $file lookups are to looked in ($dir of /a/dir
12059: and a file of ../bob will become /a/bob)
12060: 
12061: =item *
12062: 
12063: hreflocation($dir,$file) : returns file system location or a URL; same as
12064: filelocation except for hrefs
12065: 
12066: =item *
12067: 
12068: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
12069: 
12070: =back
12071: 
12072: =head2 Usererfile file routines (/uploaded*)
12073: 
12074: =over 4
12075: 
12076: =item *
12077: 
12078: userfileupload(): main rotine for putting a file in a user or course's
12079:                   filespace, arguments are,
12080: 
12081:  formname - required - this is the name of the element in $env where the
12082:            filename, and the contents of the file to create/modifed exist
12083:            the filename is in $env{'form.'.$formname.'.filename'} and the
12084:            contents of the file is located in $env{'form.'.$formname}
12085:  context - if coursedoc, store the file in the course of the active role
12086:              of the current user; 
12087:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
12088:            if 'canceloverwrite': delete file in tmp/overwrites directory
12089:  subdir - required - subdirectory to put the file in under ../userfiles/
12090:          if undefined, it will be placed in "unknown"
12091: 
12092:  (This routine calls clean_filename() to remove any dangerous
12093:  characters from the filename, and then calls finuserfileupload() to
12094:  complete the transaction)
12095: 
12096:  returns either the url of the uploaded file (/uploaded/....) if successful
12097:  and /adm/notfound.html if unsuccessful
12098: 
12099: =item *
12100: 
12101: clean_filename(): routine for cleaing a filename up for storage in
12102:                  userfile space, argument is:
12103: 
12104:  filename - proposed filename
12105: 
12106: returns: the new clean filename
12107: 
12108: =item *
12109: 
12110: finishuserfileupload(): routine that creates and sends the file to
12111: userspace, probably shouldn't be called directly
12112: 
12113:   docuname: username or courseid of destination for the file
12114:   docudom: domain of user/course of destination for the file
12115:   formname: same as for userfileupload()
12116:   fname: filename (including subdirectories) for the file
12117:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
12118:   allfiles: reference to hash used to store objects found by parser
12119:   codebase: reference to hash used for codebases of java objects found by parser
12120:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
12121:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
12122:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
12123:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
12124:   context: if 'overwrite', will move the uploaded file from its temporary location to
12125:             userfiles to facilitate overwriting a previously uploaded file with same name.
12126:   mimetype: reference to scalar to accommodate mime type determined
12127:             from File::MMagic if $parser = parse.
12128: 
12129:  returns either the url of the uploaded file (/uploaded/....) if successful
12130:  and /adm/notfound.html if unsuccessful (or an error message if context 
12131:  was 'overwrite').
12132:  
12133: 
12134: =item *
12135: 
12136: renameuserfile(): renames an existing userfile to a new name
12137: 
12138:   Args:
12139:    docuname: username or courseid of destination for the file
12140:    docudom: domain of user/course of destination for the file
12141:    old: current file name (including any subdirs under userfiles)
12142:    new: desired file name (including any subdirs under userfiles)
12143: 
12144: =item *
12145: 
12146: mkdiruserfile(): creates a directory is a userfiles dir
12147: 
12148:   Args:
12149:    docuname: username or courseid of destination for the file
12150:    docudom: domain of user/course of destination for the file
12151:    dir: dir to create (including any subdirs under userfiles)
12152: 
12153: =item *
12154: 
12155: removeuserfile(): removes a file that exists in userfiles
12156: 
12157:   Args:
12158:    docuname: username or courseid of destination for the file
12159:    docudom: domain of user/course of destination for the file
12160:    fname: filname to delete (including any subdirs under userfiles)
12161: 
12162: =item *
12163: 
12164: removeuploadedurl(): convience function for removeuserfile()
12165: 
12166:   Args:
12167:    url:  a full /uploaded/... url to delete
12168: 
12169: =item * 
12170: 
12171: get_portfile_permissions():
12172:   Args:
12173:     domain: domain of user or course contain the portfolio files
12174:     user: name of user or num of course contain the portfolio files
12175:   Returns:
12176:     hashref of a dump of the proper file_permissions.db
12177:    
12178: 
12179: =item * 
12180: 
12181: get_access_controls():
12182: 
12183: Args:
12184:   current_permissions: the hash ref returned from get_portfile_permissions()
12185:   group: (optional) the group you want the files associated with
12186:   file: (optional) the file you want access info on
12187: 
12188: Returns:
12189:     a hash (keys are file names) of hashes containing
12190:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
12191:         values are XML containing access control settings (see below) 
12192: 
12193: Internal notes:
12194: 
12195:  access controls are stored in file_permissions.db as key=value pairs.
12196:     key -> path to file/file_name\0uniqueID:scope_end_start
12197:         where scope -> public,guest,course,group,domains or users.
12198:               end -> UNIX time for end of access (0 -> no end date)
12199:               start -> UNIX time for start of access
12200: 
12201:     value -> XML description of access control
12202:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
12203:             <start></start>
12204:             <end></end>
12205: 
12206:             <password></password>  for scope type = guest
12207: 
12208:             <domain></domain>     for scope type = course or group
12209:             <number></number>
12210:             <roles id="">
12211:              <role></role>
12212:              <access></access>
12213:              <section></section>
12214:              <group></group>
12215:             </roles>
12216: 
12217:             <dom></dom>         for scope type = domains
12218: 
12219:             <users>             for scope type = users
12220:              <user>
12221:               <uname></uname>
12222:               <udom></udom>
12223:              </user>
12224:             </users>
12225:            </scope> 
12226:               
12227:  Access data is also aggregated for each file in an additional key=value pair:
12228:  key -> path to file/file_name\0accesscontrol 
12229:  value -> reference to hash
12230:           hash contains key = value pairs
12231:           where key = uniqueID:scope_end_start
12232:                 value = UNIX time record was last updated
12233: 
12234:           Used to improve speed of look-ups of access controls for each file.  
12235:  
12236:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
12237: 
12238: modify_access_controls():
12239: 
12240: Modifies access controls for a portfolio file
12241: Args
12242: 1. file name
12243: 2. reference to hash of required changes,
12244: 3. domain
12245: 4. username
12246:   where domain,username are the domain of the portfolio owner 
12247:   (either a user or a course) 
12248: 
12249: Returns:
12250: 1. result of additions or updates ('ok' or 'error', with error message). 
12251: 2. result of deletions ('ok' or 'error', with error message).
12252: 3. reference to hash of any new or updated access controls.
12253: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
12254:    key = integer (inbound ID)
12255:    value = uniqueID  
12256: 
12257: =back
12258: 
12259: =head2 HTTP Helper Routines
12260: 
12261: =over 4
12262: 
12263: =item *
12264: 
12265: escape() : unpack non-word characters into CGI-compatible hex codes
12266: 
12267: =item *
12268: 
12269: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
12270: 
12271: =back
12272: 
12273: =head1 PRIVATE SUBROUTINES
12274: 
12275: =head2 Underlying communication routines (Shouldn't call)
12276: 
12277: =over 4
12278: 
12279: =item *
12280: 
12281: subreply() : tries to pass a message to lonc, returns con_lost if incapable
12282: 
12283: =item *
12284: 
12285: reply() : uses subreply to send a message to remote machine, logs all failures
12286: 
12287: =item *
12288: 
12289: critical() : passes a critical message to another server; if cannot
12290: get through then place message in connection buffer directory and
12291: returns con_delayed, if incapable of saving message, returns
12292: con_failed
12293: 
12294: =item *
12295: 
12296: reconlonc() : tries to reconnect lonc client processes.
12297: 
12298: =back
12299: 
12300: =head2 Resource Access Logging
12301: 
12302: =over 4
12303: 
12304: =item *
12305: 
12306: flushcourselogs() : flush (save) buffer logs and access logs
12307: 
12308: =item *
12309: 
12310: courselog($what) : save message for course in hash
12311: 
12312: =item *
12313: 
12314: courseacclog($what) : save message for course using &courselog().  Perform
12315: special processing for specific resource types (problems, exams, quizzes, etc).
12316: 
12317: =item *
12318: 
12319: goodbye() : flush course logs and log shutting down; it is called in srm.conf
12320: as a PerlChildExitHandler
12321: 
12322: =back
12323: 
12324: =head2 Other
12325: 
12326: =over 4
12327: 
12328: =item *
12329: 
12330: symblist($mapname,%newhash) : update symbolic storage links
12331: 
12332: =back
12333: 
12334: =cut
12335: 

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