File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1240: download - view: text, annotated - select for diffs
Sun Oct 6 14:20:36 2013 UTC (10 years, 9 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- &get_domain_defaults() can take a second (optional) arg -- $ignore_cache
  which causes domain configuration to be loaded from configuration.db or
  domain.tab, and not cache.
- Update POD for &get_domain_defaults().

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1240 2013/10/06 14:20:36 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: ###
   29: 
   30: =pod
   31: 
   32: =head1 NAME
   33: 
   34: Apache::lonnet.pm
   35: 
   36: =head1 SYNOPSIS
   37: 
   38: This file is an interface to the lonc processes of
   39: the LON-CAPA network as well as set of elaborated functions for handling information
   40: necessary for navigating through a given cluster of LON-CAPA machines within a
   41: domain. There are over 40 specialized functions in this module which handle the
   42: reading and transmission of metadata, user information (ids, names, environments, roles,
   43: logs), file information (storage, reading, directories, extensions, replication, embedded
   44: styles and descriptors), educational resources (course descriptions, section names and
   45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
   46: and from more descriptive phrases or explanations.
   47: 
   48: This is part of the LearningOnline Network with CAPA project
   49: described at http://www.lon-capa.org.
   50: 
   51: =head1 Package Variables
   52: 
   53: These are largely undocumented, so if you decipher one please note it here.
   54: 
   55: =over 4
   56: 
   57: =item $processmarker
   58: 
   59: Contains the time this process was started and this servers host id.
   60: 
   61: =item $dumpcount
   62: 
   63: Counts the number of times a message log flush has been attempted (regardless
   64: of success) by this process.  Used as part of the filename when messages are
   65: delayed.
   66: 
   67: =back
   68: 
   69: =cut
   70: 
   71: package Apache::lonnet;
   72: 
   73: use strict;
   74: use LWP::UserAgent();
   75: use HTTP::Date;
   76: use Image::Magick;
   77: 
   78: 
   79: use Encode;
   80: 
   81: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir $apache
   82:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
   83:             %managerstab);
   84: 
   85: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
   86:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
   87:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
   88:     %courseownerbuf, %coursetypebuf,$locknum);
   89: 
   90: use IO::Socket;
   91: use GDBM_File;
   92: use HTML::LCParser;
   93: use Fcntl qw(:flock);
   94: use Storable qw(thaw nfreeze);
   95: use Time::HiRes qw( gettimeofday tv_interval );
   96: use Cache::Memcached;
   97: use Digest::MD5;
   98: use Math::Random;
   99: use File::MMagic;
  100: use LONCAPA qw(:DEFAULT :match);
  101: use LONCAPA::Configuration;
  102: use LONCAPA::lonmetadata;
  103: use LONCAPA::Lond;
  104: 
  105: use File::Copy;
  106: 
  107: my $readit;
  108: my $max_connection_retries = 10;     # Or some such value.
  109: 
  110: require Exporter;
  111: 
  112: our @ISA = qw (Exporter);
  113: our @EXPORT = qw(%env);
  114: 
  115: 
  116: # ------------------------------------ Logging (parameters, docs, slots, roles)
  117: {
  118:     my $logid;
  119:     sub write_log {
  120: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
  121:         if ($context eq 'course') {
  122:             if (($cnum eq '') || ($cdom eq '')) {
  123:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  124:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  125:             }
  126:         }
  127: 	$logid ++;
  128:         my $now = time();
  129: 	my $id=$now.'00000'.$$.'00000'.$logid;
  130:         my $logentry = { 
  131:                           $id => {
  132:                                    'exe_uname' => $env{'user.name'},
  133:                                    'exe_udom'  => $env{'user.domain'},
  134:                                    'exe_time'  => $now,
  135:                                    'exe_ip'    => $ENV{'REMOTE_ADDR'},
  136:                                    'delflag'   => $delflag,
  137:                                    'logentry'  => $storehash,
  138:                                    'uname'     => $uname,
  139:                                    'udom'      => $udom,
  140:                                   }
  141:                        };
  142: 	return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
  143:     }
  144: }
  145: 
  146: sub logtouch {
  147:     my $execdir=$perlvar{'lonDaemons'};
  148:     unless (-e "$execdir/logs/lonnet.log") {	
  149: 	open(my $fh,">>$execdir/logs/lonnet.log");
  150: 	close $fh;
  151:     }
  152:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  153:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  154: }
  155: 
  156: sub logthis {
  157:     my $message=shift;
  158:     my $execdir=$perlvar{'lonDaemons'};
  159:     my $now=time;
  160:     my $local=localtime($now);
  161:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
  162: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
  163: 	print $fh $logstring;
  164: 	close($fh);
  165:     }
  166:     return 1;
  167: }
  168: 
  169: sub logperm {
  170:     my $message=shift;
  171:     my $execdir=$perlvar{'lonDaemons'};
  172:     my $now=time;
  173:     my $local=localtime($now);
  174:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
  175: 	print $fh "$now:$message:$local\n";
  176: 	close($fh);
  177:     }
  178:     return 1;
  179: }
  180: 
  181: sub create_connection {
  182:     my ($hostname,$lonid) = @_;
  183:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  184: 				     Type    => SOCK_STREAM,
  185: 				     Timeout => 10);
  186:     return 0 if (!$client);
  187:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
  188:     my $result = <$client>;
  189:     chomp($result);
  190:     return 1 if ($result eq 'done');
  191:     return 0;
  192: }
  193: 
  194: sub get_server_timezone {
  195:     my ($cnum,$cdom) = @_;
  196:     my $home=&homeserver($cnum,$cdom);
  197:     if ($home ne 'no_host') {
  198:         my $cachetime = 24*3600;
  199:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
  200:         if (defined($cached)) {
  201:             return $timezone;
  202:         } else {
  203:             my $timezone = &reply('servertimezone',$home);
  204:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
  205:         }
  206:     }
  207: }
  208: 
  209: sub get_server_distarch {
  210:     my ($lonhost,$ignore_cache) = @_;
  211:     if (defined($lonhost)) {
  212:         if (!defined(&hostname($lonhost))) {
  213:             return;
  214:         }
  215:         my $cachetime = 12*3600;
  216:         if (!$ignore_cache) {
  217:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
  218:             if (defined($cached)) {
  219:                 return $distarch;
  220:             }
  221:         }
  222:         my $rep = &reply('serverdistarch',$lonhost);
  223:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
  224:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
  225:                 $rep eq '') {
  226:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
  227:         }
  228:     }
  229:     return;
  230: }
  231: 
  232: sub get_server_loncaparev {
  233:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
  234:     if (defined($lonhost)) {
  235:         if (!defined(&hostname($lonhost))) {
  236:             undef($lonhost);
  237:         }
  238:     }
  239:     if (!defined($lonhost)) {
  240:         if (defined(&domain($dom,'primary'))) {
  241:             $lonhost=&domain($dom,'primary');
  242:             if ($lonhost eq 'no_host') {
  243:                 undef($lonhost);
  244:             }
  245:         }
  246:     }
  247:     if (defined($lonhost)) {
  248:         my $cachetime = 12*3600;
  249:         if (!$ignore_cache) {
  250:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
  251:             if (defined($cached)) {
  252:                 return $loncaparev;
  253:             }
  254:         }
  255:         my ($answer,$loncaparev);
  256:         my @ids=&current_machine_ids();
  257:         if (grep(/^\Q$lonhost\E$/,@ids)) {
  258:             $answer = $perlvar{'lonVersion'};
  259:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  260:                 $loncaparev = $1;
  261:             }
  262:         } else {
  263:             $answer = &reply('serverloncaparev',$lonhost);
  264:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
  265:                 if ($caller eq 'loncron') {
  266:                     my $ua=new LWP::UserAgent;
  267:                     $ua->timeout(4);
  268:                     my $protocol = $protocol{$lonhost};
  269:                     $protocol = 'http' if ($protocol ne 'https');
  270:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
  271:                     my $request=new HTTP::Request('GET',$url);
  272:                     my $response=$ua->request($request);
  273:                     unless ($response->is_error()) {
  274:                         my $content = $response->content;
  275:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
  276:                             $loncaparev = $1;
  277:                         }
  278:                     }
  279:                 } else {
  280:                     $loncaparev = $loncaparevs{$lonhost};
  281:                 }
  282:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  283:                 $loncaparev = $1;
  284:             }
  285:         }
  286:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
  287:     }
  288: }
  289: 
  290: sub get_server_homeID {
  291:     my ($hostname,$ignore_cache,$caller) = @_;
  292:     unless ($ignore_cache) {
  293:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
  294:         if (defined($cached)) {
  295:             return $serverhomeID;
  296:         }
  297:     }
  298:     my $cachetime = 12*3600;
  299:     my $serverhomeID;
  300:     if ($caller eq 'loncron') { 
  301:         my @machine_ids = &machine_ids($hostname);
  302:         foreach my $id (@machine_ids) {
  303:             my $response = &reply('serverhomeID',$id);
  304:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
  305:                 $serverhomeID = $response;
  306:                 last;
  307:             }
  308:         }
  309:         if ($serverhomeID eq '') {
  310:             $serverhomeID = $machine_ids[-1];
  311:         }
  312:     } else {
  313:         $serverhomeID = $serverhomeIDs{$hostname};
  314:     }
  315:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
  316: }
  317: 
  318: sub get_remote_globals {
  319:     my ($lonhost,$whathash,$ignore_cache) = @_;
  320:     my ($result,%returnhash,%whatneeded);
  321:     if (ref($whathash) eq 'HASH') {
  322:         foreach my $what (sort(keys(%{$whathash}))) {
  323:             my $hashid = $lonhost.'-'.$what;
  324:             my ($response,$cached);
  325:             unless ($ignore_cache) {
  326:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
  327:             }
  328:             if (defined($cached)) {
  329:                 $returnhash{$what} = $response;
  330:             } else {
  331:                 $whatneeded{$what} = 1;
  332:             }
  333:         }
  334:         if (keys(%whatneeded) == 0) {
  335:             $result = 'ok';
  336:         } else {
  337:             my $requested = &freeze_escape(\%whatneeded);
  338:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
  339:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  340:                 ($rep eq 'unknown_cmd')) {
  341:                 $result = $rep;
  342:             } else {
  343:                 $result = 'ok';
  344:                 my @pairs=split(/\&/,$rep);
  345:                 foreach my $item (@pairs) {
  346:                     my ($key,$value)=split(/=/,$item,2);
  347:                     my $what = &unescape($key);
  348:                     my $hashid = $lonhost.'-'.$what;
  349:                     $returnhash{$what}=&thaw_unescape($value);
  350:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
  351:                 }
  352:             }
  353:         }
  354:     }
  355:     return ($result,\%returnhash);
  356: }
  357: 
  358: sub remote_devalidate_cache {
  359:     my ($lonhost,$name,$id) = @_;
  360:     my $response = &reply('devalidatecache:'.&escape($name).':'.&escape($id),$lonhost);
  361:     return $response;
  362: }
  363: 
  364: # -------------------------------------------------- Non-critical communication
  365: sub subreply {
  366:     my ($cmd,$server)=@_;
  367:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  368:     #
  369:     #  With loncnew process trimming, there's a timing hole between lonc server
  370:     #  process exit and the master server picking up the listen on the AF_UNIX
  371:     #  socket.  In that time interval, a lock file will exist:
  372: 
  373:     my $lockfile=$peerfile.".lock";
  374:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  375: 	sleep(1);
  376:     }
  377:     # At this point, either a loncnew parent is listening or an old lonc
  378:     # or loncnew child is listening so we can connect or everything's dead.
  379:     #
  380:     #   We'll give the connection a few tries before abandoning it.  If
  381:     #   connection is not possible, we'll con_lost back to the client.
  382:     #   
  383:     my $client;
  384:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  385: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  386: 				      Type    => SOCK_STREAM,
  387: 				      Timeout => 10);
  388: 	if ($client) {
  389: 	    last;		# Connected!
  390: 	} else {
  391: 	    &create_connection(&hostname($server),$server);
  392: 	}
  393:         sleep(1);		# Try again later if failed connection.
  394:     }
  395:     my $answer;
  396:     if ($client) {
  397: 	print $client "sethost:$server:$cmd\n";
  398: 	$answer=<$client>;
  399: 	if (!$answer) { $answer="con_lost"; }
  400: 	chomp($answer);
  401:     } else {
  402: 	$answer = 'con_lost';	# Failed connection.
  403:     }
  404:     return $answer;
  405: }
  406: 
  407: sub reply {
  408:     my ($cmd,$server)=@_;
  409:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  410:     my $answer=subreply($cmd,$server);
  411:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  412:        &logthis("<font color=\"blue\">WARNING:".
  413:                 " $cmd to $server returned $answer</font>");
  414:     }
  415:     return $answer;
  416: }
  417: 
  418: # ----------------------------------------------------------- Send USR1 to lonc
  419: 
  420: sub reconlonc {
  421:     my ($lonid) = @_;
  422:     my $hostname = &hostname($lonid);
  423:     if ($lonid) {
  424: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  425: 	if ($hostname && -e $peerfile) {
  426: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  427: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  428: 					     Type    => SOCK_STREAM,
  429: 					     Timeout => 10);
  430: 	    if ($client) {
  431: 		print $client ("reset_retries\n");
  432: 		my $answer=<$client>;
  433: 		#reset just this one.
  434: 	    }
  435: 	}
  436: 	return;
  437:     }
  438: 
  439:     &logthis("Trying to reconnect lonc");
  440:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  441:     if (open(my $fh,"<$loncfile")) {
  442: 	my $loncpid=<$fh>;
  443:         chomp($loncpid);
  444:         if (kill 0 => $loncpid) {
  445: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  446:             kill USR1 => $loncpid;
  447:             sleep 1;
  448:          } else {
  449: 	    &logthis(
  450:                "<font color=\"blue\">WARNING:".
  451:                " lonc at pid $loncpid not responding, giving up</font>");
  452:         }
  453:     } else {
  454: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  455:     }
  456: }
  457: 
  458: # ------------------------------------------------------ Critical communication
  459: 
  460: sub critical {
  461:     my ($cmd,$server)=@_;
  462:     unless (&hostname($server)) {
  463:         &logthis("<font color=\"blue\">WARNING:".
  464:                " Critical message to unknown server ($server)</font>");
  465:         return 'no_such_host';
  466:     }
  467:     my $answer=reply($cmd,$server);
  468:     if ($answer eq 'con_lost') {
  469: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
  470: 	my $answer=reply($cmd,$server);
  471:         if ($answer eq 'con_lost') {
  472:             my $now=time;
  473:             my $middlename=$cmd;
  474:             $middlename=substr($middlename,0,16);
  475:             $middlename=~s/\W//g;
  476:             my $dfilename=
  477:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  478:             $dumpcount++;
  479:             {
  480: 		my $dfh;
  481: 		if (open($dfh,">$dfilename")) {
  482: 		    print $dfh "$cmd\n"; 
  483: 		    close($dfh);
  484: 		}
  485:             }
  486:             sleep 2;
  487:             my $wcmd='';
  488:             {
  489: 		my $dfh;
  490: 		if (open($dfh,"<$dfilename")) {
  491: 		    $wcmd=<$dfh>; 
  492: 		    close($dfh);
  493: 		}
  494:             }
  495:             chomp($wcmd);
  496:             if ($wcmd eq $cmd) {
  497: 		&logthis("<font color=\"blue\">WARNING: ".
  498:                          "Connection buffer $dfilename: $cmd</font>");
  499:                 &logperm("D:$server:$cmd");
  500: 	        return 'con_delayed';
  501:             } else {
  502:                 &logthis("<font color=\"red\">CRITICAL:"
  503:                         ." Critical connection failed: $server $cmd</font>");
  504:                 &logperm("F:$server:$cmd");
  505:                 return 'con_failed';
  506:             }
  507:         }
  508:     }
  509:     return $answer;
  510: }
  511: 
  512: # ------------------------------------------- check if return value is an error
  513: 
  514: sub error {
  515:     my ($result) = @_;
  516:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  517: 	if ($2 == 2) { return undef; }
  518: 	return $1;
  519:     }
  520:     return undef;
  521: }
  522: 
  523: sub convert_and_load_session_env {
  524:     my ($lonidsdir,$handle)=@_;
  525:     my @profile;
  526:     {
  527: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  528: 	if (!$opened) {
  529: 	    return 0;
  530: 	}
  531: 	flock($idf,LOCK_SH);
  532: 	@profile=<$idf>;
  533: 	close($idf);
  534:     }
  535:     my %temp_env;
  536:     foreach my $line (@profile) {
  537: 	if ($line !~ m/=/) {
  538: 	    return 0;
  539: 	}
  540: 	chomp($line);
  541: 	my ($envname,$envvalue)=split(/=/,$line,2);
  542: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  543:     }
  544:     unlink("$lonidsdir/$handle.id");
  545:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  546: 	    0640)) {
  547: 	%disk_env = %temp_env;
  548: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  549: 	untie(%disk_env);
  550:     }
  551:     return 1;
  552: }
  553: 
  554: # ------------------------------------------- Transfer profile into environment
  555: my $env_loaded;
  556: sub transfer_profile_to_env {
  557:     my ($lonidsdir,$handle,$force_transfer) = @_;
  558:     if (!$force_transfer && $env_loaded) { return; } 
  559: 
  560:     if (!defined($lonidsdir)) {
  561: 	$lonidsdir = $perlvar{'lonIDsDir'};
  562:     }
  563:     if (!defined($handle)) {
  564:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  565:     }
  566: 
  567:     my $convert;
  568:     {
  569:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  570: 	if (!$opened) {
  571: 	    return;
  572: 	}
  573: 	flock($idf,LOCK_SH);
  574: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  575: 		&GDBM_READER(),0640)) {
  576: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  577: 	    untie(%disk_env);
  578: 	} else {
  579: 	    $convert = 1;
  580: 	}
  581:     }
  582:     if ($convert) {
  583: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  584: 	    &logthis("Failed to load session, or convert session.");
  585: 	}
  586:     }
  587: 
  588:     my %remove;
  589:     while ( my $envname = each(%env) ) {
  590:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  591:             if ($time < time-300) {
  592:                 $remove{$key}++;
  593:             }
  594:         }
  595:     }
  596: 
  597:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  598:     $env_loaded=1;
  599:     foreach my $expired_key (keys(%remove)) {
  600:         &delenv($expired_key);
  601:     }
  602: }
  603: 
  604: # ---------------------------------------------------- Check for valid session 
  605: sub check_for_valid_session {
  606:     my ($r,$name) = @_;
  607:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  608:     if ($name eq '') {
  609:         $name = 'lonID';
  610:     }
  611:     my $lonid=$cookies{$name};
  612:     return undef if (!$lonid);
  613: 
  614:     my $handle=&LONCAPA::clean_handle($lonid->value);
  615:     my $lonidsdir;
  616:     if ($name eq 'lonDAV') {
  617:         $lonidsdir=$r->dir_config('lonDAVsessDir');
  618:     } else {
  619:         $lonidsdir=$r->dir_config('lonIDsDir');
  620:     }
  621:     return undef if (!-e "$lonidsdir/$handle.id");
  622: 
  623:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  624:     return undef if (!$opened);
  625: 
  626:     flock($idf,LOCK_SH);
  627:     my %disk_env;
  628:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  629: 	    &GDBM_READER(),0640)) {
  630: 	return undef;	
  631:     }
  632: 
  633:     if (!defined($disk_env{'user.name'})
  634: 	|| !defined($disk_env{'user.domain'})) {
  635: 	return undef;
  636:     }
  637:     if (($r->user() eq '') && ($apache >= 2.4)) {
  638:         if ($disk_env{'user.domain'} eq $r->dir_config('lonDefDomain')) {
  639:             $r->user($disk_env{'user.name'});
  640:         } else {
  641:             $r->user($disk_env{'user.name'}.':'.$disk_env{'user.domain'});
  642:         }
  643:     }
  644:     return $handle;
  645: }
  646: 
  647: sub timed_flock {
  648:     my ($file,$lock_type) = @_;
  649:     my $failed=0;
  650:     eval {
  651: 	local $SIG{__DIE__}='DEFAULT';
  652: 	local $SIG{ALRM}=sub {
  653: 	    $failed=1;
  654: 	    die("failed lock");
  655: 	};
  656: 	alarm(13);
  657: 	flock($file,$lock_type);
  658: 	alarm(0);
  659:     };
  660:     if ($failed) {
  661: 	return undef;
  662:     } else {
  663: 	return 1;
  664:     }
  665: }
  666: 
  667: # ---------------------------------------------------------- Append Environment
  668: 
  669: sub appenv {
  670:     my ($newenv,$roles) = @_;
  671:     if (ref($newenv) eq 'HASH') {
  672:         foreach my $key (keys(%{$newenv})) {
  673:             my $refused = 0;
  674: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  675:                 $refused = 1;
  676:                 if (ref($roles) eq 'ARRAY') {
  677:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
  678:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  679:                         $refused = 0;
  680:                     }
  681:                 }
  682:             }
  683:             if ($refused) {
  684:                 &logthis("<font color=\"blue\">WARNING: ".
  685:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  686:                          .'</font>');
  687: 	        delete($newenv->{$key});
  688:             } else {
  689:                 $env{$key}=$newenv->{$key};
  690:             }
  691:         }
  692:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
  693:         if ($opened
  694: 	    && &timed_flock($env_file,LOCK_EX)
  695: 	    &&
  696: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  697: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  698: 	    while (my ($key,$value) = each(%{$newenv})) {
  699: 	        $disk_env{$key} = $value;
  700: 	    }
  701: 	    untie(%disk_env);
  702:         }
  703:     }
  704:     return 'ok';
  705: }
  706: # ----------------------------------------------------- Delete from Environment
  707: 
  708: sub delenv {
  709:     my ($delthis,$regexp,$roles) = @_;
  710:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
  711:         my $refused = 1;
  712:         if (ref($roles) eq 'ARRAY') {
  713:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
  714:             if (grep(/^\Q$role\E$/,@{$roles})) {
  715:                 $refused = 0;
  716:             }
  717:         }
  718:         if ($refused) {
  719:             &logthis("<font color=\"blue\">WARNING: ".
  720:                      "Attempt to delete from environment ".$delthis);
  721:             return 'error';
  722:         }
  723:     }
  724:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  725:     if ($opened
  726: 	&& &timed_flock($env_file,LOCK_EX)
  727: 	&&
  728: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  729: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  730: 	foreach my $key (keys(%disk_env)) {
  731: 	    if ($regexp) {
  732:                 if ($key=~/^$delthis/) {
  733:                     delete($env{$key});
  734:                     delete($disk_env{$key});
  735:                 } 
  736:             } else {
  737:                 if ($key=~/^\Q$delthis\E/) {
  738: 		    delete($env{$key});
  739: 		    delete($disk_env{$key});
  740: 	        }
  741:             }
  742: 	}
  743: 	untie(%disk_env);
  744:     }
  745:     return 'ok';
  746: }
  747: 
  748: sub get_env_multiple {
  749:     my ($name) = @_;
  750:     my @values;
  751:     if (defined($env{$name})) {
  752:         # exists is it an array
  753:         if (ref($env{$name})) {
  754:             @values=@{ $env{$name} };
  755:         } else {
  756:             $values[0]=$env{$name};
  757:         }
  758:     }
  759:     return(@values);
  760: }
  761: 
  762: # ------------------------------------------------------------------- Locking
  763: 
  764: sub set_lock {
  765:     my ($text)=@_;
  766:     $locknum++;
  767:     my $id=$$.'-'.$locknum;
  768:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  769:              'session.lock.'.$id => $text});
  770:     return $id;
  771: }
  772: 
  773: sub get_locks {
  774:     my $num=0;
  775:     my %texts=();
  776:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  777:        if ($lock=~/\w/) {
  778:           $num++;
  779:           $texts{$lock}=$env{'session.lock.'.$lock};
  780:        }
  781:    }
  782:    return ($num,%texts);
  783: }
  784: 
  785: sub remove_lock {
  786:     my ($id)=@_;
  787:     my $newlocks='';
  788:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  789:        if (($lock=~/\w/) && ($lock ne $id)) {
  790:           $newlocks.=','.$lock;
  791:        }
  792:     }
  793:     &appenv({'session.locks' => $newlocks});
  794:     &delenv('session.lock.'.$id);
  795: }
  796: 
  797: sub remove_all_locks {
  798:     my $activelocks=$env{'session.locks'};
  799:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  800:        if ($lock=~/\w/) {
  801:           &remove_lock($lock);
  802:        }
  803:     }
  804: }
  805: 
  806: 
  807: # ------------------------------------------ Find out current server userload
  808: sub userload {
  809:     my $numusers=0;
  810:     {
  811: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  812: 	my $filename;
  813: 	my $curtime=time;
  814: 	while ($filename=readdir(LONIDS)) {
  815: 	    next if ($filename eq '.' || $filename eq '..');
  816: 	    next if ($filename =~ /publicuser_\d+\.id/);
  817: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  818: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  819: 	}
  820: 	closedir(LONIDS);
  821:     }
  822:     my $userloadpercent=0;
  823:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  824:     if ($maxuserload) {
  825: 	$userloadpercent=100*$numusers/$maxuserload;
  826:     }
  827:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  828:     return $userloadpercent;
  829: }
  830: 
  831: # ------------------------------ Find server with least workload from spare.tab
  832: 
  833: sub spareserver {
  834:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
  835:     my $spare_server;
  836:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  837:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  838:                                                      :  $userloadpercent;
  839:     my ($uint_dom,$remotesessions);
  840:     if (($udom ne '') && (&domain($udom) ne '')) {
  841:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
  842:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
  843:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
  844:         $remotesessions = $udomdefaults{'remotesessions'};
  845:     }
  846:     my $spareshash = &this_host_spares($udom);
  847:     if (ref($spareshash) eq 'HASH') {
  848:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  849:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  850:                 if ($uint_dom) {
  851:                     next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
  852:                                                  $try_server));
  853:                 }
  854: 	        ($spare_server, $lowest_load) =
  855: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
  856:             }
  857:         }
  858: 
  859:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
  860: 
  861:         if (!$found_server) {
  862:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
  863: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
  864:                     if ($uint_dom) {
  865:                         next unless (&spare_can_host($udom,$uint_dom,
  866:                                                      $remotesessions,$try_server));
  867:                     }
  868: 	            ($spare_server, $lowest_load) =
  869: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
  870:                 }
  871: 	    }
  872:         }
  873:     }
  874: 
  875:     if (!$want_server_name) {
  876:         my $protocol = 'http';
  877:         if ($protocol{$spare_server} eq 'https') {
  878:             $protocol = $protocol{$spare_server};
  879:         }
  880:         if (defined($spare_server)) {
  881:             my $hostname = &hostname($spare_server);
  882:             if (defined($hostname)) {
  883: 	        $spare_server = $protocol.'://'.$hostname;
  884:             }
  885:         }
  886:     }
  887:     return $spare_server;
  888: }
  889: 
  890: sub compare_server_load {
  891:     my ($try_server, $spare_server, $lowest_load) = @_;
  892: 
  893:     my $loadans     = &reply('load',    $try_server);
  894:     my $userloadans = &reply('userload',$try_server);
  895: 
  896:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  897: 	return ($spare_server, $lowest_load); #didn't get a number from the server
  898:     }
  899: 
  900:     my $load;
  901:     if ($loadans =~ /\d/) {
  902: 	if ($userloadans =~ /\d/) {
  903: 	    #both are numbers, pick the bigger one
  904: 	    $load = ($loadans > $userloadans) ? $loadans 
  905: 		                              : $userloadans;
  906: 	} else {
  907: 	    $load = $loadans;
  908: 	}
  909:     } else {
  910: 	$load = $userloadans;
  911:     }
  912: 
  913:     if (($load =~ /\d/) && ($load < $lowest_load)) {
  914: 	$spare_server = $try_server;
  915: 	$lowest_load  = $load;
  916:     }
  917:     return ($spare_server,$lowest_load);
  918: }
  919: 
  920: # --------------------------- ask offload servers if user already has a session
  921: sub find_existing_session {
  922:     my ($udom,$uname) = @_;
  923:     my $spareshash = &this_host_spares($udom);
  924:     if (ref($spareshash) eq 'HASH') {
  925:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  926:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  927:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
  928:             }
  929:         }
  930:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
  931:             foreach my $try_server (@{ $spareshash->{'default'} }) {
  932:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
  933:             }
  934:         }
  935:     }
  936:     return;
  937: }
  938: 
  939: # -------------------------------- ask if server already has a session for user
  940: sub has_user_session {
  941:     my ($lonid,$udom,$uname) = @_;
  942:     my $result = &reply(join(':','userhassession',
  943: 			     map {&escape($_)} ($udom,$uname)),$lonid);
  944:     return 1 if ($result eq 'ok');
  945: 
  946:     return 0;
  947: }
  948: 
  949: # --------- determine least loaded server in a user's domain which allows login
  950: 
  951: sub choose_server {
  952:     my ($udom,$checkloginvia) = @_;
  953:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
  954:     my %servers = &get_servers($udom);
  955:     my $lowest_load = 30000;
  956:     my ($login_host,$hostname,$portal_path,$isredirect);
  957:     foreach my $lonhost (keys(%servers)) {
  958:         my $loginvia;
  959:         if ($checkloginvia) {
  960:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
  961:             if ($loginvia) {
  962:                 my ($server,$path) = split(/:/,$loginvia);
  963:                 ($login_host, $lowest_load) =
  964:                     &compare_server_load($server, $login_host, $lowest_load);
  965:                 if ($login_host eq $server) {
  966:                     $portal_path = $path;
  967:                     $isredirect = 1;
  968:                 }
  969:             } else {
  970:                 ($login_host, $lowest_load) =
  971:                     &compare_server_load($lonhost, $login_host, $lowest_load);
  972:                 if ($login_host eq $lonhost) {
  973:                     $portal_path = '';
  974:                     $isredirect = ''; 
  975:                 }
  976:             }
  977:         } else {
  978:             ($login_host, $lowest_load) =
  979:                 &compare_server_load($lonhost, $login_host, $lowest_load);
  980:         }
  981:     }
  982:     if ($login_host ne '') {
  983:         $hostname = &hostname($login_host);
  984:     }
  985:     return ($login_host,$hostname,$portal_path,$isredirect);
  986: }
  987: 
  988: # --------------------------------------------- Try to change a user's password
  989: 
  990: sub changepass {
  991:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
  992:     $currentpass = &escape($currentpass);
  993:     $newpass     = &escape($newpass);
  994:     my $lonhost = $perlvar{'lonHostID'};
  995:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
  996: 		       $server);
  997:     if (! $answer) {
  998: 	&logthis("No reply on password change request to $server ".
  999: 		 "by $uname in domain $udom.");
 1000:     } elsif ($answer =~ "^ok") {
 1001:         &logthis("$uname in $udom successfully changed their password ".
 1002: 		 "on $server.");
 1003:     } elsif ($answer =~ "^pwchange_failure") {
 1004: 	&logthis("$uname in $udom was unable to change their password ".
 1005: 		 "on $server.  The action was blocked by either lcpasswd ".
 1006: 		 "or pwchange");
 1007:     } elsif ($answer =~ "^non_authorized") {
 1008:         &logthis("$uname in $udom did not get their password correct when ".
 1009: 		 "attempting to change it on $server.");
 1010:     } elsif ($answer =~ "^auth_mode_error") {
 1011:         &logthis("$uname in $udom attempted to change their password despite ".
 1012: 		 "not being locally or internally authenticated on $server.");
 1013:     } elsif ($answer =~ "^unknown_user") {
 1014:         &logthis("$uname in $udom attempted to change their password ".
 1015: 		 "on $server but were unable to because $server is not ".
 1016: 		 "their home server.");
 1017:     } elsif ($answer =~ "^refused") {
 1018: 	&logthis("$server refused to change $uname in $udom password because ".
 1019: 		 "it was sent an unencrypted request to change the password.");
 1020:     } elsif ($answer =~ "invalid_client") {
 1021:         &logthis("$server refused to change $uname in $udom password because ".
 1022:                  "it was a reset by e-mail originating from an invalid server.");
 1023:     }
 1024:     return $answer;
 1025: }
 1026: 
 1027: # ----------------------- Try to determine user's current authentication scheme
 1028: 
 1029: sub queryauthenticate {
 1030:     my ($uname,$udom)=@_;
 1031:     my $uhome=&homeserver($uname,$udom);
 1032:     if (!$uhome) {
 1033: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
 1034: 	return 'no_host';
 1035:     }
 1036:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
 1037:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
 1038: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1039:     }
 1040:     return $answer;
 1041: }
 1042: 
 1043: # --------- Try to authenticate user from domain's lib servers (first this one)
 1044: 
 1045: sub authenticate {
 1046:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
 1047:     $upass=&escape($upass);
 1048:     $uname= &LONCAPA::clean_username($uname);
 1049:     my $uhome=&homeserver($uname,$udom,1);
 1050:     my $newhome;
 1051:     if ((!$uhome) || ($uhome eq 'no_host')) {
 1052: # Maybe the machine was offline and only re-appeared again recently?
 1053:         &reconlonc();
 1054: # One more
 1055: 	$uhome=&homeserver($uname,$udom,1);
 1056:         if (($uhome eq 'no_host') && $checkdefauth) {
 1057:             if (defined(&domain($udom,'primary'))) {
 1058:                 $newhome=&domain($udom,'primary');
 1059:             }
 1060:             if ($newhome ne '') {
 1061:                 $uhome = $newhome;
 1062:             }
 1063:         }
 1064: 	if ((!$uhome) || ($uhome eq 'no_host')) {
 1065: 	    &logthis("User $uname at $udom is unknown in authenticate");
 1066: 	    return 'no_host';
 1067:         }
 1068:     }
 1069:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
 1070:     if ($answer eq 'authorized') {
 1071:         if ($newhome) {
 1072:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
 1073:             return 'no_account_on_host'; 
 1074:         } else {
 1075:             &logthis("User $uname at $udom authorized by $uhome");
 1076:             return $uhome;
 1077:         }
 1078:     }
 1079:     if ($answer eq 'non_authorized') {
 1080: 	&logthis("User $uname at $udom rejected by $uhome");
 1081: 	return 'no_host'; 
 1082:     }
 1083:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1084:     return 'no_host';
 1085: }
 1086: 
 1087: sub can_host_session {
 1088:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
 1089:     my $canhost = 1;
 1090:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
 1091:     if (ref($remotesessions) eq 'HASH') {
 1092:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
 1093:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
 1094:                 $canhost = 0;
 1095:             } else {
 1096:                 $canhost = 1;
 1097:             }
 1098:         }
 1099:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
 1100:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
 1101:                 $canhost = 1;
 1102:             } else {
 1103:                 $canhost = 0;
 1104:             }
 1105:         }
 1106:         if ($canhost) {
 1107:             if ($remotesessions->{'version'} ne '') {
 1108:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
 1109:                 if ($reqmajor ne '' && $reqminor ne '') {
 1110:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
 1111:                         my $major = $1;
 1112:                         my $minor = $2;
 1113:                         if (($major < $reqmajor ) ||
 1114:                             (($major == $reqmajor) && ($minor < $reqminor))) {
 1115:                             $canhost = 0;
 1116:                         }
 1117:                     } else {
 1118:                         $canhost = 0;
 1119:                     }
 1120:                 }
 1121:             }
 1122:         }
 1123:     }
 1124:     if ($canhost) {
 1125:         if (ref($hostedsessions) eq 'HASH') {
 1126:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1127:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 1128:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
 1129:                 if (($uint_dom ne '') && 
 1130:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
 1131:                     $canhost = 0;
 1132:                 } else {
 1133:                     $canhost = 1;
 1134:                 }
 1135:             }
 1136:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
 1137:                 if (($uint_dom ne '') && 
 1138:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
 1139:                     $canhost = 1;
 1140:                 } else {
 1141:                     $canhost = 0;
 1142:                 }
 1143:             }
 1144:         }
 1145:     }
 1146:     return $canhost;
 1147: }
 1148: 
 1149: sub spare_can_host {
 1150:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
 1151:     my $canhost=1;
 1152:     my @intdoms;
 1153:     my $internet_names = &Apache::lonnet::get_internet_names($try_server);
 1154:     if (ref($internet_names) eq 'ARRAY') {
 1155:         @intdoms = @{$internet_names};
 1156:     }
 1157:     unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1158:         my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
 1159:         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
 1160:         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
 1161:         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
 1162:         $canhost = &can_host_session($udom,$try_server,$remoterev,
 1163:                                      $remotesessions,
 1164:                                      $defdomdefaults{'hostedsessions'});
 1165:     }
 1166:     return $canhost;
 1167: }
 1168: 
 1169: sub this_host_spares {
 1170:     my ($dom) = @_;
 1171:     my ($dom_in_use,$lonhost_in_use,$result);
 1172:     my @hosts = &current_machine_ids();
 1173:     foreach my $lonhost (@hosts) {
 1174:         if (&host_domain($lonhost) eq $dom) {
 1175:             $dom_in_use = $dom;
 1176:             $lonhost_in_use = $lonhost;
 1177:             last;
 1178:         }
 1179:     }
 1180:     if ($dom_in_use ne '') {
 1181:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1182:     }
 1183:     if (ref($result) ne 'HASH') {
 1184:         $lonhost_in_use = $perlvar{'lonHostID'};
 1185:         $dom_in_use = &host_domain($lonhost_in_use);
 1186:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1187:         if (ref($result) ne 'HASH') {
 1188:             $result = \%spareid;
 1189:         }
 1190:     }
 1191:     return $result;
 1192: }
 1193: 
 1194: sub spares_for_offload  {
 1195:     my ($dom_in_use,$lonhost_in_use) = @_;
 1196:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
 1197:     if (defined($cached)) {
 1198:         return $result;
 1199:     } else {
 1200:         my $cachetime = 60*60*24;
 1201:         my %domconfig =
 1202:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
 1203:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1204:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
 1205:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
 1206:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
 1207:                 }
 1208:             }
 1209:         }
 1210:     }
 1211:     return;
 1212: }
 1213: 
 1214: sub get_lonbalancer_config {
 1215:     my ($servers) = @_;
 1216:     my ($currbalancer,$currtargets);
 1217:     if (ref($servers) eq 'HASH') {
 1218:         foreach my $server (keys(%{$servers})) {
 1219:             my %what = (
 1220:                          spareid => 1,
 1221:                          perlvar => 1,
 1222:                        );
 1223:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
 1224:             if ($result eq 'ok') {
 1225:                 if (ref($returnhash) eq 'HASH') {
 1226:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
 1227:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
 1228:                             $currbalancer = $server;
 1229:                             $currtargets = {};
 1230:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
 1231:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
 1232:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
 1233:                                 }
 1234:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
 1235:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
 1236:                                 }
 1237:                             }
 1238:                             last;
 1239:                         }
 1240:                     }
 1241:                 }
 1242:             }
 1243:         }
 1244:     }
 1245:     return ($currbalancer,$currtargets);
 1246: }
 1247: 
 1248: sub check_loadbalancing {
 1249:     my ($uname,$udom) = @_;
 1250:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
 1251:         $rule_in_effect,$offloadto,$otherserver);
 1252:     my $lonhost = $perlvar{'lonHostID'};
 1253:     my @hosts = &current_machine_ids();
 1254:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1255:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
 1256:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
 1257:     my $serverhomedom = &host_domain($lonhost);
 1258: 
 1259:     my $cachetime = 60*60*24;
 1260: 
 1261:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1262:         $dom_in_use = $udom;
 1263:         $homeintdom = 1;
 1264:     } else {
 1265:         $dom_in_use = $serverhomedom;
 1266:     }
 1267:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
 1268:     unless (defined($cached)) {
 1269:         my %domconfig =
 1270:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
 1271:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1272:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1273:         }
 1274:     }
 1275:     if (ref($result) eq 'HASH') {
 1276:         ($is_balancer,$currtargets,$currrules) = 
 1277:             &check_balancer_result($result,@hosts);
 1278:         if ($is_balancer) {
 1279:             if (ref($currrules) eq 'HASH') {
 1280:                 if ($homeintdom) {
 1281:                     if ($uname ne '') {
 1282:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
 1283:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
 1284:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
 1285:                                 $rule_in_effect = $currrules->{'_LC_author'};
 1286:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
 1287:                                 $rule_in_effect = $currrules->{'_LC_adv'}
 1288:                             }
 1289:                         }
 1290:                         if ($rule_in_effect eq '') {
 1291:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
 1292:                             if ($userenv{'inststatus'} ne '') {
 1293:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
 1294:                                 my ($othertitle,$usertypes,$types) =
 1295:                                     &Apache::loncommon::sorted_inst_types($udom);
 1296:                                 if (ref($types) eq 'ARRAY') {
 1297:                                     foreach my $type (@{$types}) {
 1298:                                         if (grep(/^\Q$type\E$/,@statuses)) {
 1299:                                             if (exists($currrules->{$type})) {
 1300:                                                 $rule_in_effect = $currrules->{$type};
 1301:                                             }
 1302:                                         }
 1303:                                     }
 1304:                                 }
 1305:                             } else {
 1306:                                 if (exists($currrules->{'default'})) {
 1307:                                     $rule_in_effect = $currrules->{'default'};
 1308:                                 }
 1309:                             }
 1310:                         }
 1311:                     } else {
 1312:                         if (exists($currrules->{'default'})) {
 1313:                             $rule_in_effect = $currrules->{'default'};
 1314:                         }
 1315:                     }
 1316:                 } else {
 1317:                     if ($currrules->{'_LC_external'} ne '') {
 1318:                         $rule_in_effect = $currrules->{'_LC_external'};
 1319:                     }
 1320:                 }
 1321:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1322:                                                        $uname,$udom);
 1323:             }
 1324:         }
 1325:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
 1326:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
 1327:         unless (defined($cached)) {
 1328:             my %domconfig =
 1329:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
 1330:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1331:                 $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1332:             }
 1333:         }
 1334:         if (ref($result) eq 'HASH') {
 1335:             ($is_balancer,$currtargets,$currrules) = 
 1336:                 &check_balancer_result($result,@hosts);
 1337:             if ($is_balancer) {
 1338:                 if (ref($currrules) eq 'HASH') {
 1339:                     if ($currrules->{'_LC_internetdom'} ne '') {
 1340:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
 1341:                     }
 1342:                 }
 1343:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1344:                                                        $uname,$udom);
 1345:             }
 1346:         } else {
 1347:             if ($perlvar{'lonBalancer'} eq 'yes') {
 1348:                 $is_balancer = 1;
 1349:                 $offloadto = &this_host_spares($dom_in_use);
 1350:             }
 1351:         }
 1352:     } else {
 1353:         if ($perlvar{'lonBalancer'} eq 'yes') {
 1354:             $is_balancer = 1;
 1355:             $offloadto = &this_host_spares($dom_in_use);
 1356:         }
 1357:     }
 1358:     if ($is_balancer) {
 1359:         my $lowest_load = 30000;
 1360:         if (ref($offloadto) eq 'HASH') {
 1361:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
 1362:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
 1363:                     ($otherserver,$lowest_load) =
 1364:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1365:                 }
 1366:             }
 1367:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
 1368: 
 1369:             if (!$found_server) {
 1370:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
 1371:                     foreach my $try_server (@{$offloadto->{'default'}}) {
 1372:                         ($otherserver,$lowest_load) =
 1373:                             &compare_server_load($try_server,$otherserver,$lowest_load);
 1374:                     }
 1375:                 }
 1376:             }
 1377:         } elsif (ref($offloadto) eq 'ARRAY') {
 1378:             if (@{$offloadto} == 1) {
 1379:                 $otherserver = $offloadto->[0];
 1380:             } elsif (@{$offloadto} > 1) {
 1381:                 foreach my $try_server (@{$offloadto}) {
 1382:                     ($otherserver,$lowest_load) =
 1383:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1384:                 }
 1385:             }
 1386:         }
 1387:         if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
 1388:             $is_balancer = 0;
 1389:             if ($uname ne '' && $udom ne '') {
 1390:                 if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
 1391:                     
 1392:                     &appenv({'user.loadbalexempt'     => $lonhost,  
 1393:                              'user.loadbalcheck.time' => time});
 1394:                 }
 1395:             }
 1396:         }
 1397:     }
 1398:     return ($is_balancer,$otherserver);
 1399: }
 1400: 
 1401: sub check_balancer_result {
 1402:     my ($result,@hosts) = @_;
 1403:     my ($is_balancer,$currtargets,$currrules);
 1404:     if (ref($result) eq 'HASH') {
 1405:         if ($result->{'lonhost'} ne '') {
 1406:             my $currbalancer = $result->{'lonhost'};
 1407:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
 1408:                 $is_balancer = 1;
 1409:                 $currtargets = $result->{'targets'};
 1410:                 $currrules = $result->{'rules'};
 1411:             }
 1412:         } else {
 1413:             foreach my $key (keys(%{$result})) {
 1414:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
 1415:                     (ref($result->{$key}) eq 'HASH')) {
 1416:                     $is_balancer = 1;
 1417:                     $currrules = $result->{$key}{'rules'};
 1418:                     $currtargets = $result->{$key}{'targets'};
 1419:                     last;
 1420:                 }
 1421:             }
 1422:         }
 1423:     }
 1424:     return ($is_balancer,$currtargets,$currrules);
 1425: }
 1426: 
 1427: sub get_loadbalancer_targets {
 1428:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
 1429:     my $offloadto;
 1430:     if ($rule_in_effect eq 'none') {
 1431:         return [$perlvar{'lonHostID'}];
 1432:     } elsif ($rule_in_effect eq '') {
 1433:         $offloadto = $currtargets;
 1434:     } else {
 1435:         if ($rule_in_effect eq 'homeserver') {
 1436:             my $homeserver = &homeserver($uname,$udom);
 1437:             if ($homeserver ne 'no_host') {
 1438:                 $offloadto = [$homeserver];
 1439:             }
 1440:         } elsif ($rule_in_effect eq 'externalbalancer') {
 1441:             my %domconfig =
 1442:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1443:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1444:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
 1445:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
 1446:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
 1447:                     }
 1448:                 }
 1449:             } else {
 1450:                 my %servers = &internet_dom_servers($udom);
 1451:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
 1452:                 if (&hostname($remotebalancer) ne '') {
 1453:                     $offloadto = [$remotebalancer];
 1454:                 }
 1455:             }
 1456:         } elsif (&hostname($rule_in_effect) ne '') {
 1457:             $offloadto = [$rule_in_effect];
 1458:         }
 1459:     }
 1460:     return $offloadto;
 1461: }
 1462: 
 1463: sub internet_dom_servers {
 1464:     my ($dom) = @_;
 1465:     my (%uniqservers,%servers);
 1466:     my $primaryserver = &hostname(&domain($dom,'primary'));
 1467:     my @machinedoms = &machine_domains($primaryserver);
 1468:     foreach my $mdom (@machinedoms) {
 1469:         my %currservers = %servers;
 1470:         my %server = &get_servers($mdom);
 1471:         %servers = (%currservers,%server);
 1472:     }
 1473:     my %by_hostname;
 1474:     foreach my $id (keys(%servers)) {
 1475:         push(@{$by_hostname{$servers{$id}}},$id);
 1476:     }
 1477:     foreach my $hostname (sort(keys(%by_hostname))) {
 1478:         if (@{$by_hostname{$hostname}} > 1) {
 1479:             my $match = 0;
 1480:             foreach my $id (@{$by_hostname{$hostname}}) {
 1481:                 if (&host_domain($id) eq $dom) {
 1482:                     $uniqservers{$id} = $hostname;
 1483:                     $match = 1;
 1484:                 }
 1485:             }
 1486:             unless ($match) {
 1487:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1488:             }
 1489:         } else {
 1490:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1491:         }
 1492:     }
 1493:     return %uniqservers;
 1494: }
 1495: 
 1496: # ---------------------- Find the homebase for a user from domain's lib servers
 1497: 
 1498: my %homecache;
 1499: sub homeserver {
 1500:     my ($uname,$udom,$ignoreBadCache)=@_;
 1501:     my $index="$uname:$udom";
 1502: 
 1503:     if (exists($homecache{$index})) { return $homecache{$index}; }
 1504: 
 1505:     my %servers = &get_servers($udom,'library');
 1506:     foreach my $tryserver (keys(%servers)) {
 1507:         next if ($ignoreBadCache ne 'true' && 
 1508: 		 exists($badServerCache{$tryserver}));
 1509: 
 1510: 	my $answer=reply("home:$udom:$uname",$tryserver);
 1511: 	if ($answer eq 'found') {
 1512: 	    delete($badServerCache{$tryserver}); 
 1513: 	    return $homecache{$index}=$tryserver;
 1514: 	} elsif ($answer eq 'no_host') {
 1515: 	    $badServerCache{$tryserver}=1;
 1516: 	}
 1517:     }    
 1518:     return 'no_host';
 1519: }
 1520: 
 1521: # ------------------------------------- Find the usernames behind a list of IDs
 1522: 
 1523: sub idget {
 1524:     my ($udom,@ids)=@_;
 1525:     my %returnhash=();
 1526:     
 1527:     my %servers = &get_servers($udom,'library');
 1528:     foreach my $tryserver (keys(%servers)) {
 1529: 	my $idlist=join('&',@ids);
 1530: 	$idlist=~tr/A-Z/a-z/; 
 1531: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
 1532: 	my @answer=();
 1533: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
 1534: 	    @answer=split(/\&/,$reply);
 1535: 	}                    ;
 1536: 	my $i;
 1537: 	for ($i=0;$i<=$#ids;$i++) {
 1538: 	    if ($answer[$i]) {
 1539: 		$returnhash{$ids[$i]}=$answer[$i];
 1540: 	    } 
 1541: 	}
 1542:     } 
 1543:     return %returnhash;
 1544: }
 1545: 
 1546: # ------------------------------------- Find the IDs behind a list of usernames
 1547: 
 1548: sub idrget {
 1549:     my ($udom,@unames)=@_;
 1550:     my %returnhash=();
 1551:     foreach my $uname (@unames) {
 1552:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
 1553:     }
 1554:     return %returnhash;
 1555: }
 1556: 
 1557: # ------------------------------- Store away a list of names and associated IDs
 1558: 
 1559: sub idput {
 1560:     my ($udom,%ids)=@_;
 1561:     my %servers=();
 1562:     foreach my $uname (keys(%ids)) {
 1563: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
 1564:         my $uhom=&homeserver($uname,$udom);
 1565:         if ($uhom ne 'no_host') {
 1566:             my $id=&escape($ids{$uname});
 1567:             $id=~tr/A-Z/a-z/;
 1568:             my $esc_unam=&escape($uname);
 1569: 	    if ($servers{$uhom}) {
 1570: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
 1571:             } else {
 1572:                 $servers{$uhom}=$id.'='.$esc_unam;
 1573:             }
 1574:         }
 1575:     }
 1576:     foreach my $server (keys(%servers)) {
 1577:         &critical('idput:'.$udom.':'.$servers{$server},$server);
 1578:     }
 1579: }
 1580: 
 1581: # ---------------------------------------- Delete unwanted IDs from ids.db file 
 1582: 
 1583: sub iddel {
 1584:     my ($udom,$idshashref,$uhome)=@_;
 1585:     my %result=();
 1586:     unless (ref($idshashref) eq 'HASH') {
 1587:         return %result;
 1588:     }
 1589:     my %servers=();
 1590:     while (my ($id,$uname) = each(%{$idshashref})) {
 1591:         my $uhom;
 1592:         if ($uhome) {
 1593:             $uhom = $uhome;
 1594:         } else {
 1595:             $uhom=&homeserver($uname,$udom);
 1596:         }
 1597:         if ($uhom ne 'no_host') {
 1598:             if ($servers{$uhom}) {
 1599:                 $servers{$uhom}.='&'.&escape($id);
 1600:             } else {
 1601:                 $servers{$uhom}=&escape($id);
 1602:             }
 1603:         }
 1604:     }
 1605:     foreach my $server (keys(%servers)) {
 1606:         $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
 1607:     }
 1608:     return %result;
 1609: }
 1610: 
 1611: # ------------------------------dump from db file owned by domainconfig user
 1612: sub dump_dom {
 1613:     my ($namespace, $udom, $regexp) = @_;
 1614: 
 1615:     $udom ||= $env{'user.domain'};
 1616: 
 1617:     return () unless $udom;
 1618: 
 1619:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
 1620: }
 1621: 
 1622: # ------------------------------------------ get items from domain db files   
 1623: 
 1624: sub get_dom {
 1625:     my ($namespace,$storearr,$udom,$uhome)=@_;
 1626:     my $items='';
 1627:     foreach my $item (@$storearr) {
 1628:         $items.=&escape($item).'&';
 1629:     }
 1630:     $items=~s/\&$//;
 1631:     if (!$udom) {
 1632:         $udom=$env{'user.domain'};
 1633:         if (defined(&domain($udom,'primary'))) {
 1634:             $uhome=&domain($udom,'primary');
 1635:         } else {
 1636:             undef($uhome);
 1637:         }
 1638:     } else {
 1639:         if (!$uhome) {
 1640:             if (defined(&domain($udom,'primary'))) {
 1641:                 $uhome=&domain($udom,'primary');
 1642:             }
 1643:         }
 1644:     }
 1645:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1646:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 1647:         my %returnhash;
 1648:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 1649:             return %returnhash;
 1650:         }
 1651:         my @pairs=split(/\&/,$rep);
 1652:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 1653:             return @pairs;
 1654:         }
 1655:         my $i=0;
 1656:         foreach my $item (@$storearr) {
 1657:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 1658:             $i++;
 1659:         }
 1660:         return %returnhash;
 1661:     } else {
 1662:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 1663:     }
 1664: }
 1665: 
 1666: # -------------------------------------------- put items in domain db files 
 1667: 
 1668: sub put_dom {
 1669:     my ($namespace,$storehash,$udom,$uhome)=@_;
 1670:     if (!$udom) {
 1671:         $udom=$env{'user.domain'};
 1672:         if (defined(&domain($udom,'primary'))) {
 1673:             $uhome=&domain($udom,'primary');
 1674:         } else {
 1675:             undef($uhome);
 1676:         }
 1677:     } else {
 1678:         if (!$uhome) {
 1679:             if (defined(&domain($udom,'primary'))) {
 1680:                 $uhome=&domain($udom,'primary');
 1681:             }
 1682:         }
 1683:     } 
 1684:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1685:         my $items='';
 1686:         foreach my $item (keys(%$storehash)) {
 1687:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 1688:         }
 1689:         $items=~s/\&$//;
 1690:         return &reply("putdom:$udom:$namespace:$items",$uhome);
 1691:     } else {
 1692:         &logthis("put_dom failed - no homeserver and/or domain");
 1693:     }
 1694: }
 1695: 
 1696: # --------------------- newput for items in db file owned by domainconfig user
 1697: sub newput_dom {
 1698:     my ($namespace,$storehash,$udom) = @_;
 1699:     my $result;
 1700:     if (!$udom) {
 1701:         $udom=$env{'user.domain'};
 1702:     }
 1703:     if ($udom) {
 1704:         my $uname = &get_domainconfiguser($udom);
 1705:         $result = &newput($namespace,$storehash,$udom,$uname);
 1706:     }
 1707:     return $result;
 1708: }
 1709: 
 1710: # --------------------- delete for items in db file owned by domainconfig user
 1711: sub del_dom {
 1712:     my ($namespace,$storearr,$udom)=@_;
 1713:     if (ref($storearr) eq 'ARRAY') {
 1714:         if (!$udom) {
 1715:             $udom=$env{'user.domain'};
 1716:         }
 1717:         if ($udom) {
 1718:             my $uname = &get_domainconfiguser($udom); 
 1719:             return &del($namespace,$storearr,$udom,$uname);
 1720:         }
 1721:     }
 1722: }
 1723: 
 1724: # ----------------------------------construct domainconfig user for a domain 
 1725: sub get_domainconfiguser {
 1726:     my ($udom) = @_;
 1727:     return $udom.'-domainconfig';
 1728: }
 1729: 
 1730: sub retrieve_inst_usertypes {
 1731:     my ($udom) = @_;
 1732:     my (%returnhash,@order);
 1733:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 1734:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 1735:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 1736:         %returnhash = %{$domdefs{'inststatustypes'}};
 1737:         @order = @{$domdefs{'inststatusorder'}};
 1738:     } else {
 1739:         if (defined(&domain($udom,'primary'))) {
 1740:             my $uhome=&domain($udom,'primary');
 1741:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 1742:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 1743:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
 1744:                 return (\%returnhash,\@order);
 1745:             }
 1746:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 1747:             my @pairs=split(/\&/,$hashitems);
 1748:             foreach my $item (@pairs) {
 1749:                 my ($key,$value)=split(/=/,$item,2);
 1750:                 $key = &unescape($key);
 1751:                 next if ($key =~ /^error: 2 /);
 1752:                 $returnhash{$key}=&thaw_unescape($value);
 1753:             }
 1754:             my @esc_order = split(/\&/,$orderitems);
 1755:             foreach my $item (@esc_order) {
 1756:                 push(@order,&unescape($item));
 1757:             }
 1758:         } else {
 1759:             &logthis("get_dom failed - no primary domain server for $udom");
 1760:         }
 1761:     }
 1762:     return (\%returnhash,\@order);
 1763: }
 1764: 
 1765: sub is_domainimage {
 1766:     my ($url) = @_;
 1767:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
 1768:         if (&domain($1) ne '') {
 1769:             return '1';
 1770:         }
 1771:     }
 1772:     return;
 1773: }
 1774: 
 1775: sub inst_directory_query {
 1776:     my ($srch) = @_;
 1777:     my $udom = $srch->{'srchdomain'};
 1778:     my %results;
 1779:     my $homeserver = &domain($udom,'primary');
 1780:     my $outcome;
 1781:     if ($homeserver ne '') {
 1782: 	my $queryid=&reply("querysend:instdirsearch:".
 1783: 			   &escape($srch->{'srchby'}).':'.
 1784: 			   &escape($srch->{'srchterm'}).':'.
 1785: 			   &escape($srch->{'srchtype'}),$homeserver);
 1786: 	my $host=&hostname($homeserver);
 1787: 	if ($queryid !~/^\Q$host\E\_/) {
 1788: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1789: 	    return;
 1790: 	}
 1791: 	my $response = &get_query_reply($queryid);
 1792: 	my $maxtries = 5;
 1793: 	my $tries = 1;
 1794: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1795: 	    $response = &get_query_reply($queryid);
 1796: 	    $tries ++;
 1797: 	}
 1798: 
 1799:         if (!&error($response) && $response ne 'refused') {
 1800:             if ($response eq 'unavailable') {
 1801:                 $outcome = $response;
 1802:             } else {
 1803:                 $outcome = 'ok';
 1804:                 my @matches = split(/\n/,$response);
 1805:                 foreach my $match (@matches) {
 1806:                     my ($key,$value) = split(/=/,$match);
 1807:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 1808:                 }
 1809:             }
 1810:         }
 1811:     }
 1812:     return ($outcome,%results);
 1813: }
 1814: 
 1815: sub usersearch {
 1816:     my ($srch) = @_;
 1817:     my $dom = $srch->{'srchdomain'};
 1818:     my %results;
 1819:     my %libserv = &all_library();
 1820:     my $query = 'usersearch';
 1821:     foreach my $tryserver (keys(%libserv)) {
 1822:         if (&host_domain($tryserver) eq $dom) {
 1823:             my $host=&hostname($tryserver);
 1824:             my $queryid=
 1825:                 &reply("querysend:".&escape($query).':'.
 1826:                        &escape($srch->{'srchby'}).':'.
 1827:                        &escape($srch->{'srchtype'}).':'.
 1828:                        &escape($srch->{'srchterm'}),$tryserver);
 1829:             if ($queryid !~/^\Q$host\E\_/) {
 1830:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 1831:                 next;
 1832:             }
 1833:             my $reply = &get_query_reply($queryid);
 1834:             my $maxtries = 1;
 1835:             my $tries = 1;
 1836:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 1837:                 $reply = &get_query_reply($queryid);
 1838:                 $tries ++;
 1839:             }
 1840:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 1841:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 1842:             } else {
 1843:                 my @matches;
 1844:                 if ($reply =~ /\n/) {
 1845:                     @matches = split(/\n/,$reply);
 1846:                 } else {
 1847:                     @matches = split(/\&/,$reply);
 1848:                 }
 1849:                 foreach my $match (@matches) {
 1850:                     my ($uname,$udom,%userhash);
 1851:                     foreach my $entry (split(/:/,$match)) {
 1852:                         my ($key,$value) =
 1853:                             map {&unescape($_);} split(/=/,$entry);
 1854:                         $userhash{$key} = $value;
 1855:                         if ($key eq 'username') {
 1856:                             $uname = $value;
 1857:                         } elsif ($key eq 'domain') {
 1858:                             $udom = $value;
 1859:                         }
 1860:                     }
 1861:                     $results{$uname.':'.$udom} = \%userhash;
 1862:                 }
 1863:             }
 1864:         }
 1865:     }
 1866:     return %results;
 1867: }
 1868: 
 1869: sub get_instuser {
 1870:     my ($udom,$uname,$id) = @_;
 1871:     my $homeserver = &domain($udom,'primary');
 1872:     my ($outcome,%results);
 1873:     if ($homeserver ne '') {
 1874:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 1875:                            &escape($id).':'.&escape($udom),$homeserver);
 1876:         my $host=&hostname($homeserver);
 1877:         if ($queryid !~/^\Q$host\E\_/) {
 1878:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1879:             return;
 1880:         }
 1881:         my $response = &get_query_reply($queryid);
 1882:         my $maxtries = 5;
 1883:         my $tries = 1;
 1884:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1885:             $response = &get_query_reply($queryid);
 1886:             $tries ++;
 1887:         }
 1888:         if (!&error($response) && $response ne 'refused') {
 1889:             if ($response eq 'unavailable') {
 1890:                 $outcome = $response;
 1891:             } else {
 1892:                 $outcome = 'ok';
 1893:                 my @matches = split(/\n/,$response);
 1894:                 foreach my $match (@matches) {
 1895:                     my ($key,$value) = split(/=/,$match);
 1896:                     $results{&unescape($key)} = &thaw_unescape($value);
 1897:                 }
 1898:             }
 1899:         }
 1900:     }
 1901:     my %userinfo;
 1902:     if (ref($results{$uname}) eq 'HASH') {
 1903:         %userinfo = %{$results{$uname}};
 1904:     } 
 1905:     return ($outcome,%userinfo);
 1906: }
 1907: 
 1908: sub inst_rulecheck {
 1909:     my ($udom,$uname,$id,$item,$rules) = @_;
 1910:     my %returnhash;
 1911:     if ($udom ne '') {
 1912:         if (ref($rules) eq 'ARRAY') {
 1913:             @{$rules} = map {&escape($_);} (@{$rules});
 1914:             my $rulestr = join(':',@{$rules});
 1915:             my $homeserver=&domain($udom,'primary');
 1916:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1917:                 my $response;
 1918:                 if ($item eq 'username') {                
 1919:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 1920:                                               ':'.&escape($uname).':'.$rulestr,
 1921:                                               $homeserver));
 1922:                 } elsif ($item eq 'id') {
 1923:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 1924:                                               ':'.&escape($id).':'.$rulestr,
 1925:                                               $homeserver));
 1926:                 } elsif ($item eq 'selfcreate') {
 1927:                     $response=&unescape(&reply('instselfcreatecheck:'.
 1928:                                                &escape($udom).':'.&escape($uname).
 1929:                                               ':'.$rulestr,$homeserver));
 1930:                 }
 1931:                 if ($response ne 'refused') {
 1932:                     my @pairs=split(/\&/,$response);
 1933:                     foreach my $item (@pairs) {
 1934:                         my ($key,$value)=split(/=/,$item,2);
 1935:                         $key = &unescape($key);
 1936:                         next if ($key =~ /^error: 2 /);
 1937:                         $returnhash{$key}=&thaw_unescape($value);
 1938:                     }
 1939:                 }
 1940:             }
 1941:         }
 1942:     }
 1943:     return %returnhash;
 1944: }
 1945: 
 1946: sub inst_userrules {
 1947:     my ($udom,$check) = @_;
 1948:     my (%ruleshash,@ruleorder);
 1949:     if ($udom ne '') {
 1950:         my $homeserver=&domain($udom,'primary');
 1951:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1952:             my $response;
 1953:             if ($check eq 'id') {
 1954:                 $response=&reply('instidrules:'.&escape($udom),
 1955:                                  $homeserver);
 1956:             } elsif ($check eq 'email') {
 1957:                 $response=&reply('instemailrules:'.&escape($udom),
 1958:                                  $homeserver);
 1959:             } else {
 1960:                 $response=&reply('instuserrules:'.&escape($udom),
 1961:                                  $homeserver);
 1962:             }
 1963:             if (($response ne 'refused') && ($response ne 'error') && 
 1964:                 ($response ne 'unknown_cmd') && 
 1965:                 ($response ne 'no_such_host')) {
 1966:                 my ($hashitems,$orderitems) = split(/:/,$response);
 1967:                 my @pairs=split(/\&/,$hashitems);
 1968:                 foreach my $item (@pairs) {
 1969:                     my ($key,$value)=split(/=/,$item,2);
 1970:                     $key = &unescape($key);
 1971:                     next if ($key =~ /^error: 2 /);
 1972:                     $ruleshash{$key}=&thaw_unescape($value);
 1973:                 }
 1974:                 my @esc_order = split(/\&/,$orderitems);
 1975:                 foreach my $item (@esc_order) {
 1976:                     push(@ruleorder,&unescape($item));
 1977:                 }
 1978:             }
 1979:         }
 1980:     }
 1981:     return (\%ruleshash,\@ruleorder);
 1982: }
 1983: 
 1984: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 1985: 
 1986: sub get_domain_defaults {
 1987:     my ($domain,$ignore_cache) = @_;
 1988:     my $cachetime = 60*60*24;
 1989:     unless ($ignore_cache) {
 1990:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 1991:         if (defined($cached)) {
 1992:             if (ref($result) eq 'HASH') {
 1993:                 return %{$result};
 1994:             }
 1995:         }
 1996:     }
 1997:     my %domdefaults;
 1998:     my %domconfig =
 1999:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 2000:                                   'requestcourses','inststatus',
 2001:                                   'coursedefaults','usersessions',
 2002:                                   'requestauthor'],$domain);
 2003:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 2004:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 2005:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 2006:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 2007:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 2008:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 2009:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
 2010:     } else {
 2011:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 2012:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 2013:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 2014:     }
 2015:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 2016:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 2017:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 2018:         } else {
 2019:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 2020:         }
 2021:         my @usertools = ('aboutme','blog','webdav','portfolio');
 2022:         foreach my $item (@usertools) {
 2023:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 2024:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 2025:             }
 2026:         }
 2027:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
 2028:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
 2029:         }
 2030:     }
 2031:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 2032:         foreach my $item ('official','unofficial','community') {
 2033:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 2034:         }
 2035:     }
 2036:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
 2037:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
 2038:     }
 2039:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 2040:         foreach my $item ('inststatustypes','inststatusorder') {
 2041:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 2042:         }
 2043:     }
 2044:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 2045:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
 2046:         if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
 2047:             $domdefaults{'officialcredits'} = $domconfig{'coursedefaults'}{'coursecredits'}{'official'};
 2048:             $domdefaults{'unofficialcredits'} = $domconfig{'coursedefaults'}{'coursecredits'}{'unofficial'};
 2049:         }
 2050:         if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
 2051:             $domdefaults{'officialquota'} = $domconfig{'coursedefaults'}{'uploadquota'}{'official'};
 2052:             $domdefaults{'unofficialquota'} = $domconfig{'coursedefaults'}{'uploadquota'}{'unofficial'};
 2053:             $domdefaults{'communityquota'} = $domconfig{'coursedefaults'}{'uploadquota'}{'community'};           
 2054:         }
 2055:     }
 2056:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 2057:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 2058:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 2059:         }
 2060:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 2061:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 2062:         }
 2063:     }
 2064:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
 2065:     return %domdefaults;
 2066: }
 2067: 
 2068: # --------------------------------------------------- Assign a key to a student
 2069: 
 2070: sub assign_access_key {
 2071: #
 2072: # a valid key looks like uname:udom#comments
 2073: # comments are being appended
 2074: #
 2075:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 2076:     $kdom=
 2077:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 2078:     $knum=
 2079:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 2080:     $cdom=
 2081:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2082:     $cnum=
 2083:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2084:     $udom=$env{'user.name'} unless (defined($udom));
 2085:     $uname=$env{'user.domain'} unless (defined($uname));
 2086:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 2087:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 2088:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 2089:                                                   # assigned to this person
 2090:                                                   # - this should not happen,
 2091:                                                   # unless something went wrong
 2092:                                                   # the first time around
 2093: # ready to assign
 2094:         $logentry=$1.'; '.$logentry;
 2095:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 2096:                                                  $kdom,$knum) eq 'ok') {
 2097: # key now belongs to user
 2098: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 2099:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 2100:                 &appenv({'environment.'.$envkey => $ckey});
 2101:                 return 'ok';
 2102:             } else {
 2103:                 return 
 2104:   'error: Count not permanently assign key, will need to be re-entered later.';
 2105: 	    }
 2106:         } else {
 2107:             return 'error: Could not assign key, try again later.';
 2108:         }
 2109:     } elsif (!$existing{$ckey}) {
 2110: # the key does not exist
 2111: 	return 'error: The key does not exist';
 2112:     } else {
 2113: # the key is somebody else's
 2114: 	return 'error: The key is already in use';
 2115:     }
 2116: }
 2117: 
 2118: # ------------------------------------------ put an additional comment on a key
 2119: 
 2120: sub comment_access_key {
 2121: #
 2122: # a valid key looks like uname:udom#comments
 2123: # comments are being appended
 2124: #
 2125:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 2126:     $cdom=
 2127:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2128:     $cnum=
 2129:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2130:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2131:     if ($existing{$ckey}) {
 2132:         $existing{$ckey}.='; '.$logentry;
 2133: # ready to assign
 2134:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 2135:                                                  $cdom,$cnum) eq 'ok') {
 2136: 	    return 'ok';
 2137:         } else {
 2138: 	    return 'error: Count not store comment.';
 2139:         }
 2140:     } else {
 2141: # the key does not exist
 2142: 	return 'error: The key does not exist';
 2143:     }
 2144: }
 2145: 
 2146: # ------------------------------------------------------ Generate a set of keys
 2147: 
 2148: sub generate_access_keys {
 2149:     my ($number,$cdom,$cnum,$logentry)=@_;
 2150:     $cdom=
 2151:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2152:     $cnum=
 2153:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2154:     unless (&allowed('mky',$cdom)) { return 0; }
 2155:     unless (($cdom) && ($cnum)) { return 0; }
 2156:     if ($number>10000) { return 0; }
 2157:     sleep(2); # make sure don't get same seed twice
 2158:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 2159:     my $total=0;
 2160:     for (my $i=1;$i<=$number;$i++) {
 2161:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 2162:                   sprintf("%lx",int(100000*rand)).'-'.
 2163:                   sprintf("%lx",int(100000*rand));
 2164:        $newkey=~s/1/g/g; # folks mix up 1 and l
 2165:        $newkey=~s/0/h/g; # and also 0 and O
 2166:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 2167:        if ($existing{$newkey}) {
 2168:            $i--;
 2169:        } else {
 2170: 	  if (&put('accesskeys',
 2171:               { $newkey => '# generated '.localtime().
 2172:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 2173:                            '; '.$logentry },
 2174: 		   $cdom,$cnum) eq 'ok') {
 2175:               $total++;
 2176: 	  }
 2177:        }
 2178:     }
 2179:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 2180:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 2181:     return $total;
 2182: }
 2183: 
 2184: # ------------------------------------------------------- Validate an accesskey
 2185: 
 2186: sub validate_access_key {
 2187:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 2188:     $cdom=
 2189:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2190:     $cnum=
 2191:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2192:     $udom=$env{'user.domain'} unless (defined($udom));
 2193:     $uname=$env{'user.name'} unless (defined($uname));
 2194:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2195:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 2196: }
 2197: 
 2198: # ------------------------------------- Find the section of student in a course
 2199: sub devalidate_getsection_cache {
 2200:     my ($udom,$unam,$courseid)=@_;
 2201:     my $hashid="$udom:$unam:$courseid";
 2202:     &devalidate_cache_new('getsection',$hashid);
 2203: }
 2204: 
 2205: sub courseid_to_courseurl {
 2206:     my ($courseid) = @_;
 2207:     #already url style courseid
 2208:     return $courseid if ($courseid =~ m{^/});
 2209: 
 2210:     if (exists($env{'course.'.$courseid.'.num'})) {
 2211: 	my $cnum = $env{'course.'.$courseid.'.num'};
 2212: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 2213: 	return "/$cdom/$cnum";
 2214:     }
 2215: 
 2216:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 2217:     if (exists($courseinfo{'num'})) {
 2218: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 2219:     }
 2220: 
 2221:     return undef;
 2222: }
 2223: 
 2224: sub getsection {
 2225:     my ($udom,$unam,$courseid)=@_;
 2226:     my $cachetime=1800;
 2227: 
 2228:     my $hashid="$udom:$unam:$courseid";
 2229:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 2230:     if (defined($cached)) { return $result; }
 2231: 
 2232:     my %Pending; 
 2233:     my %Expired;
 2234:     #
 2235:     # Each role can either have not started yet (pending), be active, 
 2236:     #    or have expired.
 2237:     #
 2238:     # If there is an active role, we are done.
 2239:     #
 2240:     # If there is more than one role which has not started yet, 
 2241:     #     choose the one which will start sooner
 2242:     # If there is one role which has not started yet, return it.
 2243:     #
 2244:     # If there is more than one expired role, choose the one which ended last.
 2245:     # If there is a role which has expired, return it.
 2246:     #
 2247:     $courseid = &courseid_to_courseurl($courseid);
 2248:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 2249:     foreach my $key (keys(%roleshash)) {
 2250:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 2251:         my $section=$1;
 2252:         if ($key eq $courseid.'_st') { $section=''; }
 2253:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 2254:         my $now=time;
 2255:         if (defined($end) && $end && ($now > $end)) {
 2256:             $Expired{$end}=$section;
 2257:             next;
 2258:         }
 2259:         if (defined($start) && $start && ($now < $start)) {
 2260:             $Pending{$start}=$section;
 2261:             next;
 2262:         }
 2263:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 2264:     }
 2265:     #
 2266:     # Presumedly there will be few matching roles from the above
 2267:     # loop and the sorting time will be negligible.
 2268:     if (scalar(keys(%Pending))) {
 2269:         my ($time) = sort {$a <=> $b} keys(%Pending);
 2270:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 2271:     } 
 2272:     if (scalar(keys(%Expired))) {
 2273:         my @sorted = sort {$a <=> $b} keys(%Expired);
 2274:         my $time = pop(@sorted);
 2275:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 2276:     }
 2277:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 2278: }
 2279: 
 2280: sub save_cache {
 2281:     &purge_remembered();
 2282:     #&Apache::loncommon::validate_page();
 2283:     undef(%env);
 2284:     undef($env_loaded);
 2285: }
 2286: 
 2287: my $to_remember=-1;
 2288: my %remembered;
 2289: my %accessed;
 2290: my $kicks=0;
 2291: my $hits=0;
 2292: sub make_key {
 2293:     my ($name,$id) = @_;
 2294:     if (length($id) > 65 
 2295: 	&& length(&escape($id)) > 200) {
 2296: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 2297:     }
 2298:     return &escape($name.':'.$id);
 2299: }
 2300: 
 2301: sub devalidate_cache_new {
 2302:     my ($name,$id,$debug) = @_;
 2303:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 2304:     $id=&make_key($name,$id);
 2305:     $memcache->delete($id);
 2306:     delete($remembered{$id});
 2307:     delete($accessed{$id});
 2308: }
 2309: 
 2310: sub is_cached_new {
 2311:     my ($name,$id,$debug) = @_;
 2312:     $id=&make_key($name,$id);
 2313:     if (exists($remembered{$id})) {
 2314: 	if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
 2315: 	$accessed{$id}=[&gettimeofday()];
 2316: 	$hits++;
 2317: 	return ($remembered{$id},1);
 2318:     }
 2319:     my $value = $memcache->get($id);
 2320:     if (!(defined($value))) {
 2321: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 2322: 	return (undef,undef);
 2323:     }
 2324:     if ($value eq '__undef__') {
 2325: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 2326: 	$value=undef;
 2327:     }
 2328:     &make_room($id,$value,$debug);
 2329:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 2330:     return ($value,1);
 2331: }
 2332: 
 2333: sub do_cache_new {
 2334:     my ($name,$id,$value,$time,$debug) = @_;
 2335:     $id=&make_key($name,$id);
 2336:     my $setvalue=$value;
 2337:     if (!defined($setvalue)) {
 2338: 	$setvalue='__undef__';
 2339:     }
 2340:     if (!defined($time) ) {
 2341: 	$time=600;
 2342:     }
 2343:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 2344:     my $result = $memcache->set($id,$setvalue,$time);
 2345:     if (! $result) {
 2346: 	&logthis("caching of id -> $id  failed");
 2347: 	$memcache->disconnect_all();
 2348:     }
 2349:     # need to make a copy of $value
 2350:     &make_room($id,$value,$debug);
 2351:     return $value;
 2352: }
 2353: 
 2354: sub make_room {
 2355:     my ($id,$value,$debug)=@_;
 2356: 
 2357:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
 2358:                                     : $value;
 2359:     if ($to_remember<0) { return; }
 2360:     $accessed{$id}=[&gettimeofday()];
 2361:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 2362:     my $to_kick;
 2363:     my $max_time=0;
 2364:     foreach my $other (keys(%accessed)) {
 2365: 	if (&tv_interval($accessed{$other}) > $max_time) {
 2366: 	    $to_kick=$other;
 2367: 	    $max_time=&tv_interval($accessed{$other});
 2368: 	}
 2369:     }
 2370:     delete($remembered{$to_kick});
 2371:     delete($accessed{$to_kick});
 2372:     $kicks++;
 2373:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 2374:     return;
 2375: }
 2376: 
 2377: sub purge_remembered {
 2378:     #&logthis("Tossing ".scalar(keys(%remembered)));
 2379:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 2380:     undef(%remembered);
 2381:     undef(%accessed);
 2382: }
 2383: # ------------------------------------- Read an entry from a user's environment
 2384: 
 2385: sub userenvironment {
 2386:     my ($udom,$unam,@what)=@_;
 2387:     my $items;
 2388:     foreach my $item (@what) {
 2389:         $items.=&escape($item).'&';
 2390:     }
 2391:     $items=~s/\&$//;
 2392:     my %returnhash=();
 2393:     my $uhome = &homeserver($unam,$udom);
 2394:     unless ($uhome eq 'no_host') {
 2395:         my @answer=split(/\&/, 
 2396:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 2397:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 2398:             return %returnhash;
 2399:         }
 2400:         my $i;
 2401:         for ($i=0;$i<=$#what;$i++) {
 2402: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 2403:         }
 2404:     }
 2405:     return %returnhash;
 2406: }
 2407: 
 2408: # ---------------------------------------------------------- Get a studentphoto
 2409: sub studentphoto {
 2410:     my ($udom,$unam,$ext) = @_;
 2411:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2412:     if (defined($env{'request.course.id'})) {
 2413:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 2414:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 2415:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 2416:             } else {
 2417:                 my ($result,$perm_reqd)=
 2418: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2419:                 if ($result eq 'ok') {
 2420:                     if (!($perm_reqd eq 'yes')) {
 2421:                         return(&retrievestudentphoto($udom,$unam,$ext));
 2422:                     }
 2423:                 }
 2424:             }
 2425:         }
 2426:     } else {
 2427:         my ($result,$perm_reqd) = 
 2428: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2429:         if ($result eq 'ok') {
 2430:             if (!($perm_reqd eq 'yes')) {
 2431:                 return(&retrievestudentphoto($udom,$unam,$ext));
 2432:             }
 2433:         }
 2434:     }
 2435:     return '/adm/lonKaputt/lonlogo_broken.gif';
 2436: }
 2437: 
 2438: sub retrievestudentphoto {
 2439:     my ($udom,$unam,$ext,$type) = @_;
 2440:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2441:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 2442:     if ($ret eq 'ok') {
 2443:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 2444:         if ($type eq 'thumbnail') {
 2445:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 2446:         }
 2447:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 2448:         return $tokenurl;
 2449:     } else {
 2450:         if ($type eq 'thumbnail') {
 2451:             return '/adm/lonKaputt/genericstudent_tn.gif';
 2452:         } else { 
 2453:             return '/adm/lonKaputt/lonlogo_broken.gif';
 2454:         }
 2455:     }
 2456: }
 2457: 
 2458: # -------------------------------------------------------------------- New chat
 2459: 
 2460: sub chatsend {
 2461:     my ($newentry,$anon,$group)=@_;
 2462:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 2463:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2464:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 2465:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 2466: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 2467: 		   &escape($newentry)).':'.$group,$chome);
 2468: }
 2469: 
 2470: # ------------------------------------------ Find current version of a resource
 2471: 
 2472: sub getversion {
 2473:     my $fname=&clutter(shift);
 2474:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
 2475:     return &currentversion(&filelocation('',$fname));
 2476: }
 2477: 
 2478: sub currentversion {
 2479:     my $fname=shift;
 2480:     my $author=$fname;
 2481:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2482:     my ($udom,$uname)=split(/\//,$author);
 2483:     my $home=&homeserver($uname,$udom);
 2484:     if ($home eq 'no_host') { 
 2485:         return -1; 
 2486:     }
 2487:     my $answer=&reply("currentversion:$fname",$home);
 2488:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 2489: 	return -1;
 2490:     }
 2491:     return $answer;
 2492: }
 2493: 
 2494: #
 2495: # Return special version number of resource if set by override, empty otherwise
 2496: #
 2497: sub usedversion {
 2498:     my $fname=shift;
 2499:     unless ($fname) { $fname=$env{'request.uri'}; }
 2500:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 2501:     if ($urlversion) { return $urlversion; }
 2502:     return '';
 2503: }
 2504: 
 2505: # ----------------------------- Subscribe to a resource, return URL if possible
 2506: 
 2507: sub subscribe {
 2508:     my $fname=shift;
 2509:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 2510:     $fname=~s/[\n\r]//g;
 2511:     my $author=$fname;
 2512:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2513:     my ($udom,$uname)=split(/\//,$author);
 2514:     my $home=homeserver($uname,$udom);
 2515:     if ($home eq 'no_host') {
 2516:         return 'not_found';
 2517:     }
 2518:     my $answer=reply("sub:$fname",$home);
 2519:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 2520: 	$answer.=' by '.$home;
 2521:     }
 2522:     return $answer;
 2523: }
 2524:     
 2525: # -------------------------------------------------------------- Replicate file
 2526: 
 2527: sub repcopy {
 2528:     my $filename=shift;
 2529:     $filename=~s/\/+/\//g;
 2530:     my $londocroot = $perlvar{'lonDocRoot'};
 2531:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 2532:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
 2533:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 2534: 	$filename=~m{^/*(uploaded|editupload)/}) {
 2535: 	return &repcopy_userfile($filename);
 2536:     }
 2537:     $filename=~s/[\n\r]//g;
 2538:     my $transname="$filename.in.transfer";
 2539: # FIXME: this should flock
 2540:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 2541:     my $remoteurl=subscribe($filename);
 2542:     if ($remoteurl =~ /^con_lost by/) {
 2543: 	   &logthis("Subscribe returned $remoteurl: $filename");
 2544:            return 'unavailable';
 2545:     } elsif ($remoteurl eq 'not_found') {
 2546: 	   #&logthis("Subscribe returned not_found: $filename");
 2547: 	   return 'not_found';
 2548:     } elsif ($remoteurl =~ /^rejected by/) {
 2549: 	   &logthis("Subscribe returned $remoteurl: $filename");
 2550:            return 'forbidden';
 2551:     } elsif ($remoteurl eq 'directory') {
 2552:            return 'ok';
 2553:     } else {
 2554:         my $author=$filename;
 2555:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2556:         my ($udom,$uname)=split(/\//,$author);
 2557:         my $home=homeserver($uname,$udom);
 2558:         unless ($home eq $perlvar{'lonHostID'}) {
 2559:            my @parts=split(/\//,$filename);
 2560:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 2561:            if ($path ne "$londocroot/res") {
 2562:                &logthis("Malconfiguration for replication: $filename");
 2563: 	       return 'bad_request';
 2564:            }
 2565:            my $count;
 2566:            for ($count=5;$count<$#parts;$count++) {
 2567:                $path.="/$parts[$count]";
 2568:                if ((-e $path)!=1) {
 2569: 		   mkdir($path,0777);
 2570:                }
 2571:            }
 2572:            my $ua=new LWP::UserAgent;
 2573:            my $request=new HTTP::Request('GET',"$remoteurl");
 2574:            my $response=$ua->request($request,$transname);
 2575:            if ($response->is_error()) {
 2576: 	       unlink($transname);
 2577:                my $message=$response->status_line;
 2578:                &logthis("<font color=\"blue\">WARNING:"
 2579:                        ." LWP get: $message: $filename</font>");
 2580:                return 'unavailable';
 2581:            } else {
 2582: 	       if ($remoteurl!~/\.meta$/) {
 2583:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 2584:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 2585:                   if ($mresponse->is_error()) {
 2586: 		      unlink($filename.'.meta');
 2587:                       &logthis(
 2588:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 2589:                   }
 2590: 	       }
 2591:                rename($transname,$filename);
 2592:                return 'ok';
 2593:            }
 2594:        }
 2595:     }
 2596: }
 2597: 
 2598: # ------------------------------------------------ Get server side include body
 2599: sub ssi_body {
 2600:     my ($filelink,%form)=@_;
 2601:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 2602:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 2603:     }
 2604:     my $output='';
 2605:     my $response;
 2606:     if ($filelink=~/^https?\:/) {
 2607:        ($output,$response)=&externalssi($filelink);
 2608:     } else {
 2609:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 2610:        $filelink .= 'inhibitmenu=yes';
 2611:        ($output,$response)=&ssi($filelink,%form);
 2612:     }
 2613:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 2614:     $output=~s/^.*?\<body[^\>]*\>//si;
 2615:     $output=~s/\<\/body\s*\>.*?$//si;
 2616:     if (wantarray) {
 2617:         return ($output, $response);
 2618:     } else {
 2619:         return $output;
 2620:     }
 2621: }
 2622: 
 2623: # --------------------------------------------------------- Server Side Include
 2624: 
 2625: sub absolute_url {
 2626:     my ($host_name) = @_;
 2627:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 2628:     if ($host_name eq '') {
 2629: 	$host_name = $ENV{'SERVER_NAME'};
 2630:     }
 2631:     return $protocol.$host_name;
 2632: }
 2633: 
 2634: #
 2635: #   Server side include.
 2636: # Parameters:
 2637: #  fn     Possibly encrypted resource name/id.
 2638: #  form   Hash that describes how the rendering should be done
 2639: #         and other things.
 2640: # Returns:
 2641: #   Scalar context: The content of the response.
 2642: #   Array context:  2 element list of the content and the full response object.
 2643: #     
 2644: sub ssi {
 2645: 
 2646:     my ($fn,%form)=@_;
 2647:     my $ua=new LWP::UserAgent;
 2648:     my $request;
 2649: 
 2650:     $form{'no_update_last_known'}=1;
 2651:     &Apache::lonenc::check_encrypt(\$fn);
 2652:     if (%form) {
 2653:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 2654:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
 2655:     } else {
 2656:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 2657:     }
 2658: 
 2659:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 2660:     my $response= $ua->request($request);
 2661:     my $content = $response->content;
 2662: 
 2663: 
 2664:     if (wantarray) {
 2665: 	return ($content, $response);
 2666:     } else {
 2667: 	return $content;
 2668:     }
 2669: }
 2670: 
 2671: sub externalssi {
 2672:     my ($url)=@_;
 2673:     my $ua=new LWP::UserAgent;
 2674:     my $request=new HTTP::Request('GET',$url);
 2675:     my $response=$ua->request($request);
 2676:     if (wantarray) {
 2677:         return ($response->content, $response);
 2678:     } else {
 2679:         return $response->content;
 2680:     }
 2681: }
 2682: 
 2683: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 2684: 
 2685: sub allowuploaded {
 2686:     my ($srcurl,$url)=@_;
 2687:     $url=&clutter(&declutter($url));
 2688:     my $dir=$url;
 2689:     $dir=~s/\/[^\/]+$//;
 2690:     my %httpref=();
 2691:     my $httpurl=&hreflocation('',$url);
 2692:     $httpref{'httpref.'.$httpurl}=$srcurl;
 2693:     &Apache::lonnet::appenv(\%httpref);
 2694: }
 2695: 
 2696: #
 2697: # Determine if the current user should be able to edit a particular resource,
 2698: # when viewing in course context.
 2699: # (a) When viewing resource used to determine if "Edit" item is included in 
 2700: #     Functions.
 2701: # (b) When displaying folder contents in course editor, used to determine if
 2702: #     "Edit" link will be displayed alongside resource.
 2703: #
 2704: #  input: six args -- filename (decluttered), course number, course domain,
 2705: #                   url, symb (if registered) and group (if this is a group
 2706: #                   item -- e.g., bulletin board, group page etc.).
 2707: #  output: array of five scalars -- 
 2708: #          $cfile -- url for file editing if editable on current server
 2709: #          $home -- homeserver of resource (i.e., for author if published,
 2710: #                                           or course if uploaded.).
 2711: #          $switchserver --  1 if server switch will be needed.
 2712: #          $forceedit -- 1 if icon/link should be to go to edit mode 
 2713: #          $forceview -- 1 if icon/link should be to go to view mode
 2714: #
 2715: 
 2716: sub can_edit_resource {
 2717:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
 2718:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
 2719: #
 2720: # For aboutme pages user can only edit his/her own.
 2721: #
 2722:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
 2723:         my ($sdom,$sname) = ($1,$2);
 2724:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
 2725:             $home = $env{'user.home'};
 2726:             $cfile = $resurl;
 2727:             if ($env{'form.forceedit'}) {
 2728:                 $forceview = 1;
 2729:             } else {
 2730:                 $forceedit = 1;
 2731:             }
 2732:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
 2733:         } else {
 2734:             return;
 2735:         }
 2736:     }
 2737: 
 2738:     if ($env{'request.course.id'}) {
 2739:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
 2740:         if ($group ne '') {
 2741: # if this is a group homepage or group bulletin board, check group privs
 2742:             my $allowed = 0;
 2743:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
 2744:                 if ((&allowed('mdg',$env{'request.course.id'}.
 2745:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 2746:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 2747:                     $allowed = 1;
 2748:                 }
 2749:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
 2750:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 2751:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 2752:                     $allowed = 1;
 2753:                 }
 2754:             }
 2755:             if ($allowed) {
 2756:                 $home=&homeserver($cnum,$cdom);
 2757:                 if ($env{'form.forceedit'}) {
 2758:                     $forceview = 1;
 2759:                 } else {
 2760:                     $forceedit = 1;
 2761:                 }
 2762:                 $cfile = $resurl;
 2763:             } else {
 2764:                 return;
 2765:             }
 2766:         } else {
 2767:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
 2768:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
 2769:                     return;
 2770:                 }
 2771:             } elsif (!$crsedit) {
 2772: #
 2773: # No edit allowed where CC has switched to student role.
 2774: #
 2775:                 return;
 2776:             }
 2777:         }
 2778:     }
 2779: 
 2780:     if ($file ne '') {
 2781:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
 2782:             if (&is_course_upload($file,$cnum,$cdom)) {
 2783:                 $uploaded = 1;
 2784:                 $incourse = 1;
 2785:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
 2786:                     $cfile = &hreflocation('',$file);
 2787:                     if ($env{'form.forceedit'}) {
 2788:                         $forceview = 1;
 2789:                     } else {
 2790:                         $forceedit = 1;
 2791:                     }
 2792:                 }
 2793:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
 2794:                 $incourse = 1;
 2795:                 if ($env{'form.forceedit'}) {
 2796:                     $forceview = 1;
 2797:                 } else {
 2798:                     $forceedit = 1;
 2799:                 }
 2800:                 $cfile = $resurl;
 2801:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
 2802:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
 2803:                     $incourse = 1;
 2804:                     if ($env{'form.forceedit'}) {
 2805:                         $forceview = 1;
 2806:                     } else {
 2807:                         $forceedit = 1;
 2808:                     }
 2809:                     $cfile = $resurl;
 2810:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
 2811:                     $incourse = 1;
 2812:                     $cfile = $resurl.'/smpedit';
 2813:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
 2814:                     $incourse = 1;
 2815:                     if ($env{'form.forceedit'}) {
 2816:                         $forceview = 1;
 2817:                     } else {
 2818:                         $forceedit = 1;
 2819:                     }
 2820:                     $cfile = $resurl;
 2821:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 2822:                     $incourse = 1;
 2823:                     if ($env{'form.forceedit'}) {
 2824:                         $forceview = 1;
 2825:                     } else {
 2826:                         $forceedit = 1;
 2827:                     }
 2828:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 2829:                 }
 2830:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
 2831:                 my $template = '/res/lib/templates/simpleproblem.problem';
 2832:                 if (&is_on_map($template)) { 
 2833:                     $incourse = 1;
 2834:                     $forceview = 1;
 2835:                     $cfile = $template;
 2836:                 }
 2837:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 2838:                     $incourse = 1;
 2839:                     if ($env{'form.forceedit'}) {
 2840:                         $forceview = 1;
 2841:                     } else {
 2842:                         $forceedit = 1;
 2843:                     }
 2844:                     $cfile = $resurl;
 2845:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
 2846:                 $incourse = 1;
 2847:                 $forceview = 1;
 2848:                 if ($symb) {
 2849:                     my ($map,$id,$res)=&decode_symb($symb);
 2850:                     $env{'request.symb'} = $symb;
 2851:                     $cfile = &clutter($res);
 2852:                 } else {
 2853:                     $cfile = $env{'form.suppurl'};
 2854:                     $cfile =~ s{^http://}{};
 2855:                     $cfile = '/adm/wrapper/ext/'.$cfile;
 2856:                 }
 2857:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 2858:                 if ($env{'form.forceedit'}) {
 2859:                     $forceview = 1;
 2860:                 } else {
 2861:                     $forceedit = 1;
 2862:                 }
 2863:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 2864:             }
 2865:         }
 2866:         if ($uploaded || $incourse) {
 2867:             $home=&homeserver($cnum,$cdom);
 2868:         } elsif ($file !~ m{/$}) {
 2869:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
 2870:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
 2871:             # Check that the user has permission to edit this resource
 2872:             my $setpriv = 1;
 2873:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
 2874:             if (defined($cfudom)) {
 2875:                 $home=&homeserver($cfuname,$cfudom);
 2876:                 $cfile=$file;
 2877:             }
 2878:         }
 2879:         if (($cfile ne '') && (!$incourse || $uploaded) && 
 2880:             (($home ne '') && ($home ne 'no_host'))) {
 2881:             my @ids=&current_machine_ids();
 2882:             unless (grep(/^\Q$home\E$/,@ids)) {
 2883:                 $switchserver=1;
 2884:             }
 2885:         }
 2886:     }
 2887:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
 2888: }
 2889: 
 2890: sub is_course_upload {
 2891:     my ($file,$cnum,$cdom) = @_;
 2892:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
 2893:     $uploadpath =~ s{^\/}{};
 2894:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
 2895:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
 2896:         return 1;
 2897:     }
 2898:     return;
 2899: }
 2900: 
 2901: sub in_course {
 2902:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
 2903:     if ($hideprivileged) {
 2904:         my $skipuser;
 2905:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
 2906:         my @possdoms = ($cdom);  
 2907:         if ($coursehash{'checkforpriv'}) { 
 2908:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
 2909:         }
 2910:         if (&privileged($uname,$udom,\@possdoms)) {
 2911:             $skipuser = 1;
 2912:             if ($coursehash{'nothideprivileged'}) {
 2913:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2914:                     my $user;
 2915:                     if ($item =~ /:/) {
 2916:                         $user = $item;
 2917:                     } else {
 2918:                         $user = join(':',split(/[\@]/,$item));
 2919:                     }
 2920:                     if ($user eq $uname.':'.$udom) {
 2921:                         undef($skipuser);
 2922:                         last;
 2923:                     }
 2924:                 }
 2925:             }
 2926:             if ($skipuser) {
 2927:                 return 0;
 2928:             }
 2929:         }
 2930:     }
 2931:     $type ||= 'any';
 2932:     if (!defined($cdom) || !defined($cnum)) {
 2933:         my $cid  = $env{'request.course.id'};
 2934:         $cdom = $env{'course.'.$cid.'.domain'};
 2935:         $cnum = $env{'course.'.$cid.'.num'};
 2936:     }
 2937:     my $typesref;
 2938:     if (($type eq 'any') || ($type eq 'all')) {
 2939:         $typesref = ['active','previous','future'];
 2940:     } elsif ($type eq 'previous' || $type eq 'future') {
 2941:         $typesref = [$type];
 2942:     }
 2943:     my %roles = &get_my_roles($uname,$udom,'userroles',
 2944:                               $typesref,undef,[$cdom]);
 2945:     my ($tmp) = keys(%roles);
 2946:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
 2947:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
 2948:     if (@course_roles > 0) {
 2949:         return 1;
 2950:     }
 2951:     return 0;
 2952: }
 2953: 
 2954: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 2955: # input: action, courseID, current domain, intended
 2956: #        path to file, source of file, instruction to parse file for objects,
 2957: #        ref to hash for embedded objects,
 2958: #        ref to hash for codebase of java objects.
 2959: #        reference to scalar to accommodate mime type determined
 2960: #          from File::MMagic if $parser = parse.
 2961: #
 2962: # output: url to file (if action was uploaddoc), 
 2963: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 2964: #
 2965: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 2966: # course.
 2967: #
 2968: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2969: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 2970: #          course's home server.
 2971: #
 2972: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 2973: #          be copied from $source (current location) to 
 2974: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2975: #         and will then be copied to
 2976: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 2977: #         course's home server.
 2978: #
 2979: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2980: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 2981: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2982: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 2983: #         in course's home server.
 2984: #
 2985: 
 2986: sub process_coursefile {
 2987:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 2988:         $mimetype)=@_;
 2989:     my $fetchresult;
 2990:     my $home=&homeserver($docuname,$docudom);
 2991:     if ($action eq 'propagate') {
 2992:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2993: 			     $home);
 2994:     } else {
 2995:         my $fpath = '';
 2996:         my $fname = $file;
 2997:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 2998:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 2999:         my $filepath = &build_filepath($fpath);
 3000:         if ($action eq 'copy') {
 3001:             if ($source eq '') {
 3002:                 $fetchresult = 'no source file';
 3003:                 return $fetchresult;
 3004:             } else {
 3005:                 my $destination = $filepath.'/'.$fname;
 3006:                 rename($source,$destination);
 3007:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3008:                                  $home);
 3009:             }
 3010:         } elsif ($action eq 'uploaddoc') {
 3011:             open(my $fh,'>'.$filepath.'/'.$fname);
 3012:             print $fh $env{'form.'.$source};
 3013:             close($fh);
 3014:             if ($parser eq 'parse') {
 3015:                 my $mm = new File::MMagic;
 3016:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 3017:                 if ($type eq 'text/html') {
 3018:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 3019:                     unless ($parse_result eq 'ok') {
 3020:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 3021:                     }
 3022:                 }
 3023:                 if (ref($mimetype)) {
 3024:                     $$mimetype = $type;
 3025:                 } 
 3026:             }
 3027:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3028:                                  $home);
 3029:             if ($fetchresult eq 'ok') {
 3030:                 return '/uploaded/'.$fpath.'/'.$fname;
 3031:             } else {
 3032:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3033:                         ' to host '.$home.': '.$fetchresult);
 3034:                 return '/adm/notfound.html';
 3035:             }
 3036:         }
 3037:     }
 3038:     unless ( $fetchresult eq 'ok') {
 3039:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3040:              ' to host '.$home.': '.$fetchresult);
 3041:     }
 3042:     return $fetchresult;
 3043: }
 3044: 
 3045: sub build_filepath {
 3046:     my ($fpath) = @_;
 3047:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 3048:     unless ($fpath eq '') {
 3049:         my @parts=split('/',$fpath);
 3050:         foreach my $part (@parts) {
 3051:             $filepath.= '/'.$part;
 3052:             if ((-e $filepath)!=1) {
 3053:                 mkdir($filepath,0777);
 3054:             }
 3055:         }
 3056:     }
 3057:     return $filepath;
 3058: }
 3059: 
 3060: sub store_edited_file {
 3061:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 3062:     my $file = $primary_url;
 3063:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 3064:     my $fpath = '';
 3065:     my $fname = $file;
 3066:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3067:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3068:     my $filepath = &build_filepath($fpath);
 3069:     open(my $fh,'>'.$filepath.'/'.$fname);
 3070:     print $fh $content;
 3071:     close($fh);
 3072:     my $home=&homeserver($docuname,$docudom);
 3073:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3074: 			  $home);
 3075:     if ($$fetchresult eq 'ok') {
 3076:         return '/uploaded/'.$fpath.'/'.$fname;
 3077:     } else {
 3078:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3079: 		 ' to host '.$home.': '.$$fetchresult);
 3080:         return '/adm/notfound.html';
 3081:     }
 3082: }
 3083: 
 3084: sub clean_filename {
 3085:     my ($fname,$args)=@_;
 3086: # Replace Windows backslashes by forward slashes
 3087:     $fname=~s/\\/\//g;
 3088:     if (!$args->{'keep_path'}) {
 3089:         # Get rid of everything but the actual filename
 3090: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 3091:     }
 3092: # Replace spaces by underscores
 3093:     $fname=~s/\s+/\_/g;
 3094: # Replace all other weird characters by nothing
 3095:     $fname=~s{[^/\w\.\-]}{}g;
 3096: # Replace all .\d. sequences with _\d. so they no longer look like version
 3097: # numbers
 3098:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 3099:     return $fname;
 3100: }
 3101: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 3102: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 3103: # image with the same aspect ratio as the original, but with dimensions which do 
 3104: # not exceed $resizewidth and $resizeheight.
 3105:  
 3106: sub resizeImage {
 3107:     my ($img_path,$resizewidth,$resizeheight) = @_;
 3108:     my $ima = Image::Magick->new;
 3109:     my $resized;
 3110:     if (-e $img_path) {
 3111:         $ima->Read($img_path);
 3112:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 3113:             my $width = $ima->Get('width');
 3114:             my $height = $ima->Get('height');
 3115:             if ($width > $resizewidth) {
 3116: 	        my $factor = $width/$resizewidth;
 3117:                 my $newheight = $height/$factor;
 3118:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 3119:                 $resized = 1;
 3120:             }
 3121:         }
 3122:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 3123:             my $width = $ima->Get('width');
 3124:             my $height = $ima->Get('height');
 3125:             if ($height > $resizeheight) {
 3126:                 my $factor = $height/$resizeheight;
 3127:                 my $newwidth = $width/$factor;
 3128:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 3129:                 $resized = 1;
 3130:             }
 3131:         }
 3132:         if ($resized) {
 3133:             $ima->Write($img_path);
 3134:         }
 3135:     }
 3136:     return;
 3137: }
 3138: 
 3139: # --------------- Take an uploaded file and put it into the userfiles directory
 3140: # input: $formname - the contents of the file are in $env{"form.$formname"}
 3141: #                    the desired filename is in $env{"form.$formname.filename"}
 3142: #        $context - possible values: coursedoc, existingfile, overwrite, 
 3143: #                                    canceloverwrite, or ''. 
 3144: #                   if 'coursedoc': upload to the current course
 3145: #                   if 'existingfile': write file to tmp/overwrites directory 
 3146: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 3147: #                   $context is passed as argument to &finishuserfileupload
 3148: #        $subdir - directory in userfile to store the file into
 3149: #        $parser - instruction to parse file for objects ($parser = parse)    
 3150: #        $allfiles - reference to hash for embedded objects
 3151: #        $codebase - reference to hash for codebase of java objects
 3152: #        $desuname - username for permanent storage of uploaded file
 3153: #        $dsetudom - domain for permanaent storage of uploaded file
 3154: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 3155: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 3156: #        $resizewidth - width (pixels) to which to resize uploaded image
 3157: #        $resizeheight - height (pixels) to which to resize uploaded image
 3158: #        $mimetype - reference to scalar to accommodate mime type determined
 3159: #                    from File::MMagic.
 3160: # 
 3161: # output: url of file in userspace, or error: <message> 
 3162: #             or /adm/notfound.html if failure to upload occurse
 3163: 
 3164: sub userfileupload {
 3165:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 3166:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 3167:     if (!defined($subdir)) { $subdir='unknown'; }
 3168:     my $fname=$env{'form.'.$formname.'.filename'};
 3169:     $fname=&clean_filename($fname);
 3170:     # See if there is anything left
 3171:     unless ($fname) { return 'error: no uploaded file'; }
 3172:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 3173:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 3174:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 3175:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3176:         my $now = time;
 3177:         my $filepath;
 3178:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 3179:              $filepath = 'tmp/helprequests/'.$now;
 3180:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 3181:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 3182:                          '_'.$env{'user.domain'}.'/pending';
 3183:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3184:             my ($docuname,$docudom);
 3185:             if ($destudom) {
 3186:                 $docudom = $destudom;
 3187:             } else {
 3188:                 $docudom = $env{'user.domain'};
 3189:             }
 3190:             if ($destuname) {
 3191:                 $docuname = $destuname;
 3192:             } else {
 3193:                 $docuname = $env{'user.name'};
 3194:             }
 3195:             if (exists($env{'form.group'})) {
 3196:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3197:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3198:             }
 3199:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 3200:             if ($context eq 'canceloverwrite') {
 3201:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 3202:                 if (-e  $tempfile) {
 3203:                     my @info = stat($tempfile);
 3204:                     if ($info[9] eq $env{'form.timestamp'}) {
 3205:                         unlink($tempfile);
 3206:                     }
 3207:                 }
 3208:                 return;
 3209:             }
 3210:         }
 3211:         # Create the directory if not present
 3212:         my @parts=split(/\//,$filepath);
 3213:         my $fullpath = $perlvar{'lonDaemons'};
 3214:         for (my $i=0;$i<@parts;$i++) {
 3215:             $fullpath .= '/'.$parts[$i];
 3216:             if ((-e $fullpath)!=1) {
 3217:                 mkdir($fullpath,0777);
 3218:             }
 3219:         }
 3220:         open(my $fh,'>'.$fullpath.'/'.$fname);
 3221:         print $fh $env{'form.'.$formname};
 3222:         close($fh);
 3223:         if ($context eq 'existingfile') {
 3224:             my @info = stat($fullpath.'/'.$fname);
 3225:             return ($fullpath.'/'.$fname,$info[9]);
 3226:         } else {
 3227:             return $fullpath.'/'.$fname;
 3228:         }
 3229:     }
 3230:     if ($subdir eq 'scantron') {
 3231:         $fname = 'scantron_orig_'.$fname;
 3232:     } else {
 3233:         $fname="$subdir/$fname";
 3234:     }
 3235:     if ($context eq 'coursedoc') {
 3236: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3237: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3238:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 3239:             return &finishuserfileupload($docuname,$docudom,
 3240: 					 $formname,$fname,$parser,$allfiles,
 3241: 					 $codebase,$thumbwidth,$thumbheight,
 3242:                                          $resizewidth,$resizeheight,$context,$mimetype);
 3243:         } else {
 3244:             if ($env{'form.folder'}) {
 3245:                 $fname=$env{'form.folder'}.'/'.$fname;
 3246:             }
 3247:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 3248: 				       $fname,$formname,$parser,
 3249: 				       $allfiles,$codebase,$mimetype);
 3250:         }
 3251:     } elsif (defined($destuname)) {
 3252:         my $docuname=$destuname;
 3253:         my $docudom=$destudom;
 3254: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3255: 				     $parser,$allfiles,$codebase,
 3256:                                      $thumbwidth,$thumbheight,
 3257:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3258:     } else {
 3259:         my $docuname=$env{'user.name'};
 3260:         my $docudom=$env{'user.domain'};
 3261:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
 3262:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3263:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3264:         }
 3265: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3266: 				     $parser,$allfiles,$codebase,
 3267:                                      $thumbwidth,$thumbheight,
 3268:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3269:     }
 3270: }
 3271: 
 3272: sub finishuserfileupload {
 3273:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 3274:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 3275:     my $path=$docudom.'/'.$docuname.'/';
 3276:     my $filepath=$perlvar{'lonDocRoot'};
 3277:   
 3278:     my ($fnamepath,$file,$fetchthumb);
 3279:     $file=$fname;
 3280:     if ($fname=~m|/|) {
 3281:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 3282: 	$path.=$fnamepath.'/';
 3283:     }
 3284:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 3285:     my $count;
 3286:     for ($count=4;$count<=$#parts;$count++) {
 3287:         $filepath.="/$parts[$count]";
 3288:         if ((-e $filepath)!=1) {
 3289: 	    mkdir($filepath,0777);
 3290:         }
 3291:     }
 3292: 
 3293: # Save the file
 3294:     {
 3295: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 3296: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 3297: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 3298: 	    return '/adm/notfound.html';
 3299: 	}
 3300:         if ($context eq 'overwrite') {
 3301:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 3302:             my $target = $filepath.'/'.$file;
 3303:             if (-e $source) {
 3304:                 my @info = stat($source);
 3305:                 if ($info[9] eq $env{'form.timestamp'}) {   
 3306:                     unless (&File::Copy::move($source,$target)) {
 3307:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 3308:                         return "Moving from $source failed";
 3309:                     }
 3310:                 } else {
 3311:                     return "Temporary file: $source had unexpected date/time for last modification";
 3312:                 }
 3313:             } else {
 3314:                 return "Temporary file: $source missing";
 3315:             }
 3316:         } elsif (!print FH ($env{'form.'.$formname})) {
 3317: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 3318: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 3319: 	    return '/adm/notfound.html';
 3320: 	}
 3321: 	close(FH);
 3322:         if ($resizewidth && $resizeheight) {
 3323:             my $mm = new File::MMagic;
 3324:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 3325:             if ($mime_type =~ m{^image/}) {
 3326: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 3327:             }  
 3328: 	}
 3329:     }
 3330:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 3331:         if (ref($mimetype)) {
 3332:             if ($$mimetype eq '') {
 3333:                 my $mm = new File::MMagic;
 3334:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 3335:                 $$mimetype = $type;
 3336:             }
 3337:         }
 3338:     }
 3339:     if ($parser eq 'parse') {
 3340:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 3341:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 3342:                                                        $allfiles,$codebase);
 3343:             unless ($parse_result eq 'ok') {
 3344:                 &logthis('Failed to parse '.$filepath.$file.
 3345: 	   	         ' for embedded media: '.$parse_result); 
 3346:             }
 3347:         }
 3348:     }
 3349:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 3350:         my $input = $filepath.'/'.$file;
 3351:         my $output = $filepath.'/'.'tn-'.$file;
 3352:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 3353:         system("convert -sample $thumbsize $input $output");
 3354:         if (-e $filepath.'/'.'tn-'.$file) {
 3355:             $fetchthumb  = 1; 
 3356:         }
 3357:     }
 3358:  
 3359: # Notify homeserver to grep it
 3360: #
 3361:     my $docuhome=&homeserver($docuname,$docudom);	
 3362:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 3363:     if ($fetchresult eq 'ok') {
 3364:         if ($fetchthumb) {
 3365:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 3366:             if ($thumbresult ne 'ok') {
 3367:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 3368:                          $docuhome.': '.$thumbresult);
 3369:             }
 3370:         }
 3371: #
 3372: # Return the URL to it
 3373:         return '/uploaded/'.$path.$file;
 3374:     } else {
 3375:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 3376: 		 ': '.$fetchresult);
 3377:         return '/adm/notfound.html';
 3378:     }
 3379: }
 3380: 
 3381: sub extract_embedded_items {
 3382:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 3383:     my @state = ();
 3384:     my (%lastids,%related,%shockwave,%flashvars);
 3385:     my %javafiles = (
 3386:                       codebase => '',
 3387:                       code => '',
 3388:                       archive => ''
 3389:                     );
 3390:     my %mediafiles = (
 3391:                       src => '',
 3392:                       movie => '',
 3393:                      );
 3394:     my $p;
 3395:     if ($content) {
 3396:         $p = HTML::LCParser->new($content);
 3397:     } else {
 3398:         $p = HTML::LCParser->new($fullpath);
 3399:     }
 3400:     while (my $t=$p->get_token()) {
 3401: 	if ($t->[0] eq 'S') {
 3402: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 3403: 	    push(@state, $tagname);
 3404:             if (lc($tagname) eq 'allow') {
 3405:                 &add_filetype($allfiles,$attr->{'src'},'src');
 3406:             }
 3407: 	    if (lc($tagname) eq 'img') {
 3408: 		&add_filetype($allfiles,$attr->{'src'},'src');
 3409: 	    }
 3410: 	    if (lc($tagname) eq 'a') {
 3411:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
 3412:                     &add_filetype($allfiles,$attr->{'href'},'href');
 3413:                 }
 3414: 	    }
 3415:             if (lc($tagname) eq 'script') {
 3416:                 my $src;
 3417:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 3418:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 3419:                 } else {
 3420:                     if ($attr->{'src'} ne '') {
 3421:                         $src = $attr->{'src'};
 3422:                         &add_filetype($allfiles,$src,'src');
 3423:                     }
 3424:                 }
 3425:                 my $text = $p->get_trimmed_text();
 3426:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 3427:                     my @swfargs = split(/,/,$1);
 3428:                     foreach my $item (@swfargs) {
 3429:                         $item =~ s/["']//g;
 3430:                         $item =~ s/^\s+//;
 3431:                         $item =~ s/\s+$//;
 3432:                     }
 3433:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 3434:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 3435:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 3436:                         } else {
 3437:                             $related{$swfargs[0]} = [$swfargs[2]];
 3438:                         }
 3439:                     }
 3440:                 }
 3441:             }
 3442:             if (lc($tagname) eq 'link') {
 3443:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 3444:                     &add_filetype($allfiles,$attr->{'href'},'href');
 3445:                 }
 3446:             }
 3447: 	    if (lc($tagname) eq 'object' ||
 3448: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 3449: 		foreach my $item (keys(%javafiles)) {
 3450: 		    $javafiles{$item} = '';
 3451: 		}
 3452:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 3453:                     $lastids{lc($tagname)} = $attr->{'id'};
 3454:                 }
 3455: 	    }
 3456: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 3457: 		my $name = lc($attr->{'name'});
 3458: 		foreach my $item (keys(%javafiles)) {
 3459: 		    if ($name eq $item) {
 3460: 			$javafiles{$item} = $attr->{'value'};
 3461: 			last;
 3462: 		    }
 3463: 		}
 3464:                 my $pathfrom;
 3465: 		foreach my $item (keys(%mediafiles)) {
 3466: 		    if ($name eq $item) {
 3467:                         $pathfrom = $attr->{'value'};
 3468:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 3469: 			&add_filetype($allfiles,$pathfrom,$name);
 3470: 			last;
 3471: 		    }
 3472: 		}
 3473:                 if ($name eq 'flashvars') {
 3474:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 3475:                 }
 3476:                 if ($pathfrom ne '') {
 3477:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 3478:                                          $pathfrom);
 3479:                 }
 3480: 	    }
 3481: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 3482: 		foreach my $item (keys(%javafiles)) {
 3483: 		    if ($attr->{$item}) {
 3484: 			$javafiles{$item} = $attr->{$item};
 3485: 			last;
 3486: 		    }
 3487: 		}
 3488: 		foreach my $item (keys(%mediafiles)) {
 3489: 		    if ($attr->{$item}) {
 3490: 			&add_filetype($allfiles,$attr->{$item},$item);
 3491: 			last;
 3492: 		    }
 3493: 		}
 3494:                 if (lc($tagname) eq 'embed') {
 3495:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 3496:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 3497:                                              $attr->{'src'});
 3498:                     }
 3499:                 }
 3500: 	    }
 3501:             if ($t->[4] =~ m{/>$}) {
 3502:                 pop(@state);  
 3503:             }
 3504: 	} elsif ($t->[0] eq 'E') {
 3505: 	    my ($tagname) = ($t->[1]);
 3506: 	    if ($javafiles{'codebase'} ne '') {
 3507: 		$javafiles{'codebase'} .= '/';
 3508: 	    }  
 3509: 	    if (lc($tagname) eq 'applet' ||
 3510: 		lc($tagname) eq 'object' ||
 3511: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 3512: 		) {
 3513: 		foreach my $item (keys(%javafiles)) {
 3514: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 3515: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 3516: 			&add_filetype($allfiles,$file,$item);
 3517: 		    }
 3518: 		}
 3519: 	    } 
 3520: 	    pop @state;
 3521: 	}
 3522:     }
 3523:     foreach my $id (sort(keys(%flashvars))) {
 3524:         if ($shockwave{$id} ne '') {
 3525:             my @pairs = split(/\&/,$flashvars{$id});
 3526:             foreach my $pair (@pairs) {
 3527:                 my ($key,$value) = split(/\=/,$pair);
 3528:                 if ($key eq 'thumb') {
 3529:                     &add_filetype($allfiles,$value,$key);
 3530:                 } elsif ($key eq 'content') {
 3531:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 3532:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 3533:                     if ($ext ne '') {
 3534:                         &add_filetype($allfiles,$path.$value,$ext);
 3535:                     }
 3536:                 }
 3537:             }
 3538:         }
 3539:     }
 3540:     return 'ok';
 3541: }
 3542: 
 3543: sub add_filetype {
 3544:     my ($allfiles,$file,$type)=@_;
 3545:     if (exists($allfiles->{$file})) {
 3546: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 3547: 	    push(@{$allfiles->{$file}}, &escape($type));
 3548: 	}
 3549:     } else {
 3550: 	@{$allfiles->{$file}} = (&escape($type));
 3551:     }
 3552: }
 3553: 
 3554: sub embedded_dependency {
 3555:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 3556:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 3557:         if (($identifier ne '') &&
 3558:             (ref($related->{$identifier}) eq 'ARRAY') &&
 3559:             ($pathfrom ne '')) {
 3560:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 3561:             foreach my $dep (@{$related->{$identifier}}) {
 3562:                 &add_filetype($allfiles,$path.$dep,'object');
 3563:             }
 3564:         }
 3565:     }
 3566:     return;
 3567: }
 3568: 
 3569: sub removeuploadedurl {
 3570:     my ($url)=@_;	
 3571:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 3572:     return &removeuserfile($uname,$udom,$fname);
 3573: }
 3574: 
 3575: sub removeuserfile {
 3576:     my ($docuname,$docudom,$fname)=@_;
 3577:     my $home=&homeserver($docuname,$docudom);    
 3578:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 3579:     if ($result eq 'ok') {	
 3580:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 3581:             my $metafile = $fname.'.meta';
 3582:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 3583: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 3584:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 3585:             my $sqlresult = 
 3586:                 &update_portfolio_table($docuname,$docudom,$file,
 3587:                                         'portfolio_metadata',$group,
 3588:                                         'delete');
 3589:         }
 3590:     }
 3591:     return $result;
 3592: }
 3593: 
 3594: sub mkdiruserfile {
 3595:     my ($docuname,$docudom,$dir)=@_;
 3596:     my $home=&homeserver($docuname,$docudom);
 3597:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 3598: }
 3599: 
 3600: sub renameuserfile {
 3601:     my ($docuname,$docudom,$old,$new)=@_;
 3602:     my $home=&homeserver($docuname,$docudom);
 3603:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 3604:                         &escape("$old").':'.&escape("$new"),$home);
 3605:     if ($result eq 'ok') {
 3606:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 3607:             my $oldmeta = $old.'.meta';
 3608:             my $newmeta = $new.'.meta';
 3609:             my $metaresult = 
 3610:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 3611: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 3612:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 3613:             my $sqlresult = 
 3614:                 &update_portfolio_table($docuname,$docudom,$file,
 3615:                                         'portfolio_metadata',$group,
 3616:                                         'delete');
 3617:         }
 3618:     }
 3619:     return $result;
 3620: }
 3621: 
 3622: # ------------------------------------------------------------------------- Log
 3623: 
 3624: sub log {
 3625:     my ($dom,$nam,$hom,$what)=@_;
 3626:     return critical("log:$dom:$nam:$what",$hom);
 3627: }
 3628: 
 3629: # ------------------------------------------------------------------ Course Log
 3630: #
 3631: # This routine flushes several buffers of non-mission-critical nature
 3632: #
 3633: 
 3634: sub flushcourselogs {
 3635:     &logthis('Flushing log buffers');
 3636: #
 3637: # course logs
 3638: # This is a log of all transactions in a course, which can be used
 3639: # for data mining purposes
 3640: #
 3641: # It also collects the courseid database, which lists last transaction
 3642: # times and course titles for all courseids
 3643: #
 3644:     my %courseidbuffer=();
 3645:     foreach my $crsid (keys(%courselogs)) {
 3646:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 3647: 		          &escape($courselogs{$crsid}),
 3648: 		          $coursehombuf{$crsid}) eq 'ok') {
 3649: 	    delete $courselogs{$crsid};
 3650:         } else {
 3651:             &logthis('Failed to flush log buffer for '.$crsid);
 3652:             if (length($courselogs{$crsid})>40000) {
 3653:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 3654:                         " exceeded maximum size, deleting.</font>");
 3655:                delete $courselogs{$crsid};
 3656:             }
 3657:         }
 3658:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 3659:             'description' => $coursedescrbuf{$crsid},
 3660:             'inst_code'    => $courseinstcodebuf{$crsid},
 3661:             'type'        => $coursetypebuf{$crsid},
 3662:             'owner'       => $courseownerbuf{$crsid},
 3663:         };
 3664:     }
 3665: #
 3666: # Write course id database (reverse lookup) to homeserver of courses 
 3667: # Is used in pickcourse
 3668: #
 3669:     foreach my $crs_home (keys(%courseidbuffer)) {
 3670:         my $response = &courseidput(&host_domain($crs_home),
 3671:                                     $courseidbuffer{$crs_home},
 3672:                                     $crs_home,'timeonly');
 3673:     }
 3674: #
 3675: # File accesses
 3676: # Writes to the dynamic metadata of resources to get hit counts, etc.
 3677: #
 3678:     foreach my $entry (keys(%accesshash)) {
 3679:         if ($entry =~ /___count$/) {
 3680:             my ($dom,$name);
 3681:             ($dom,$name,undef)=
 3682: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 3683:             if (! defined($dom) || $dom eq '' || 
 3684:                 ! defined($name) || $name eq '') {
 3685:                 my $cid = $env{'request.course.id'};
 3686:                 $dom  = $env{'request.'.$cid.'.domain'};
 3687:                 $name = $env{'request.'.$cid.'.num'};
 3688:             }
 3689:             my $value = $accesshash{$entry};
 3690:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 3691:             my %temphash=($url => $value);
 3692:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 3693:             if ($result eq 'ok') {
 3694:                 delete $accesshash{$entry};
 3695:             }
 3696:         } else {
 3697:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 3698:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 3699:             my %temphash=($entry => $accesshash{$entry});
 3700:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 3701:                 delete $accesshash{$entry};
 3702:             }
 3703:         }
 3704:     }
 3705: #
 3706: # Roles
 3707: # Reverse lookup of user roles for course faculty/staff and co-authorship
 3708: #
 3709:     foreach my $entry (keys(%userrolehash)) {
 3710:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 3711: 	    split(/\:/,$entry);
 3712:         if (&Apache::lonnet::put('nohist_userroles',
 3713:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 3714:                 $rudom,$runame) eq 'ok') {
 3715: 	    delete $userrolehash{$entry};
 3716:         }
 3717:     }
 3718: #
 3719: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 3720: #
 3721:     my %domrolebuffer = ();
 3722:     foreach my $entry (keys(%domainrolehash)) {
 3723:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 3724:         if ($domrolebuffer{$rudom}) {
 3725:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 3726:                       '='.&escape($domainrolehash{$entry});
 3727:         } else {
 3728:             $domrolebuffer{$rudom}.=&escape($entry).
 3729:                       '='.&escape($domainrolehash{$entry});
 3730:         }
 3731:         delete $domainrolehash{$entry};
 3732:     }
 3733:     foreach my $dom (keys(%domrolebuffer)) {
 3734: 	my %servers = &get_servers($dom,'library');
 3735: 	foreach my $tryserver (keys(%servers)) {
 3736: 	    unless (&reply('domroleput:'.$dom.':'.
 3737: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 3738: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 3739: 	    }
 3740:         }
 3741:     }
 3742:     $dumpcount++;
 3743: }
 3744: 
 3745: sub courselog {
 3746:     my $what=shift;
 3747:     $what=time.':'.$what;
 3748:     unless ($env{'request.course.id'}) { return ''; }
 3749:     $coursedombuf{$env{'request.course.id'}}=
 3750:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 3751:     $coursenumbuf{$env{'request.course.id'}}=
 3752:        $env{'course.'.$env{'request.course.id'}.'.num'};
 3753:     $coursehombuf{$env{'request.course.id'}}=
 3754:        $env{'course.'.$env{'request.course.id'}.'.home'};
 3755:     $coursedescrbuf{$env{'request.course.id'}}=
 3756:        $env{'course.'.$env{'request.course.id'}.'.description'};
 3757:     $courseinstcodebuf{$env{'request.course.id'}}=
 3758:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 3759:     $courseownerbuf{$env{'request.course.id'}}=
 3760:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 3761:     $coursetypebuf{$env{'request.course.id'}}=
 3762:        $env{'course.'.$env{'request.course.id'}.'.type'};
 3763:     if (defined $courselogs{$env{'request.course.id'}}) {
 3764: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 3765:     } else {
 3766: 	$courselogs{$env{'request.course.id'}}.=$what;
 3767:     }
 3768:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 3769: 	&flushcourselogs();
 3770:     }
 3771: }
 3772: 
 3773: sub courseacclog {
 3774:     my $fnsymb=shift;
 3775:     unless ($env{'request.course.id'}) { return ''; }
 3776:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 3777:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 3778:         $what.=':POST';
 3779:         # FIXME: Probably ought to escape things....
 3780: 	foreach my $key (keys(%env)) {
 3781:             if ($key=~/^form\.(.*)/) {
 3782:                 my $formitem = $1;
 3783:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 3784:                     $what.=':'.$formitem.'='.$env{$key};
 3785:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 3786:                     $what.=':'.$formitem.'='.$env{$key};
 3787:                 }
 3788:             }
 3789:         }
 3790:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 3791:         # FIXME: We should not be depending on a form parameter that someone
 3792:         # editing lonsearchcat.pm might change in the future.
 3793:         if ($env{'form.phase'} eq 'course_search') {
 3794:             $what.= ':POST';
 3795:             # FIXME: Probably ought to escape things....
 3796:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 3797:                                  'crsdiscuss') {
 3798:                 $what.=':'.$element.'='.$env{'form.'.$element};
 3799:             }
 3800:         }
 3801:     }
 3802:     &courselog($what);
 3803: }
 3804: 
 3805: sub countacc {
 3806:     my $url=&declutter(shift);
 3807:     return if (! defined($url) || $url eq '');
 3808:     unless ($env{'request.course.id'}) { return ''; }
 3809: #
 3810: # Mark that this url was used in this course
 3811: #
 3812:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 3813: #
 3814: # Increase the access count for this resource in this child process
 3815: #
 3816:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 3817:     $accesshash{$key}++;
 3818: }
 3819: 
 3820: sub linklog {
 3821:     my ($from,$to)=@_;
 3822:     $from=&declutter($from);
 3823:     $to=&declutter($to);
 3824:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 3825:     $accesshash{$to.'___'.$from.'___goto'}=1;
 3826: }
 3827: 
 3828: sub statslog {
 3829:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 3830:     if ($users<2) { return; }
 3831:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 3832:             'course'       => $env{'request.course.id'},
 3833:             'sections'     => '"all"',
 3834:             'num_students' => $users,
 3835:             'part'         => $part,
 3836:             'symb'         => $symb,
 3837:             'mean_tries'   => $av_attempts,
 3838:             'deg_of_diff'  => $degdiff});
 3839:     foreach my $key (keys(%dynstore)) {
 3840:         $accesshash{$key}=$dynstore{$key};
 3841:     }
 3842: }
 3843:   
 3844: sub userrolelog {
 3845:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 3846:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
 3847:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 3848:        $userrolehash
 3849:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 3850:                     =$tend.':'.$tstart;
 3851:     }
 3852:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
 3853:        $userrolehash
 3854:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 3855:                     =$tend.':'.$tstart;
 3856:     }
 3857:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
 3858:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 3859:        $domainrolehash
 3860:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 3861:                     = $tend.':'.$tstart;
 3862:     }
 3863: }
 3864: 
 3865: sub courserolelog {
 3866:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 3867:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 3868:         my $cdom = $1;
 3869:         my $cnum = $2;
 3870:         my $sec = $3;
 3871:         my $namespace = 'rolelog';
 3872:         my %storehash = (
 3873:                            role    => $trole,
 3874:                            start   => $tstart,
 3875:                            end     => $tend,
 3876:                            selfenroll => $selfenroll,
 3877:                            context    => $context,
 3878:                         );
 3879:         if ($trole eq 'gr') {
 3880:             $namespace = 'groupslog';
 3881:             $storehash{'group'} = $sec;
 3882:         } else {
 3883:             $storehash{'section'} = $sec;
 3884:         }
 3885:         &write_log('course',$namespace,\%storehash,$delflag,$username,
 3886:                    $domain,$cnum,$cdom);
 3887:         if (($trole ne 'st') || ($sec ne '')) {
 3888:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 3889:         }
 3890:     }
 3891:     return;
 3892: }
 3893: 
 3894: sub domainrolelog {
 3895:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 3896:     if ($area =~ m{^/($match_domain)/$}) {
 3897:         my $cdom = $1;
 3898:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
 3899:         my $namespace = 'rolelog';
 3900:         my %storehash = (
 3901:                            role    => $trole,
 3902:                            start   => $tstart,
 3903:                            end     => $tend,
 3904:                            context => $context,
 3905:                         );
 3906:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
 3907:                    $domain,$domconfiguser,$cdom);
 3908:     }
 3909:     return;
 3910: 
 3911: }
 3912: 
 3913: sub coauthorrolelog {
 3914:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 3915:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
 3916:         my $audom = $1;
 3917:         my $auname = $2;
 3918:         my $namespace = 'rolelog';
 3919:         my %storehash = (
 3920:                            role    => $trole,
 3921:                            start   => $tstart,
 3922:                            end     => $tend,
 3923:                            context => $context,
 3924:                         );
 3925:         &write_log('author',$namespace,\%storehash,$delflag,$username,
 3926:                    $domain,$auname,$audom);
 3927:     }
 3928:     return;
 3929: }
 3930: 
 3931: sub get_course_adv_roles {
 3932:     my ($cid,$codes) = @_;
 3933:     $cid=$env{'request.course.id'} unless (defined($cid));
 3934:     my %coursehash=&coursedescription($cid);
 3935:     my $crstype = &Apache::loncommon::course_type($cid);
 3936:     my %nothide=();
 3937:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3938:         if ($user !~ /:/) {
 3939: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 3940:         } else {
 3941:             $nothide{$user}=1;
 3942:         }
 3943:     }
 3944:     my @possdoms = ($coursehash{'domain'});
 3945:     if ($coursehash{'checkforpriv'}) {
 3946:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 3947:     }
 3948:     my %returnhash=();
 3949:     my %dumphash=
 3950:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 3951:     my $now=time;
 3952:     my %privileged;
 3953:     foreach my $entry (keys(%dumphash)) {
 3954: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 3955:         if (($tstart) && ($tstart<0)) { next; }
 3956:         if (($tend) && ($tend<$now)) { next; }
 3957:         if (($tstart) && ($now<$tstart)) { next; }
 3958:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 3959: 	if ($username eq '' || $domain eq '') { next; }
 3960:         if ((&privileged($username,$domain,\@possdoms)) &&
 3961:             (!$nothide{$username.':'.$domain})) { next; }
 3962: 	if ($role eq 'cr') { next; }
 3963:         if ($codes) {
 3964:             if ($section) { $role .= ':'.$section; }
 3965:             if ($returnhash{$role}) {
 3966:                 $returnhash{$role}.=','.$username.':'.$domain;
 3967:             } else {
 3968:                 $returnhash{$role}=$username.':'.$domain;
 3969:             }
 3970:         } else {
 3971:             my $key=&plaintext($role,$crstype);
 3972:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 3973:             if ($returnhash{$key}) {
 3974: 	        $returnhash{$key}.=','.$username.':'.$domain;
 3975:             } else {
 3976:                 $returnhash{$key}=$username.':'.$domain;
 3977:             }
 3978:         }
 3979:     }
 3980:     return %returnhash;
 3981: }
 3982: 
 3983: sub get_my_roles {
 3984:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 3985:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 3986:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 3987:     my (%dumphash,%nothide);
 3988:     if ($context eq 'userroles') {
 3989:         %dumphash = &dump('roles',$udom,$uname);
 3990:     } else {
 3991:         %dumphash = &dump('nohist_userroles',$udom,$uname);
 3992:         if ($hidepriv) {
 3993:             my %coursehash=&coursedescription($udom.'_'.$uname);
 3994:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3995:                 if ($user !~ /:/) {
 3996:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 3997:                 } else {
 3998:                     $nothide{$user} = 1;
 3999:                 }
 4000:             }
 4001:         }
 4002:     }
 4003:     my %returnhash=();
 4004:     my $now=time;
 4005:     my %privileged;
 4006:     foreach my $entry (keys(%dumphash)) {
 4007:         my ($role,$tend,$tstart);
 4008:         if ($context eq 'userroles') {
 4009:             next if ($entry =~ /^rolesdef/);
 4010: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 4011:         } else {
 4012:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 4013:         }
 4014:         if (($tstart) && ($tstart<0)) { next; }
 4015:         my $status = 'active';
 4016:         if (($tend) && ($tend<=$now)) {
 4017:             $status = 'previous';
 4018:         } 
 4019:         if (($tstart) && ($now<$tstart)) {
 4020:             $status = 'future';
 4021:         }
 4022:         if (ref($types) eq 'ARRAY') {
 4023:             if (!grep(/^\Q$status\E$/,@{$types})) {
 4024:                 next;
 4025:             } 
 4026:         } else {
 4027:             if ($status ne 'active') {
 4028:                 next;
 4029:             }
 4030:         }
 4031:         my ($rolecode,$username,$domain,$section,$area);
 4032:         if ($context eq 'userroles') {
 4033:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
 4034:             (undef,$domain,$username,$section) = split(/\//,$area);
 4035:         } else {
 4036:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 4037:         }
 4038:         if (ref($roledoms) eq 'ARRAY') {
 4039:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 4040:                 next;
 4041:             }
 4042:         }
 4043:         if (ref($roles) eq 'ARRAY') {
 4044:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 4045:                 if ($role =~ /^cr\//) {
 4046:                     if (!grep(/^cr$/,@{$roles})) {
 4047:                         next;
 4048:                     }
 4049:                 } elsif ($role =~ /^gr\//) {
 4050:                     if (!grep(/^gr$/,@{$roles})) {
 4051:                         next;
 4052:                     }
 4053:                 } else {
 4054:                     next;
 4055:                 }
 4056:             }
 4057:         }
 4058:         if ($hidepriv) {
 4059:             my @privroles = ('dc','su');
 4060:             if ($context eq 'userroles') {
 4061:                 next if (grep(/^\Q$role\E$/,@privroles));
 4062:             } else {
 4063:                 my $possdoms = [$domain];
 4064:                 if (ref($roledoms) eq 'ARRAY') {
 4065:                    push(@{$possdoms},@{$roledoms}); 
 4066:                 }
 4067:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
 4068:                     if (!$nothide{$username.':'.$domain}) {
 4069:                         next;
 4070:                     }
 4071:                 }
 4072:             }
 4073:         }
 4074:         if ($withsec) {
 4075:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 4076:                 $tstart.':'.$tend;
 4077:         } else {
 4078:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 4079:         }
 4080:     }
 4081:     return %returnhash;
 4082: }
 4083: 
 4084: # ----------------------------------------------------- Frontpage Announcements
 4085: #
 4086: #
 4087: 
 4088: sub postannounce {
 4089:     my ($server,$text)=@_;
 4090:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 4091:     unless ($text=~/\w/) { $text=''; }
 4092:     return &reply('setannounce:'.&escape($text),$server);
 4093: }
 4094: 
 4095: sub getannounce {
 4096: 
 4097:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 4098: 	my $announcement='';
 4099: 	while (my $line = <$fh>) { $announcement .= $line; }
 4100: 	close($fh);
 4101: 	if ($announcement=~/\w/) { 
 4102: 	    return 
 4103:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 4104:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 4105: 	} else {
 4106: 	    return '';
 4107: 	}
 4108:     } else {
 4109: 	return '';
 4110:     }
 4111: }
 4112: 
 4113: # ---------------------------------------------------------- Course ID routines
 4114: # Deal with domain's nohist_courseid.db files
 4115: #
 4116: 
 4117: sub courseidput {
 4118:     my ($domain,$storehash,$coursehome,$caller) = @_;
 4119:     return unless (ref($storehash) eq 'HASH');
 4120:     my $outcome;
 4121:     if ($caller eq 'timeonly') {
 4122:         my $cids = '';
 4123:         foreach my $item (keys(%$storehash)) {
 4124:             $cids.=&escape($item).'&';
 4125:         }
 4126:         $cids=~s/\&$//;
 4127:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 4128:                           $coursehome);       
 4129:     } else {
 4130:         my $items = '';
 4131:         foreach my $item (keys(%$storehash)) {
 4132:             $items.= &escape($item).'='.
 4133:                      &freeze_escape($$storehash{$item}).'&';
 4134:         }
 4135:         $items=~s/\&$//;
 4136:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 4137:                           $coursehome);
 4138:     }
 4139:     if ($outcome eq 'unknown_cmd') {
 4140:         my $what;
 4141:         foreach my $cid (keys(%$storehash)) {
 4142:             $what .= &escape($cid).'=';
 4143:             foreach my $item ('description','inst_code','owner','type') {
 4144:                 $what .= &escape($storehash->{$cid}{$item}).':';
 4145:             }
 4146:             $what =~ s/\:$/&/;
 4147:         }
 4148:         $what =~ s/\&$//;  
 4149:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 4150:     } else {
 4151:         return $outcome;
 4152:     }
 4153: }
 4154: 
 4155: sub courseiddump {
 4156:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 4157:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 4158:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 4159:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
 4160:     my $as_hash = 1;
 4161:     my %returnhash;
 4162:     if (!$domfilter) { $domfilter=''; }
 4163:     my %libserv = &all_library();
 4164:     foreach my $tryserver (keys(%libserv)) {
 4165:         if ( (  $hostidflag == 1 
 4166: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 4167: 	     || (!defined($hostidflag)) ) {
 4168: 
 4169: 	    if (($domfilter eq '') ||
 4170: 		(&host_domain($tryserver) eq $domfilter)) {
 4171:                 my $rep;
 4172:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
 4173:                     $rep = LONCAPA::Lond::dump_course_id_handler(
 4174:                         join(":", (&host_domain($tryserver), $sincefilter, 
 4175:                                 &escape($descfilter), &escape($instcodefilter), 
 4176:                                 &escape($ownerfilter), &escape($coursefilter),
 4177:                                 &escape($typefilter), &escape($regexp_ok), 
 4178:                                 $as_hash, &escape($selfenrollonly), 
 4179:                                 &escape($catfilter), $showhidden, $caller, 
 4180:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
 4181:                                 &escape($createdbefore), &escape($createdafter), 
 4182:                                 &escape($creationcontext), $domcloner)));
 4183:                 } else {
 4184:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
 4185:                              $sincefilter.':'.&escape($descfilter).':'.
 4186:                              &escape($instcodefilter).':'.&escape($ownerfilter).
 4187:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
 4188:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
 4189:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
 4190:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
 4191:                              &escape($cc_clone).':'.$cloneonly.':'.
 4192:                              &escape($createdbefore).':'.&escape($createdafter).':'.
 4193:                              &escape($creationcontext).':'.$domcloner,
 4194:                              $tryserver);
 4195:                 }
 4196:                      
 4197:                 my @pairs=split(/\&/,$rep);
 4198:                 foreach my $item (@pairs) {
 4199:                     my ($key,$value)=split(/\=/,$item,2);
 4200:                     $key = &unescape($key);
 4201:                     next if ($key =~ /^error: 2 /);
 4202:                     my $result = &thaw_unescape($value);
 4203:                     if (ref($result) eq 'HASH') {
 4204:                         $returnhash{$key}=$result;
 4205:                     } else {
 4206:                         my @responses = split(/:/,$value);
 4207:                         my @items = ('description','inst_code','owner','type');
 4208:                         for (my $i=0; $i<@responses; $i++) {
 4209:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 4210:                         }
 4211:                     }
 4212:                 }
 4213:             }
 4214:         }
 4215:     }
 4216:     return %returnhash;
 4217: }
 4218: 
 4219: sub courselastaccess {
 4220:     my ($cdom,$cnum,$hostidref) = @_;
 4221:     my %returnhash;
 4222:     if ($cdom && $cnum) {
 4223:         my $chome = &homeserver($cnum,$cdom);
 4224:         if ($chome ne 'no_host') {
 4225:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 4226:             &extract_lastaccess(\%returnhash,$rep);
 4227:         }
 4228:     } else {
 4229:         if (!$cdom) { $cdom=''; }
 4230:         my %libserv = &all_library();
 4231:         foreach my $tryserver (keys(%libserv)) {
 4232:             if (ref($hostidref) eq 'ARRAY') {
 4233:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 4234:             } 
 4235:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 4236:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 4237:                 &extract_lastaccess(\%returnhash,$rep);
 4238:             }
 4239:         }
 4240:     }
 4241:     return %returnhash;
 4242: }
 4243: 
 4244: sub extract_lastaccess {
 4245:     my ($returnhash,$rep) = @_;
 4246:     if (ref($returnhash) eq 'HASH') {
 4247:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 4248:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 4249:                  $rep eq '') {
 4250:             my @pairs=split(/\&/,$rep);
 4251:             foreach my $item (@pairs) {
 4252:                 my ($key,$value)=split(/\=/,$item,2);
 4253:                 $key = &unescape($key);
 4254:                 next if ($key =~ /^error: 2 /);
 4255:                 $returnhash->{$key} = &thaw_unescape($value);
 4256:             }
 4257:         }
 4258:     }
 4259:     return;
 4260: }
 4261: 
 4262: # ---------------------------------------------------------- DC e-mail
 4263: 
 4264: sub dcmailput {
 4265:     my ($domain,$msgid,$message,$server)=@_;
 4266:     my $status = &Apache::lonnet::critical(
 4267:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 4268:        &escape($message),$server);
 4269:     return $status;
 4270: }
 4271: 
 4272: sub dcmaildump {
 4273:     my ($dom,$startdate,$enddate,$senders) = @_;
 4274:     my %returnhash=();
 4275: 
 4276:     if (defined(&domain($dom,'primary'))) {
 4277:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 4278:                                                          &escape($enddate).':';
 4279: 	my @esc_senders=map { &escape($_)} @$senders;
 4280: 	$cmd.=&escape(join('&',@esc_senders));
 4281: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 4282:             my ($key,$value) = split(/\=/,$line,2);
 4283:             if (($key) && ($value)) {
 4284:                 $returnhash{&unescape($key)} = &unescape($value);
 4285:             }
 4286:         }
 4287:     }
 4288:     return %returnhash;
 4289: }
 4290: # ---------------------------------------------------------- Domain roles
 4291: 
 4292: sub get_domain_roles {
 4293:     my ($dom,$roles,$startdate,$enddate)=@_;
 4294:     if ((!defined($startdate)) || ($startdate eq '')) {
 4295:         $startdate = '.';
 4296:     }
 4297:     if ((!defined($enddate)) || ($enddate eq '')) {
 4298:         $enddate = '.';
 4299:     }
 4300:     my $rolelist;
 4301:     if (ref($roles) eq 'ARRAY') {
 4302:         $rolelist = join('&',@{$roles});
 4303:     }
 4304:     my %personnel = ();
 4305: 
 4306:     my %servers = &get_servers($dom,'library');
 4307:     foreach my $tryserver (keys(%servers)) {
 4308: 	%{$personnel{$tryserver}}=();
 4309: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 4310: 					    &escape($startdate).':'.
 4311: 					    &escape($enddate).':'.
 4312: 					    &escape($rolelist), $tryserver))) {
 4313: 	    my ($key,$value) = split(/\=/,$line,2);
 4314: 	    if (($key) && ($value)) {
 4315: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 4316: 	    }
 4317: 	}
 4318:     }
 4319:     return %personnel;
 4320: }
 4321: 
 4322: # ----------------------------------------------------------- Interval timing 
 4323: 
 4324: {
 4325: # Caches needed for speedup of navmaps
 4326: # We don't want to cache this for very long at all (5 seconds at most)
 4327: # 
 4328: # The user for whom we cache
 4329: my $cachedkey='';
 4330: # The cached times for this user
 4331: my %cachedtimes=();
 4332: # When this was last done
 4333: my $cachedtime=();
 4334: 
 4335: sub load_all_first_access {
 4336:     my ($uname,$udom)=@_;
 4337:     if (($cachedkey eq $uname.':'.$udom) &&
 4338:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
 4339:         return;
 4340:     }
 4341:     $cachedtime=time;
 4342:     $cachedkey=$uname.':'.$udom;
 4343:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 4344: }
 4345: 
 4346: sub get_first_access {
 4347:     my ($type,$argsymb,$argmap)=@_;
 4348:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 4349:     if ($argsymb) { $symb=$argsymb; }
 4350:     my ($map,$id,$res)=&decode_symb($symb);
 4351:     if ($argmap) { $map = $argmap; }
 4352:     if ($type eq 'course') {
 4353: 	$res='course';
 4354:     } elsif ($type eq 'map') {
 4355: 	$res=&symbread($map);
 4356:     } else {
 4357: 	$res=$symb;
 4358:     }
 4359:     &load_all_first_access($uname,$udom);
 4360:     return $cachedtimes{"$courseid\0$res"};
 4361: }
 4362: 
 4363: sub set_first_access {
 4364:     my ($type,$interval)=@_;
 4365:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 4366:     my ($map,$id,$res)=&decode_symb($symb);
 4367:     if ($type eq 'course') {
 4368: 	$res='course';
 4369:     } elsif ($type eq 'map') {
 4370: 	$res=&symbread($map);
 4371:     } else {
 4372: 	$res=$symb;
 4373:     }
 4374:     $cachedkey='';
 4375:     my $firstaccess=&get_first_access($type,$symb,$map);
 4376:     if (!$firstaccess) {
 4377:         my $start = time;
 4378: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 4379:                           $udom,$uname);
 4380:         if ($putres eq 'ok') {
 4381:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 4382:                  $udom,$uname); 
 4383:             &appenv(
 4384:                      {
 4385:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 4386:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 4387:                      }
 4388:                   );
 4389:         }
 4390:         return $putres;
 4391:     }
 4392:     return 'already_set';
 4393: }
 4394: }
 4395: # --------------------------------------------- Set Expire Date for Spreadsheet
 4396: 
 4397: sub expirespread {
 4398:     my ($uname,$udom,$stype,$usymb)=@_;
 4399:     my $cid=$env{'request.course.id'}; 
 4400:     if ($cid) {
 4401:        my $now=time;
 4402:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 4403:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 4404:                             $env{'course.'.$cid.'.num'}.
 4405: 	        	    ':nohist_expirationdates:'.
 4406:                             &escape($key).'='.$now,
 4407:                             $env{'course.'.$cid.'.home'})
 4408:     }
 4409:     return 'ok';
 4410: }
 4411: 
 4412: # ----------------------------------------------------- Devalidate Spreadsheets
 4413: 
 4414: sub devalidate {
 4415:     my ($symb,$uname,$udom)=@_;
 4416:     my $cid=$env{'request.course.id'}; 
 4417:     if ($cid) {
 4418:         # delete the stored spreadsheets for
 4419:         # - the student level sheet of this user in course's homespace
 4420:         # - the assessment level sheet for this resource 
 4421:         #   for this user in user's homespace
 4422: 	# - current conditional state info
 4423: 	my $key=$uname.':'.$udom.':';
 4424:         my $status=
 4425: 	    &del('nohist_calculatedsheets',
 4426: 		 [$key.'studentcalc:'],
 4427: 		 $env{'course.'.$cid.'.domain'},
 4428: 		 $env{'course.'.$cid.'.num'})
 4429: 		.' '.
 4430: 	    &del('nohist_calculatedsheets_'.$cid,
 4431: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 4432:         unless ($status eq 'ok ok') {
 4433:            &logthis('Could not devalidate spreadsheet '.
 4434:                     $uname.' at '.$udom.' for '.
 4435: 		    $symb.': '.$status);
 4436:         }
 4437: 	&delenv('user.state.'.$cid);
 4438:     }
 4439: }
 4440: 
 4441: sub get_scalar {
 4442:     my ($string,$end) = @_;
 4443:     my $value;
 4444:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 4445: 	$value = $1;
 4446:     } elsif ($$string =~ s/^([^&]*?)&//) {
 4447: 	$value = $1;
 4448:     }
 4449:     return &unescape($value);
 4450: }
 4451: 
 4452: sub array2str {
 4453:   my (@array) = @_;
 4454:   my $result=&arrayref2str(\@array);
 4455:   $result=~s/^__ARRAY_REF__//;
 4456:   $result=~s/__END_ARRAY_REF__$//;
 4457:   return $result;
 4458: }
 4459: 
 4460: sub arrayref2str {
 4461:   my ($arrayref) = @_;
 4462:   my $result='__ARRAY_REF__';
 4463:   foreach my $elem (@$arrayref) {
 4464:     if(ref($elem) eq 'ARRAY') {
 4465:       $result.=&arrayref2str($elem).'&';
 4466:     } elsif(ref($elem) eq 'HASH') {
 4467:       $result.=&hashref2str($elem).'&';
 4468:     } elsif(ref($elem)) {
 4469:       #print("Got a ref of ".(ref($elem))." skipping.");
 4470:     } else {
 4471:       $result.=&escape($elem).'&';
 4472:     }
 4473:   }
 4474:   $result=~s/\&$//;
 4475:   $result .= '__END_ARRAY_REF__';
 4476:   return $result;
 4477: }
 4478: 
 4479: sub hash2str {
 4480:   my (%hash) = @_;
 4481:   my $result=&hashref2str(\%hash);
 4482:   $result=~s/^__HASH_REF__//;
 4483:   $result=~s/__END_HASH_REF__$//;
 4484:   return $result;
 4485: }
 4486: 
 4487: sub hashref2str {
 4488:   my ($hashref)=@_;
 4489:   my $result='__HASH_REF__';
 4490:   foreach my $key (sort(keys(%$hashref))) {
 4491:     if (ref($key) eq 'ARRAY') {
 4492:       $result.=&arrayref2str($key).'=';
 4493:     } elsif (ref($key) eq 'HASH') {
 4494:       $result.=&hashref2str($key).'=';
 4495:     } elsif (ref($key)) {
 4496:       $result.='=';
 4497:       #print("Got a ref of ".(ref($key))." skipping.");
 4498:     } else {
 4499: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 4500:     }
 4501: 
 4502:     if(ref($hashref->{$key}) eq 'ARRAY') {
 4503:       $result.=&arrayref2str($hashref->{$key}).'&';
 4504:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 4505:       $result.=&hashref2str($hashref->{$key}).'&';
 4506:     } elsif(ref($hashref->{$key})) {
 4507:        $result.='&';
 4508:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 4509:     } else {
 4510:       $result.=&escape($hashref->{$key}).'&';
 4511:     }
 4512:   }
 4513:   $result=~s/\&$//;
 4514:   $result .= '__END_HASH_REF__';
 4515:   return $result;
 4516: }
 4517: 
 4518: sub str2hash {
 4519:     my ($string)=@_;
 4520:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 4521:     return %$hash;
 4522: }
 4523: 
 4524: sub str2hashref {
 4525:   my ($string) = @_;
 4526: 
 4527:   my %hash;
 4528: 
 4529:   if($string !~ /^__HASH_REF__/) {
 4530:       if (! ($string eq '' || !defined($string))) {
 4531: 	  $hash{'error'}='Not hash reference';
 4532:       }
 4533:       return (\%hash, $string);
 4534:   }
 4535: 
 4536:   $string =~ s/^__HASH_REF__//;
 4537: 
 4538:   while($string !~ /^__END_HASH_REF__/) {
 4539:       #key
 4540:       my $key='';
 4541:       if($string =~ /^__HASH_REF__/) {
 4542:           ($key, $string)=&str2hashref($string);
 4543:           if(defined($key->{'error'})) {
 4544:               $hash{'error'}='Bad data';
 4545:               return (\%hash, $string);
 4546:           }
 4547:       } elsif($string =~ /^__ARRAY_REF__/) {
 4548:           ($key, $string)=&str2arrayref($string);
 4549:           if($key->[0] eq 'Array reference error') {
 4550:               $hash{'error'}='Bad data';
 4551:               return (\%hash, $string);
 4552:           }
 4553:       } else {
 4554:           $string =~ s/^(.*?)=//;
 4555: 	  $key=&unescape($1);
 4556:       }
 4557:       $string =~ s/^=//;
 4558: 
 4559:       #value
 4560:       my $value='';
 4561:       if($string =~ /^__HASH_REF__/) {
 4562:           ($value, $string)=&str2hashref($string);
 4563:           if(defined($value->{'error'})) {
 4564:               $hash{'error'}='Bad data';
 4565:               return (\%hash, $string);
 4566:           }
 4567:       } elsif($string =~ /^__ARRAY_REF__/) {
 4568:           ($value, $string)=&str2arrayref($string);
 4569:           if($value->[0] eq 'Array reference error') {
 4570:               $hash{'error'}='Bad data';
 4571:               return (\%hash, $string);
 4572:           }
 4573:       } else {
 4574: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 4575:       }
 4576:       $string =~ s/^&//;
 4577: 
 4578:       $hash{$key}=$value;
 4579:   }
 4580: 
 4581:   $string =~ s/^__END_HASH_REF__//;
 4582: 
 4583:   return (\%hash, $string);
 4584: }
 4585: 
 4586: sub str2array {
 4587:     my ($string)=@_;
 4588:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 4589:     return @$array;
 4590: }
 4591: 
 4592: sub str2arrayref {
 4593:   my ($string) = @_;
 4594:   my @array;
 4595: 
 4596:   if($string !~ /^__ARRAY_REF__/) {
 4597:       if (! ($string eq '' || !defined($string))) {
 4598: 	  $array[0]='Array reference error';
 4599:       }
 4600:       return (\@array, $string);
 4601:   }
 4602: 
 4603:   $string =~ s/^__ARRAY_REF__//;
 4604: 
 4605:   while($string !~ /^__END_ARRAY_REF__/) {
 4606:       my $value='';
 4607:       if($string =~ /^__HASH_REF__/) {
 4608:           ($value, $string)=&str2hashref($string);
 4609:           if(defined($value->{'error'})) {
 4610:               $array[0] ='Array reference error';
 4611:               return (\@array, $string);
 4612:           }
 4613:       } elsif($string =~ /^__ARRAY_REF__/) {
 4614:           ($value, $string)=&str2arrayref($string);
 4615:           if($value->[0] eq 'Array reference error') {
 4616:               $array[0] ='Array reference error';
 4617:               return (\@array, $string);
 4618:           }
 4619:       } else {
 4620: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 4621:       }
 4622:       $string =~ s/^&//;
 4623: 
 4624:       push(@array, $value);
 4625:   }
 4626: 
 4627:   $string =~ s/^__END_ARRAY_REF__//;
 4628: 
 4629:   return (\@array, $string);
 4630: }
 4631: 
 4632: # -------------------------------------------------------------------Temp Store
 4633: 
 4634: sub tmpreset {
 4635:   my ($symb,$namespace,$domain,$stuname) = @_;
 4636:   if (!$symb) {
 4637:     $symb=&symbread();
 4638:     if (!$symb) { $symb= $env{'request.url'}; }
 4639:   }
 4640:   $symb=escape($symb);
 4641: 
 4642:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4643:   $namespace=~s/\//\_/g;
 4644:   $namespace=~s/\W//g;
 4645: 
 4646:   if (!$domain) { $domain=$env{'user.domain'}; }
 4647:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4648:   if ($domain eq 'public' && $stuname eq 'public') {
 4649:       $stuname=$ENV{'REMOTE_ADDR'};
 4650:   }
 4651:   my $path=LONCAPA::tempdir();
 4652:   my %hash;
 4653:   if (tie(%hash,'GDBM_File',
 4654: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4655: 	  &GDBM_WRCREAT(),0640)) {
 4656:     foreach my $key (keys(%hash)) {
 4657:       if ($key=~ /:$symb/) {
 4658: 	delete($hash{$key});
 4659:       }
 4660:     }
 4661:   }
 4662: }
 4663: 
 4664: sub tmpstore {
 4665:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4666: 
 4667:   if (!$symb) {
 4668:     $symb=&symbread();
 4669:     if (!$symb) { $symb= $env{'request.url'}; }
 4670:   }
 4671:   $symb=escape($symb);
 4672: 
 4673:   if (!$namespace) {
 4674:     # I don't think we would ever want to store this for a course.
 4675:     # it seems this will only be used if we don't have a course.
 4676:     #$namespace=$env{'request.course.id'};
 4677:     #if (!$namespace) {
 4678:       $namespace=$env{'request.state'};
 4679:     #}
 4680:   }
 4681:   $namespace=~s/\//\_/g;
 4682:   $namespace=~s/\W//g;
 4683:   if (!$domain) { $domain=$env{'user.domain'}; }
 4684:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4685:   if ($domain eq 'public' && $stuname eq 'public') {
 4686:       $stuname=$ENV{'REMOTE_ADDR'};
 4687:   }
 4688:   my $now=time;
 4689:   my %hash;
 4690:   my $path=LONCAPA::tempdir();
 4691:   if (tie(%hash,'GDBM_File',
 4692: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4693: 	  &GDBM_WRCREAT(),0640)) {
 4694:     $hash{"version:$symb"}++;
 4695:     my $version=$hash{"version:$symb"};
 4696:     my $allkeys=''; 
 4697:     foreach my $key (keys(%$storehash)) {
 4698:       $allkeys.=$key.':';
 4699:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 4700:     }
 4701:     $hash{"$version:$symb:timestamp"}=$now;
 4702:     $allkeys.='timestamp';
 4703:     $hash{"$version:keys:$symb"}=$allkeys;
 4704:     if (untie(%hash)) {
 4705:       return 'ok';
 4706:     } else {
 4707:       return "error:$!";
 4708:     }
 4709:   } else {
 4710:     return "error:$!";
 4711:   }
 4712: }
 4713: 
 4714: # -----------------------------------------------------------------Temp Restore
 4715: 
 4716: sub tmprestore {
 4717:   my ($symb,$namespace,$domain,$stuname) = @_;
 4718: 
 4719:   if (!$symb) {
 4720:     $symb=&symbread();
 4721:     if (!$symb) { $symb= $env{'request.url'}; }
 4722:   }
 4723:   $symb=escape($symb);
 4724: 
 4725:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4726: 
 4727:   if (!$domain) { $domain=$env{'user.domain'}; }
 4728:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4729:   if ($domain eq 'public' && $stuname eq 'public') {
 4730:       $stuname=$ENV{'REMOTE_ADDR'};
 4731:   }
 4732:   my %returnhash;
 4733:   $namespace=~s/\//\_/g;
 4734:   $namespace=~s/\W//g;
 4735:   my %hash;
 4736:   my $path=LONCAPA::tempdir();
 4737:   if (tie(%hash,'GDBM_File',
 4738: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4739: 	  &GDBM_READER(),0640)) {
 4740:     my $version=$hash{"version:$symb"};
 4741:     $returnhash{'version'}=$version;
 4742:     my $scope;
 4743:     for ($scope=1;$scope<=$version;$scope++) {
 4744:       my $vkeys=$hash{"$scope:keys:$symb"};
 4745:       my @keys=split(/:/,$vkeys);
 4746:       my $key;
 4747:       $returnhash{"$scope:keys"}=$vkeys;
 4748:       foreach $key (@keys) {
 4749: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4750: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4751:       }
 4752:     }
 4753:     if (!(untie(%hash))) {
 4754:       return "error:$!";
 4755:     }
 4756:   } else {
 4757:     return "error:$!";
 4758:   }
 4759:   return %returnhash;
 4760: }
 4761: 
 4762: # ----------------------------------------------------------------------- Store
 4763: 
 4764: sub store {
 4765:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4766:     my $home='';
 4767: 
 4768:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4769: 
 4770:     $symb=&symbclean($symb);
 4771:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 4772: 
 4773:     if (!$domain) { $domain=$env{'user.domain'}; }
 4774:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4775: 
 4776:     &devalidate($symb,$stuname,$domain);
 4777: 
 4778:     $symb=escape($symb);
 4779:     if (!$namespace) { 
 4780:        unless ($namespace=$env{'request.course.id'}) { 
 4781:           return ''; 
 4782:        } 
 4783:     }
 4784:     if (!$home) { $home=$env{'user.home'}; }
 4785: 
 4786:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 4787:     $$storehash{'host'}=$perlvar{'lonHostID'};
 4788: 
 4789:     my $namevalue='';
 4790:     foreach my $key (keys(%$storehash)) {
 4791:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4792:     }
 4793:     $namevalue=~s/\&$//;
 4794:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 4795:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 4796: }
 4797: 
 4798: # -------------------------------------------------------------- Critical Store
 4799: 
 4800: sub cstore {
 4801:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4802:     my $home='';
 4803: 
 4804:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4805: 
 4806:     $symb=&symbclean($symb);
 4807:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 4808: 
 4809:     if (!$domain) { $domain=$env{'user.domain'}; }
 4810:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4811: 
 4812:     &devalidate($symb,$stuname,$domain);
 4813: 
 4814:     $symb=escape($symb);
 4815:     if (!$namespace) { 
 4816:        unless ($namespace=$env{'request.course.id'}) { 
 4817:           return ''; 
 4818:        } 
 4819:     }
 4820:     if (!$home) { $home=$env{'user.home'}; }
 4821: 
 4822:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 4823:     $$storehash{'host'}=$perlvar{'lonHostID'};
 4824: 
 4825:     my $namevalue='';
 4826:     foreach my $key (keys(%$storehash)) {
 4827:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4828:     }
 4829:     $namevalue=~s/\&$//;
 4830:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 4831:     return critical
 4832:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 4833: }
 4834: 
 4835: # --------------------------------------------------------------------- Restore
 4836: 
 4837: sub restore {
 4838:     my ($symb,$namespace,$domain,$stuname) = @_;
 4839:     my $home='';
 4840: 
 4841:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4842: 
 4843:     if (!$symb) {
 4844:         return if ($namespace eq 'courserequests');
 4845:         unless ($symb=escape(&symbread())) { return ''; }
 4846:     } else {
 4847:         unless ($namespace eq 'courserequests') {
 4848:             $symb=&escape(&symbclean($symb));
 4849:         }
 4850:     }
 4851:     if (!$namespace) { 
 4852:        unless ($namespace=$env{'request.course.id'}) { 
 4853:           return ''; 
 4854:        } 
 4855:     }
 4856:     if (!$domain) { $domain=$env{'user.domain'}; }
 4857:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4858:     if (!$home) { $home=$env{'user.home'}; }
 4859:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 4860: 
 4861:     my %returnhash=();
 4862:     foreach my $line (split(/\&/,$answer)) {
 4863: 	my ($name,$value)=split(/\=/,$line);
 4864:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 4865:     }
 4866:     my $version;
 4867:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 4868:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 4869:           $returnhash{$item}=$returnhash{$version.':'.$item};
 4870:        }
 4871:     }
 4872:     return %returnhash;
 4873: }
 4874: 
 4875: # ---------------------------------------------------------- Course Description
 4876: #
 4877: #  
 4878: 
 4879: sub coursedescription {
 4880:     my ($courseid,$args)=@_;
 4881:     $courseid=~s/^\///;
 4882:     $courseid=~s/\_/\//g;
 4883:     my ($cdomain,$cnum)=split(/\//,$courseid);
 4884:     my $chome=&homeserver($cnum,$cdomain);
 4885:     my $normalid=$cdomain.'_'.$cnum;
 4886:     # need to always cache even if we get errors otherwise we keep 
 4887:     # trying and trying and trying to get the course description.
 4888:     my %envhash=();
 4889:     my %returnhash=();
 4890:     
 4891:     my $expiretime=600;
 4892:     if ($env{'request.course.id'} eq $normalid) {
 4893: 	$expiretime=120;
 4894:     }
 4895: 
 4896:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 4897:     if (!$args->{'freshen_cache'}
 4898: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 4899: 	foreach my $key (keys(%env)) {
 4900: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 4901: 	    my ($setting) = $1;
 4902: 	    $returnhash{$setting} = $env{$key};
 4903: 	}
 4904: 	return %returnhash;
 4905:     }
 4906: 
 4907:     # get the data again
 4908: 
 4909:     if (!$args->{'one_time'}) {
 4910: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 4911:     }
 4912: 
 4913:     if ($chome ne 'no_host') {
 4914:        %returnhash=&dump('environment',$cdomain,$cnum);
 4915:        if (!exists($returnhash{'con_lost'})) {
 4916: 	   my $username = $env{'user.name'}; # Defult username
 4917: 	   if(defined $args->{'user'}) {
 4918: 	       $username = $args->{'user'};
 4919: 	   }
 4920:            $returnhash{'home'}= $chome;
 4921: 	   $returnhash{'domain'} = $cdomain;
 4922: 	   $returnhash{'num'} = $cnum;
 4923:            if (!defined($returnhash{'type'})) {
 4924:                $returnhash{'type'} = 'Course';
 4925:            }
 4926:            while (my ($name,$value) = each %returnhash) {
 4927:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 4928:            }
 4929:            $returnhash{'url'}=&clutter($returnhash{'url'});
 4930:            $returnhash{'fn'}=LONCAPA::tempdir() .
 4931: 	       $username.'_'.$cdomain.'_'.$cnum;
 4932:            $envhash{'course.'.$normalid.'.home'}=$chome;
 4933:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 4934:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 4935:        }
 4936:     }
 4937:     if (!$args->{'one_time'}) {
 4938: 	&appenv(\%envhash);
 4939:     }
 4940:     return %returnhash;
 4941: }
 4942: 
 4943: sub update_released_required {
 4944:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 4945:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 4946:         $cid = $env{'request.course.id'};
 4947:         $cdom = $env{'course.'.$cid.'.domain'};
 4948:         $cnum = $env{'course.'.$cid.'.num'};
 4949:         $chome = $env{'course.'.$cid.'.home'};
 4950:     }
 4951:     if ($needsrelease) {
 4952:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 4953:         my $needsupdate;
 4954:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 4955:             $needsupdate = 1;
 4956:         } else {
 4957:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 4958:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 4959:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 4960:                 $needsupdate = 1;
 4961:             }
 4962:         }
 4963:         if ($needsupdate) {
 4964:             my %needshash = (
 4965:                              'internal.releaserequired' => $needsrelease,
 4966:                             );
 4967:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 4968:             if ($putresult eq 'ok') {
 4969:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 4970:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 4971:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 4972:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 4973:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 4974:                 }
 4975:             }
 4976:         }
 4977:     }
 4978:     return;
 4979: }
 4980: 
 4981: # -------------------------------------------------See if a user is privileged
 4982: 
 4983: sub privileged {
 4984:     my ($username,$domain,$possdomains,$possroles)=@_;
 4985:     my $now = time;
 4986:     my $roles;
 4987:     if (ref($possroles) eq 'ARRAY') {
 4988:         $roles = $possroles; 
 4989:     } else {
 4990:         $roles = ['dc','su'];
 4991:     }
 4992:     if (ref($possdomains) eq 'ARRAY') {
 4993:         my %privileged = &privileged_by_domain($possdomains,$roles);
 4994:         foreach my $dom (@{$possdomains}) {
 4995:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
 4996:                 (ref($privileged{$dom}) eq 'HASH')) {
 4997:                 foreach my $role (@{$roles}) {
 4998:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 4999:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
 5000:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
 5001:                             return 1 unless (($end && $end < $now) ||
 5002:                                              ($start && $start > $now));
 5003:                         }
 5004:                     }
 5005:                 }
 5006:             }
 5007:         }
 5008:     } else {
 5009:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
 5010:         my $now = time;
 5011: 
 5012:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
 5013:             my ($trole, $tend, $tstart) = split(/_/, $role);
 5014:             if (grep(/^\Q$trole\E$/,@{$roles})) {
 5015:                 return 1 unless ($tend && $tend < $now) 
 5016:                         or ($tstart && $tstart > $now);
 5017:             }
 5018:         }
 5019:     }
 5020:     return 0;
 5021: }
 5022: 
 5023: sub privileged_by_domain {
 5024:     my ($domains,$roles) = @_;
 5025:     my %privileged = ();
 5026:     my $cachetime = 60*60*24;
 5027:     my $now = time;
 5028:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
 5029:         return %privileged;
 5030:     }
 5031:     foreach my $dom (@{$domains}) {
 5032:         next if (ref($privileged{$dom}) eq 'HASH');
 5033:         my $needroles;
 5034:         foreach my $role (@{$roles}) {
 5035:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
 5036:             if (defined($cached)) {
 5037:                 if (ref($result) eq 'HASH') {
 5038:                     $privileged{$dom}{$role} = $result;
 5039:                 }
 5040:             } else {
 5041:                 $needroles = 1;
 5042:             }
 5043:         }
 5044:         if ($needroles) {
 5045:             my %dompersonnel = &get_domain_roles($dom,$roles);
 5046:             $privileged{$dom} = {};
 5047:             foreach my $server (keys(%dompersonnel)) {
 5048:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 5049:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
 5050:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
 5051:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
 5052:                         next if ($end && $end < $now);
 5053:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
 5054:                             $dompersonnel{$server}{$item};
 5055:                     }
 5056:                 }
 5057:             }
 5058:             if (ref($privileged{$dom}) eq 'HASH') {
 5059:                 foreach my $role (@{$roles}) {
 5060:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 5061:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
 5062:                     } else {
 5063:                         my %hash = ();
 5064:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
 5065:                     }
 5066:                 }
 5067:             }
 5068:         }
 5069:     }
 5070:     return %privileged;
 5071: }
 5072: 
 5073: # -------------------------------------------------------- Get user privileges
 5074: 
 5075: sub rolesinit {
 5076:     my ($domain, $username) = @_;
 5077:     my %userroles = ('user.login.time' => time);
 5078:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 5079: 
 5080:     # firstaccess and timerinterval are related to timed maps/resources. 
 5081:     # also, blocking can be triggered by an activating timer
 5082:     # it's saved in the user's %env.
 5083:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 5084:     my %timerinterval = &dump('timerinterval', $domain, $username);
 5085:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 5086:         %timerintchk, %timerintenv);
 5087: 
 5088:     foreach my $key (keys(%firstaccess)) {
 5089:         my ($cid, $rest) = split(/\0/, $key);
 5090:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 5091:     }
 5092: 
 5093:     foreach my $key (keys(%timerinterval)) {
 5094:         my ($cid,$rest) = split(/\0/,$key);
 5095:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 5096:     }
 5097: 
 5098:     my %allroles=();
 5099:     my %allgroups=();
 5100: 
 5101:     for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
 5102:         my $role = $rolesdump{$area};
 5103:         $area =~ s/\_\w\w$//;
 5104: 
 5105:         my ($trole, $tend, $tstart, $group_privs);
 5106: 
 5107:         if ($role =~ /^cr/) {
 5108:         # Custom role, defined by a user 
 5109:         # e.g., user.role.cr/msu/smith/mynewrole
 5110:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 5111:                 $trole = $1;
 5112:                 ($tend, $tstart) = split('_', $2);
 5113:             } else {
 5114:                 $trole = $role;
 5115:             }
 5116:         } elsif ($role =~ m|^gr/|) {
 5117:         # Role of member in a group, defined within a course/community
 5118:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 5119:             ($trole, $tend, $tstart) = split(/_/, $role);
 5120:             next if $tstart eq '-1';
 5121:             ($trole, $group_privs) = split(/\//, $trole);
 5122:             $group_privs = &unescape($group_privs);
 5123:         } else {
 5124:         # Just a normal role, defined in roles.tab
 5125:             ($trole, $tend, $tstart) = split(/_/,$role);
 5126:         }
 5127: 
 5128:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 5129:                  $username);
 5130:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 5131: 
 5132:         # role expired or not available yet?
 5133:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 5134:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 5135: 
 5136:         next if $area eq '' or $trole eq '';
 5137: 
 5138:         my $spec = "$trole.$area";
 5139:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 5140: 
 5141:         if ($trole =~ /^cr\//) {
 5142:         # Custom role, defined by a user
 5143:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 5144:         } elsif ($trole eq 'gr') {
 5145:         # Role of a member in a group, defined within a course/community
 5146:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 5147:             next;
 5148:         } else {
 5149:         # Normal role, defined in roles.tab
 5150:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 5151:         }
 5152: 
 5153:         my $cid = $tdomain.'_'.$trest;
 5154:         unless ($firstaccchk{$cid}) {
 5155:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 5156:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 5157:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 5158:                         $coursetimerstarts{$cid}{$item}; 
 5159:                 }
 5160:             }
 5161:             $firstaccchk{$cid} = 1;
 5162:         }
 5163:         unless ($timerintchk{$cid}) {
 5164:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 5165:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 5166:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 5167:                        $coursetimerintervals{$cid}{$item};
 5168:                 }
 5169:             }
 5170:             $timerintchk{$cid} = 1;
 5171:         }
 5172:     }
 5173: 
 5174:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
 5175:         \%allroles, \%allgroups);
 5176:     $env{'user.adv'} = $userroles{'user.adv'};
 5177: 
 5178:     return (\%userroles,\%firstaccenv,\%timerintenv);
 5179: }
 5180: 
 5181: sub set_arearole {
 5182:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
 5183:     unless ($nolog) {
 5184: # log the associated role with the area
 5185:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 5186:     }
 5187:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 5188: }
 5189: 
 5190: sub custom_roleprivs {
 5191:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 5192:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 5193:     my $homsvr=homeserver($rauthor,$rdomain);
 5194:     if (&hostname($homsvr) ne '') {
 5195:         my ($rdummy,$roledef)=
 5196:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 5197:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 5198:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 5199:             if (defined($syspriv)) {
 5200:                 if ($trest =~ /^$match_community$/) {
 5201:                     $syspriv =~ s/bre\&S//; 
 5202:                 }
 5203:                 $$allroles{'cm./'}.=':'.$syspriv;
 5204:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 5205:             }
 5206:             if ($tdomain ne '') {
 5207:                 if (defined($dompriv)) {
 5208:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 5209:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 5210:                 }
 5211:                 if (($trest ne '') && (defined($coursepriv))) {
 5212:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 5213:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 5214:                 }
 5215:             }
 5216:         }
 5217:     }
 5218: }
 5219: 
 5220: sub group_roleprivs {
 5221:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 5222:     my $access = 1;
 5223:     my $now = time;
 5224:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 5225:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 5226:     if ($access) {
 5227:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 5228:         $$allgroups{$course}{$group} .=':'.$group_privs;
 5229:     }
 5230: }
 5231: 
 5232: sub standard_roleprivs {
 5233:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 5234:     if (defined($pr{$trole.':s'})) {
 5235:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 5236:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 5237:     }
 5238:     if ($tdomain ne '') {
 5239:         if (defined($pr{$trole.':d'})) {
 5240:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 5241:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 5242:         }
 5243:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 5244:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 5245:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 5246:         }
 5247:     }
 5248: }
 5249: 
 5250: sub set_userprivs {
 5251:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 5252:     my $author=0;
 5253:     my $adv=0;
 5254:     my %grouproles = ();
 5255:     if (keys(%{$allgroups}) > 0) {
 5256:         my @groupkeys; 
 5257:         foreach my $role (keys(%{$allroles})) {
 5258:             push(@groupkeys,$role);
 5259:         }
 5260:         if (ref($groups_roles) eq 'HASH') {
 5261:             foreach my $key (keys(%{$groups_roles})) {
 5262:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 5263:                     push(@groupkeys,$key);
 5264:                 }
 5265:             }
 5266:         }
 5267:         if (@groupkeys > 0) {
 5268:             foreach my $role (@groupkeys) {
 5269:                 my ($trole,$area,$sec,$extendedarea);
 5270:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 5271:                     $trole = $1;
 5272:                     $area = $2;
 5273:                     $sec = $3;
 5274:                     $extendedarea = $area.$sec;
 5275:                     if (exists($$allgroups{$area})) {
 5276:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 5277:                             my $spec = $trole.'.'.$extendedarea;
 5278:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 5279:                                                 $$allgroups{$area}{$group};
 5280:                         }
 5281:                     }
 5282:                 }
 5283:             }
 5284:         }
 5285:     }
 5286:     foreach my $group (keys(%grouproles)) {
 5287:         $$allroles{$group} = $grouproles{$group};
 5288:     }
 5289:     foreach my $role (keys(%{$allroles})) {
 5290:         my %thesepriv;
 5291:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 5292:         foreach my $item (split(/:/,$$allroles{$role})) {
 5293:             if ($item ne '') {
 5294:                 my ($privilege,$restrictions)=split(/&/,$item);
 5295:                 if ($restrictions eq '') {
 5296:                     $thesepriv{$privilege}='F';
 5297:                 } elsif ($thesepriv{$privilege} ne 'F') {
 5298:                     $thesepriv{$privilege}.=$restrictions;
 5299:                 }
 5300:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 5301:             }
 5302:         }
 5303:         my $thesestr='';
 5304:         foreach my $priv (sort(keys(%thesepriv))) {
 5305: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 5306: 	}
 5307:         $userroles->{'user.priv.'.$role} = $thesestr;
 5308:     }
 5309:     return ($author,$adv);
 5310: }
 5311: 
 5312: sub role_status {
 5313:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 5314:     my @pwhere = ();
 5315:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 5316:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
 5317:         unless (!defined($$role) || $$role eq '') {
 5318:             $$where=join('.',@pwhere);
 5319:             $$trolecode=$$role.'.'.$$where;
 5320:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 5321:             $$tstatus='is';
 5322:             if ($$tstart && $$tstart>$update) {
 5323:                 $$tstatus='future';
 5324:                 if ($$tstart<$now) {
 5325:                     if ($$tstart && $$tstart>$refresh) {
 5326:                         if (($$where ne '') && ($$role ne '')) {
 5327:                             my (%allroles,%allgroups,$group_privs,
 5328:                                 %groups_roles,@rolecodes);
 5329:                             my %userroles = (
 5330:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 5331:                             );
 5332:                             @rolecodes = ('cm'); 
 5333:                             my $spec=$$role.'.'.$$where;
 5334:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 5335:                             if ($$role =~ /^cr\//) {
 5336:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 5337:                                 push(@rolecodes,'cr');
 5338:                             } elsif ($$role eq 'gr') {
 5339:                                 push(@rolecodes,$$role);
 5340:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 5341:                                                     $env{'user.name'});
 5342:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 5343:                                 (undef,my $group_privs) = split(/\//,$trole);
 5344:                                 $group_privs = &unescape($group_privs);
 5345:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 5346:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 5347:                                 &get_groups_roles($tdomain,$trest,
 5348:                                                   \%course_roles,\@rolecodes,
 5349:                                                   \%groups_roles);
 5350:                             } else {
 5351:                                 push(@rolecodes,$$role);
 5352:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 5353:                             }
 5354:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
 5355:                             &appenv(\%userroles,\@rolecodes);
 5356:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 5357:                         }
 5358:                     }
 5359:                     $$tstatus = 'is';
 5360:                 }
 5361:             }
 5362:             if ($$tend) {
 5363:                 if ($$tend<$update) {
 5364:                     $$tstatus='expired';
 5365:                 } elsif ($$tend<$now) {
 5366:                     $$tstatus='will_not';
 5367:                 }
 5368:             }
 5369:         }
 5370:     }
 5371: }
 5372: 
 5373: sub get_groups_roles {
 5374:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 5375:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 5376:                   (ref($rolecodes) eq 'ARRAY') && 
 5377:                   (ref($groups_roles) eq 'HASH')); 
 5378:     if (keys(%{$cdom_courseroles}) > 0) {
 5379:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 5380:         if ($cdom ne '' && $cnum ne '') {
 5381:             foreach my $key (keys(%{$cdom_courseroles})) {
 5382:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 5383:                     my $crsrole = $1;
 5384:                     my $crssec = $2;
 5385:                     if ($crsrole =~ /^cr/) {
 5386:                         unless (grep(/^cr$/,@{$rolecodes})) {
 5387:                             push(@{$rolecodes},'cr');
 5388:                         }
 5389:                     } else {
 5390:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 5391:                             push(@{$rolecodes},$crsrole);
 5392:                         }
 5393:                     }
 5394:                     my $rolekey = "$crsrole./$cdom/$cnum";
 5395:                     if ($crssec ne '') {
 5396:                         $rolekey .= "/$crssec";
 5397:                     }
 5398:                     $rolekey .= './';
 5399:                     $groups_roles->{$rolekey} = $rolecodes;
 5400:                 }
 5401:             }
 5402:         }
 5403:     }
 5404:     return;
 5405: }
 5406: 
 5407: sub delete_env_groupprivs {
 5408:     my ($where,$courseroles,$possroles) = @_;
 5409:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 5410:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 5411:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 5412:         %{$courseroles->{$udom}} =
 5413:             &get_my_roles('','','userroles',['active'],
 5414:                           $possroles,[$udom],1);
 5415:     }
 5416:     if (ref($courseroles->{$udom}) eq 'HASH') {
 5417:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 5418:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 5419:             my $area = '/'.$cdom.'/'.$cnum;
 5420:             my $privkey = "user.priv.$crsrole.$area";
 5421:             if ($crssec ne '') {
 5422:                 $privkey .= '/'.$crssec;
 5423:             }
 5424:             $privkey .= ".$area/$group";
 5425:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 5426:         }
 5427:     }
 5428:     return;
 5429: }
 5430: 
 5431: sub check_adhoc_privs {
 5432:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
 5433:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 5434:     my $setprivs;
 5435:     if ($env{$cckey}) {
 5436:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 5437:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 5438:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 5439:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 5440:             $setprivs = 1;
 5441:         }
 5442:     } else {
 5443:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 5444:         $setprivs = 1;
 5445:     }
 5446:     return $setprivs;
 5447: }
 5448: 
 5449: sub set_adhoc_privileges {
 5450: # role can be cc or ca
 5451:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
 5452:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 5453:     my $spec = $role.'.'.$area;
 5454:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 5455:                                   $env{'user.name'},1);
 5456:     my %ccrole = ();
 5457:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
 5458:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
 5459:     &appenv(\%userroles,[$role,'cm']);
 5460:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 5461:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
 5462:         &appenv( {'request.role'        => $spec,
 5463:                   'request.role.domain' => $dcdom,
 5464:                   'request.course.sec'  => ''
 5465:                  }
 5466:                );
 5467:         my $tadv=0;
 5468:         if (&allowed('adv') eq 'F') { $tadv=1; }
 5469:         &appenv({'request.role.adv'    => $tadv});
 5470:     }
 5471: }
 5472: 
 5473: # --------------------------------------------------------------- get interface
 5474: 
 5475: sub get {
 5476:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5477:    my $items='';
 5478:    foreach my $item (@$storearr) {
 5479:        $items.=&escape($item).'&';
 5480:    }
 5481:    $items=~s/\&$//;
 5482:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5483:    if (!$uname) { $uname=$env{'user.name'}; }
 5484:    my $uhome=&homeserver($uname,$udomain);
 5485: 
 5486:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 5487:    my @pairs=split(/\&/,$rep);
 5488:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 5489:      return @pairs;
 5490:    }
 5491:    my %returnhash=();
 5492:    my $i=0;
 5493:    foreach my $item (@$storearr) {
 5494:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 5495:       $i++;
 5496:    }
 5497:    return %returnhash;
 5498: }
 5499: 
 5500: # --------------------------------------------------------------- del interface
 5501: 
 5502: sub del {
 5503:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5504:    my $items='';
 5505:    foreach my $item (@$storearr) {
 5506:        $items.=&escape($item).'&';
 5507:    }
 5508: 
 5509:    $items=~s/\&$//;
 5510:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5511:    if (!$uname) { $uname=$env{'user.name'}; }
 5512:    my $uhome=&homeserver($uname,$udomain);
 5513:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 5514: }
 5515: 
 5516: # -------------------------------------------------------------- dump interface
 5517: 
 5518: sub unserialize {
 5519:     my ($rep, $escapedkeys) = @_;
 5520: 
 5521:     return {} if $rep =~ /^error/;
 5522: 
 5523:     my %returnhash=();
 5524: 	foreach my $item (split /\&/, $rep) {
 5525: 	    my ($key, $value) = split(/=/, $item, 2);
 5526: 	    $key = unescape($key) unless $escapedkeys;
 5527: 	    next if $key =~ /^error: 2 /;
 5528: 	    $returnhash{$key} = Apache::lonnet::thaw_unescape($value);
 5529: 	}
 5530:     #return %returnhash;
 5531:     return \%returnhash;
 5532: }        
 5533: 
 5534: # see Lond::dump_with_regexp
 5535: # if $escapedkeys hash keys won't get unescaped.
 5536: sub dump {
 5537:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
 5538:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5539:     if (!$uname) { $uname=$env{'user.name'}; }
 5540:     my $uhome=&homeserver($uname,$udomain);
 5541: 
 5542:     my $reply;
 5543:     if (grep { $_ eq $uhome } current_machine_ids()) {
 5544:         # user is hosted on this machine
 5545:         $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
 5546:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
 5547:         return %{unserialize($reply, $escapedkeys)};
 5548:     }
 5549:     if ($regexp) {
 5550: 	$regexp=&escape($regexp);
 5551:     } else {
 5552: 	$regexp='.';
 5553:     }
 5554:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 5555:     my @pairs=split(/\&/,$rep);
 5556:     my %returnhash=();
 5557:     if (!($rep =~ /^error/ )) {
 5558: 	foreach my $item (@pairs) {
 5559: 	    my ($key,$value)=split(/=/,$item,2);
 5560:         $key = unescape($key) unless $escapedkeys;
 5561:         #$key = &unescape($key);
 5562: 	    next if ($key =~ /^error: 2 /);
 5563: 	    $returnhash{$key}=&thaw_unescape($value);
 5564: 	}
 5565:     }
 5566:     return %returnhash;
 5567: }
 5568: 
 5569: 
 5570: # --------------------------------------------------------- dumpstore interface
 5571: 
 5572: sub dumpstore {
 5573:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 5574:    # same as dump but keys must be escaped. They may contain colon separated
 5575:    # lists of values that may themself contain colons (e.g. symbs).
 5576:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
 5577: }
 5578: 
 5579: # -------------------------------------------------------------- keys interface
 5580: 
 5581: sub getkeys {
 5582:    my ($namespace,$udomain,$uname)=@_;
 5583:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5584:    if (!$uname) { $uname=$env{'user.name'}; }
 5585:    my $uhome=&homeserver($uname,$udomain);
 5586:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 5587:    my @keyarray=();
 5588:    foreach my $key (split(/\&/,$rep)) {
 5589:       next if ($key =~ /^error: 2 /);
 5590:       push(@keyarray,&unescape($key));
 5591:    }
 5592:    return @keyarray;
 5593: }
 5594: 
 5595: # --------------------------------------------------------------- currentdump
 5596: sub currentdump {
 5597:    my ($courseid,$sdom,$sname)=@_;
 5598:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 5599:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 5600:    $sname    = $env{'user.name'}         if (! defined($sname));
 5601:    my $uhome = &homeserver($sname,$sdom);
 5602:    my $rep;
 5603: 
 5604:    if (grep { $_ eq $uhome } current_machine_ids()) {
 5605:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
 5606:                    $courseid)));
 5607:    } else {
 5608:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 5609:    }
 5610: 
 5611:    return if ($rep =~ /^(error:|no_such_host)/);
 5612:    #
 5613:    my %returnhash=();
 5614:    #
 5615:    if ($rep eq "unknown_cmd") { 
 5616:        # an old lond will not know currentdump
 5617:        # Do a dump and make it look like a currentdump
 5618:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 5619:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 5620:        my %hash = @tmp;
 5621:        @tmp=();
 5622:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 5623:    } else {
 5624:        my @pairs=split(/\&/,$rep);
 5625:        foreach my $pair (@pairs) {
 5626:            my ($key,$value)=split(/=/,$pair,2);
 5627:            my ($symb,$param) = split(/:/,$key);
 5628:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 5629:                                                         &thaw_unescape($value);
 5630:        }
 5631:    }
 5632:    return %returnhash;
 5633: }
 5634: 
 5635: sub convert_dump_to_currentdump{
 5636:     my %hash = %{shift()};
 5637:     my %returnhash;
 5638:     # Code ripped from lond, essentially.  The only difference
 5639:     # here is the unescaping done by lonnet::dump().  Conceivably
 5640:     # we might run in to problems with parameter names =~ /^v\./
 5641:     while (my ($key,$value) = each(%hash)) {
 5642:         my ($v,$symb,$param) = split(/:/,$key);
 5643: 	$symb  = &unescape($symb);
 5644: 	$param = &unescape($param);
 5645:         next if ($v eq 'version' || $symb eq 'keys');
 5646:         next if (exists($returnhash{$symb}) &&
 5647:                  exists($returnhash{$symb}->{$param}) &&
 5648:                  $returnhash{$symb}->{'v.'.$param} > $v);
 5649:         $returnhash{$symb}->{$param}=$value;
 5650:         $returnhash{$symb}->{'v.'.$param}=$v;
 5651:     }
 5652:     #
 5653:     # Remove all of the keys in the hashes which keep track of
 5654:     # the version of the parameter.
 5655:     while (my ($symb,$param_hash) = each(%returnhash)) {
 5656:         # use a foreach because we are going to delete from the hash.
 5657:         foreach my $key (keys(%$param_hash)) {
 5658:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 5659:         }
 5660:     }
 5661:     return \%returnhash;
 5662: }
 5663: 
 5664: # ------------------------------------------------------ critical inc interface
 5665: 
 5666: sub cinc {
 5667:     return &inc(@_,'critical');
 5668: }
 5669: 
 5670: # --------------------------------------------------------------- inc interface
 5671: 
 5672: sub inc {
 5673:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 5674:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5675:     if (!$uname) { $uname=$env{'user.name'}; }
 5676:     my $uhome=&homeserver($uname,$udomain);
 5677:     my $items='';
 5678:     if (! ref($store)) {
 5679:         # got a single value, so use that instead
 5680:         $items = &escape($store).'=&';
 5681:     } elsif (ref($store) eq 'SCALAR') {
 5682:         $items = &escape($$store).'=&';        
 5683:     } elsif (ref($store) eq 'ARRAY') {
 5684:         $items = join('=&',map {&escape($_);} @{$store});
 5685:     } elsif (ref($store) eq 'HASH') {
 5686:         while (my($key,$value) = each(%{$store})) {
 5687:             $items.= &escape($key).'='.&escape($value).'&';
 5688:         }
 5689:     }
 5690:     $items=~s/\&$//;
 5691:     if ($critical) {
 5692: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 5693:     } else {
 5694: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 5695:     }
 5696: }
 5697: 
 5698: # --------------------------------------------------------------- put interface
 5699: 
 5700: sub put {
 5701:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5702:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5703:    if (!$uname) { $uname=$env{'user.name'}; }
 5704:    my $uhome=&homeserver($uname,$udomain);
 5705:    my $items='';
 5706:    foreach my $item (keys(%$storehash)) {
 5707:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5708:    }
 5709:    $items=~s/\&$//;
 5710:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5711: }
 5712: 
 5713: # ------------------------------------------------------------ newput interface
 5714: 
 5715: sub newput {
 5716:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5717:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5718:    if (!$uname) { $uname=$env{'user.name'}; }
 5719:    my $uhome=&homeserver($uname,$udomain);
 5720:    my $items='';
 5721:    foreach my $key (keys(%$storehash)) {
 5722:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 5723:    }
 5724:    $items=~s/\&$//;
 5725:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 5726: }
 5727: 
 5728: # ---------------------------------------------------------  putstore interface
 5729: 
 5730: sub putstore {
 5731:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 5732:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5733:    if (!$uname) { $uname=$env{'user.name'}; }
 5734:    my $uhome=&homeserver($uname,$udomain);
 5735:    my $items='';
 5736:    foreach my $key (keys(%$storehash)) {
 5737:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 5738:    }
 5739:    $items=~s/\&$//;
 5740:    my $esc_symb=&escape($symb);
 5741:    my $esc_v=&escape($version);
 5742:    my $reply =
 5743:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 5744: 	      $uhome);
 5745:    if ($reply eq 'unknown_cmd') {
 5746:        # gfall back to way things use to be done
 5747:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 5748: 			    $uname);
 5749:    }
 5750:    return $reply;
 5751: }
 5752: 
 5753: sub old_putstore {
 5754:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 5755:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5756:     if (!$uname) { $uname=$env{'user.name'}; }
 5757:     my $uhome=&homeserver($uname,$udomain);
 5758:     my %newstorehash;
 5759:     foreach my $item (keys(%$storehash)) {
 5760: 	my $key = $version.':'.&escape($symb).':'.$item;
 5761: 	$newstorehash{$key} = $storehash->{$item};
 5762:     }
 5763:     my $items='';
 5764:     my %allitems = ();
 5765:     foreach my $item (keys(%newstorehash)) {
 5766: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 5767: 	    my $key = $1.':keys:'.$2;
 5768: 	    $allitems{$key} .= $3.':';
 5769: 	}
 5770: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 5771:     }
 5772:     foreach my $item (keys(%allitems)) {
 5773: 	$allitems{$item} =~ s/\:$//;
 5774: 	$items.= $item.'='.$allitems{$item}.'&';
 5775:     }
 5776:     $items=~s/\&$//;
 5777:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5778: }
 5779: 
 5780: # ------------------------------------------------------ critical put interface
 5781: 
 5782: sub cput {
 5783:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5784:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5785:    if (!$uname) { $uname=$env{'user.name'}; }
 5786:    my $uhome=&homeserver($uname,$udomain);
 5787:    my $items='';
 5788:    foreach my $item (keys(%$storehash)) {
 5789:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5790:    }
 5791:    $items=~s/\&$//;
 5792:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 5793: }
 5794: 
 5795: # -------------------------------------------------------------- eget interface
 5796: 
 5797: sub eget {
 5798:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5799:    my $items='';
 5800:    foreach my $item (@$storearr) {
 5801:        $items.=&escape($item).'&';
 5802:    }
 5803:    $items=~s/\&$//;
 5804:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5805:    if (!$uname) { $uname=$env{'user.name'}; }
 5806:    my $uhome=&homeserver($uname,$udomain);
 5807:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 5808:    my @pairs=split(/\&/,$rep);
 5809:    my %returnhash=();
 5810:    my $i=0;
 5811:    foreach my $item (@$storearr) {
 5812:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 5813:       $i++;
 5814:    }
 5815:    return %returnhash;
 5816: }
 5817: 
 5818: # ------------------------------------------------------------ tmpput interface
 5819: sub tmpput {
 5820:     my ($storehash,$server,$context)=@_;
 5821:     my $items='';
 5822:     foreach my $item (keys(%$storehash)) {
 5823: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5824:     }
 5825:     $items=~s/\&$//;
 5826:     if (defined($context)) {
 5827:         $items .= ':'.&escape($context);
 5828:     }
 5829:     return &reply("tmpput:$items",$server);
 5830: }
 5831: 
 5832: # ------------------------------------------------------------ tmpget interface
 5833: sub tmpget {
 5834:     my ($token,$server)=@_;
 5835:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 5836:     my $rep=&reply("tmpget:$token",$server);
 5837:     my %returnhash;
 5838:     foreach my $item (split(/\&/,$rep)) {
 5839: 	my ($key,$value)=split(/=/,$item);
 5840:         next if ($key =~ /^error: 2 /);
 5841: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 5842:     }
 5843:     return %returnhash;
 5844: }
 5845: 
 5846: # ------------------------------------------------------------ tmpdel interface
 5847: sub tmpdel {
 5848:     my ($token,$server)=@_;
 5849:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 5850:     return &reply("tmpdel:$token",$server);
 5851: }
 5852: 
 5853: # ------------------------------------------------------------ get_timebased_id 
 5854: 
 5855: sub get_timebased_id {
 5856:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
 5857:         $maxtries) = @_;
 5858:     my ($newid,$error,$dellock);
 5859:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
 5860:         return ('','ok','invalid call to get suffix');
 5861:     }
 5862: 
 5863: # set defaults for any optional args for which values were not supplied
 5864:     if ($who eq '') {
 5865:         $who = $env{'user.name'}.':'.$env{'user.domain'};
 5866:     }
 5867:     if (!$locktries) {
 5868:         $locktries = 3;
 5869:     }
 5870:     if (!$maxtries) {
 5871:         $maxtries = 10;
 5872:     }
 5873:     
 5874:     if (($cdom eq '') || ($cnum eq '')) {
 5875:         if ($env{'request.course.id'}) {
 5876:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5877:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5878:         }
 5879:         if (($cdom eq '') || ($cnum eq '')) {
 5880:             return ('','ok','call to get suffix not in course context');
 5881:         }
 5882:     }
 5883: 
 5884: # construct locking item
 5885:     my $lockhash = {
 5886:                       $prefix."\0".'locked_'.$keyid => $who,
 5887:                    };
 5888:     my $tries = 0;
 5889: 
 5890: # attempt to get lock on nohist_$namespace file
 5891:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 5892:     while (($gotlock ne 'ok') && $tries <$locktries) {
 5893:         $tries ++;
 5894:         sleep 1;
 5895:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 5896:     }
 5897: 
 5898: # attempt to get unique identifier, based on current timestamp
 5899:     if ($gotlock eq 'ok') {
 5900:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
 5901:         my $id = time;
 5902:         $newid = $id;
 5903:         my $idtries = 0;
 5904:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
 5905:             if ($idtype eq 'concat') {
 5906:                 $newid = $id.$idtries;
 5907:             } else {
 5908:                 $newid ++;
 5909:             }
 5910:             $idtries ++;
 5911:         }
 5912:         if (!exists($inuse{$prefix."\0".$newid})) {
 5913:             my %new_item =  (
 5914:                               $prefix."\0".$newid => $who,
 5915:                             );
 5916:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
 5917:                                                  $cdom,$cnum);
 5918:             if ($putresult ne 'ok') {
 5919:                 undef($newid);
 5920:                 $error = 'error saving new item: '.$putresult;
 5921:             }
 5922:         } else {
 5923:              $error = ('error: no unique suffix available for the new item ');
 5924:         }
 5925: #  remove lock
 5926:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
 5927:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
 5928:     } else {
 5929:         $error = "error: could not obtain lockfile\n";
 5930:         $dellock = 'ok';
 5931:     }
 5932:     return ($newid,$dellock,$error);
 5933: }
 5934: 
 5935: # -------------------------------------------------- portfolio access checking
 5936: 
 5937: sub portfolio_access {
 5938:     my ($requrl) = @_;
 5939:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 5940:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 5941:     if ($result) {
 5942:         my %setters;
 5943:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 5944:             my ($startblock,$endblock) =
 5945:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 5946:             if ($startblock && $endblock) {
 5947:                 return 'B';
 5948:             }
 5949:         } else {
 5950:             my ($startblock,$endblock) =
 5951:                 &Apache::loncommon::blockcheck(\%setters,'port');
 5952:             if ($startblock && $endblock) {
 5953:                 return 'B';
 5954:             }
 5955:         }
 5956:     }
 5957:     if ($result eq 'ok') {
 5958:        return 'F';
 5959:     } elsif ($result =~ /^[^:]+:guest_/) {
 5960:        return 'A';
 5961:     }
 5962:     return '';
 5963: }
 5964: 
 5965: sub get_portfolio_access {
 5966:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 5967: 
 5968:     if (!ref($access_hash)) {
 5969: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 5970: 	my %access_controls = &get_access_controls($current_perms,$group,
 5971: 						   $file_name);
 5972: 	$access_hash = $access_controls{$file_name};
 5973:     }
 5974: 
 5975:     my ($public,$guest,@domains,@users,@courses,@groups);
 5976:     my $now = time;
 5977:     if (ref($access_hash) eq 'HASH') {
 5978:         foreach my $key (keys(%{$access_hash})) {
 5979:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 5980:             if ($start > $now) {
 5981:                 next;
 5982:             }
 5983:             if ($end && $end<$now) {
 5984:                 next;
 5985:             }
 5986:             if ($scope eq 'public') {
 5987:                 $public = $key;
 5988:                 last;
 5989:             } elsif ($scope eq 'guest') {
 5990:                 $guest = $key;
 5991:             } elsif ($scope eq 'domains') {
 5992:                 push(@domains,$key);
 5993:             } elsif ($scope eq 'users') {
 5994:                 push(@users,$key);
 5995:             } elsif ($scope eq 'course') {
 5996:                 push(@courses,$key);
 5997:             } elsif ($scope eq 'group') {
 5998:                 push(@groups,$key);
 5999:             }
 6000:         }
 6001:         if ($public) {
 6002:             return 'ok';
 6003:         }
 6004:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 6005:             if ($guest) {
 6006:                 return $guest;
 6007:             }
 6008:         } else {
 6009:             if (@domains > 0) {
 6010:                 foreach my $domkey (@domains) {
 6011:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 6012:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 6013:                             return 'ok';
 6014:                         }
 6015:                     }
 6016:                 }
 6017:             }
 6018:             if (@users > 0) {
 6019:                 foreach my $userkey (@users) {
 6020:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 6021:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 6022:                             if (ref($item) eq 'HASH') {
 6023:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 6024:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 6025:                                     return 'ok';
 6026:                                 }
 6027:                             }
 6028:                         }
 6029:                     } 
 6030:                 }
 6031:             }
 6032:             my %roleshash;
 6033:             my @courses_and_groups = @courses;
 6034:             push(@courses_and_groups,@groups); 
 6035:             if (@courses_and_groups > 0) {
 6036:                 my (%allgroups,%allroles); 
 6037:                 my ($start,$end,$role,$sec,$group);
 6038:                 foreach my $envkey (%env) {
 6039:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 6040:                         my $cid = $2.'_'.$3; 
 6041:                         if ($1 eq 'gr') {
 6042:                             $group = $4;
 6043:                             $allgroups{$cid}{$group} = $env{$envkey};
 6044:                         } else {
 6045:                             if ($4 eq '') {
 6046:                                 $sec = 'none';
 6047:                             } else {
 6048:                                 $sec = $4;
 6049:                             }
 6050:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 6051:                         }
 6052:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 6053:                         my $cid = $2.'_'.$3;
 6054:                         if ($4 eq '') {
 6055:                             $sec = 'none';
 6056:                         } else {
 6057:                             $sec = $4;
 6058:                         }
 6059:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 6060:                     }
 6061:                 }
 6062:                 if (keys(%allroles) == 0) {
 6063:                     return;
 6064:                 }
 6065:                 foreach my $key (@courses_and_groups) {
 6066:                     my %content = %{$$access_hash{$key}};
 6067:                     my $cnum = $content{'number'};
 6068:                     my $cdom = $content{'domain'};
 6069:                     my $cid = $cdom.'_'.$cnum;
 6070:                     if (!exists($allroles{$cid})) {
 6071:                         next;
 6072:                     }    
 6073:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 6074:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 6075:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 6076:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 6077:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 6078:                         foreach my $role (keys(%{$allroles{$cid}})) {
 6079:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 6080:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 6081:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 6082:                                         if (grep/^all$/,@sections) {
 6083:                                             return 'ok';
 6084:                                         } else {
 6085:                                             if (grep/^$sec$/,@sections) {
 6086:                                                 return 'ok';
 6087:                                             }
 6088:                                         }
 6089:                                     }
 6090:                                 }
 6091:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 6092:                                     if (grep/^none$/,@groups) {
 6093:                                         return 'ok';
 6094:                                     }
 6095:                                 } else {
 6096:                                     if (grep/^all$/,@groups) {
 6097:                                         return 'ok';
 6098:                                     } 
 6099:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 6100:                                         if (grep/^$group$/,@groups) {
 6101:                                             return 'ok';
 6102:                                         }
 6103:                                     }
 6104:                                 } 
 6105:                             }
 6106:                         }
 6107:                     }
 6108:                 }
 6109:             }
 6110:             if ($guest) {
 6111:                 return $guest;
 6112:             }
 6113:         }
 6114:     }
 6115:     return;
 6116: }
 6117: 
 6118: sub course_group_datechecker {
 6119:     my ($dates,$now,$status) = @_;
 6120:     my ($start,$end) = split(/\./,$dates);
 6121:     if (!$start && !$end) {
 6122:         return 'ok';
 6123:     }
 6124:     if (grep/^active$/,@{$status}) {
 6125:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 6126:             return 'ok';
 6127:         }
 6128:     }
 6129:     if (grep/^previous$/,@{$status}) {
 6130:         if ($end > $now ) {
 6131:             return 'ok';
 6132:         }
 6133:     }
 6134:     if (grep/^future$/,@{$status}) {
 6135:         if ($start > $now) {
 6136:             return 'ok';
 6137:         }
 6138:     }
 6139:     return; 
 6140: }
 6141: 
 6142: sub parse_portfolio_url {
 6143:     my ($url) = @_;
 6144: 
 6145:     my ($type,$udom,$unum,$group,$file_name);
 6146:     
 6147:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 6148: 	$type = 1;
 6149:         $udom = $1;
 6150:         $unum = $2;
 6151:         $file_name = $3;
 6152:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 6153: 	$type = 2;
 6154:         $udom = $1;
 6155:         $unum = $2;
 6156:         $group = $3;
 6157:         $file_name = $3.'/'.$4;
 6158:     }
 6159:     if (wantarray) {
 6160: 	return ($type,$udom,$unum,$file_name,$group);
 6161:     }
 6162:     return $type;
 6163: }
 6164: 
 6165: sub is_portfolio_url {
 6166:     my ($url) = @_;
 6167:     return scalar(&parse_portfolio_url($url));
 6168: }
 6169: 
 6170: sub is_portfolio_file {
 6171:     my ($file) = @_;
 6172:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 6173:         return 1;
 6174:     }
 6175:     return;
 6176: }
 6177: 
 6178: sub usertools_access {
 6179:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 6180:     my ($access,%tools);
 6181:     if ($context eq '') {
 6182:         $context = 'tools';
 6183:     }
 6184:     if ($context eq 'requestcourses') {
 6185:         %tools = (
 6186:                       official   => 1,
 6187:                       unofficial => 1,
 6188:                       community  => 1,
 6189:                  );
 6190:     } elsif ($context eq 'requestauthor') {
 6191:         %tools = (
 6192:                       requestauthor => 1,
 6193:                  );
 6194:     } else {
 6195:         %tools = (
 6196:                       aboutme   => 1,
 6197:                       blog      => 1,
 6198:                       webdav    => 1,
 6199:                       portfolio => 1,
 6200:                  );
 6201:     }
 6202:     return if (!defined($tools{$tool}));
 6203: 
 6204:     if ((!defined($udom)) || (!defined($uname))) {
 6205:         $udom = $env{'user.domain'};
 6206:         $uname = $env{'user.name'};
 6207:     }
 6208: 
 6209:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 6210:         if ($action ne 'reload') {
 6211:             if ($context eq 'requestcourses') {
 6212:                 return $env{'environment.canrequest.'.$tool};
 6213:             } elsif ($context eq 'requestauthor') {
 6214:                 return $env{'environment.canrequest.author'};
 6215:             } else {
 6216:                 return $env{'environment.availabletools.'.$tool};
 6217:             }
 6218:         }
 6219:     }
 6220: 
 6221:     my ($toolstatus,$inststatus,$envkey);
 6222:     if ($context eq 'requestauthor') {
 6223:         $envkey = $context; 
 6224:     } else {
 6225:         $envkey = $context.'.'.$tool;
 6226:     }
 6227: 
 6228:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 6229:          ($action ne 'reload')) {
 6230:         $toolstatus = $env{'environment.'.$envkey};
 6231:         $inststatus = $env{'environment.inststatus'};
 6232:     } else {
 6233:         if (ref($userenvref) eq 'HASH') {
 6234:             $toolstatus = $userenvref->{$envkey};
 6235:             $inststatus = $userenvref->{'inststatus'};
 6236:         } else {
 6237:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 6238:             $toolstatus = $userenv{$envkey};
 6239:             $inststatus = $userenv{'inststatus'};
 6240:         }
 6241:     }
 6242: 
 6243:     if ($toolstatus ne '') {
 6244:         if ($toolstatus) {
 6245:             $access = 1;
 6246:         } else {
 6247:             $access = 0;
 6248:         }
 6249:         return $access;
 6250:     }
 6251: 
 6252:     my ($is_adv,%domdef);
 6253:     if (ref($is_advref) eq 'HASH') {
 6254:         $is_adv = $is_advref->{'is_adv'};
 6255:     } else {
 6256:         $is_adv = &is_advanced_user($udom,$uname);
 6257:     }
 6258:     if (ref($domdefref) eq 'HASH') {
 6259:         %domdef = %{$domdefref};
 6260:     } else {
 6261:         %domdef = &get_domain_defaults($udom);
 6262:     }
 6263:     if (ref($domdef{$tool}) eq 'HASH') {
 6264:         if ($is_adv) {
 6265:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 6266:                 if ($domdef{$tool}{'_LC_adv'}) { 
 6267:                     $access = 1;
 6268:                 } else {
 6269:                     $access = 0;
 6270:                 }
 6271:                 return $access;
 6272:             }
 6273:         }
 6274:         if ($inststatus ne '') {
 6275:             my ($hasaccess,$hasnoaccess);
 6276:             foreach my $affiliation (split(/:/,$inststatus)) {
 6277:                 if ($domdef{$tool}{$affiliation} ne '') { 
 6278:                     if ($domdef{$tool}{$affiliation}) {
 6279:                         $hasaccess = 1;
 6280:                     } else {
 6281:                         $hasnoaccess = 1;
 6282:                     }
 6283:                 }
 6284:             }
 6285:             if ($hasaccess || $hasnoaccess) {
 6286:                 if ($hasaccess) {
 6287:                     $access = 1;
 6288:                 } elsif ($hasnoaccess) {
 6289:                     $access = 0; 
 6290:                 }
 6291:                 return $access;
 6292:             }
 6293:         } else {
 6294:             if ($domdef{$tool}{'default'} ne '') {
 6295:                 if ($domdef{$tool}{'default'}) {
 6296:                     $access = 1;
 6297:                 } elsif ($domdef{$tool}{'default'} == 0) {
 6298:                     $access = 0;
 6299:                 }
 6300:                 return $access;
 6301:             }
 6302:         }
 6303:     } else {
 6304:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 6305:             $access = 1;
 6306:         } else {
 6307:             $access = 0;
 6308:         }
 6309:         return $access;
 6310:     }
 6311: }
 6312: 
 6313: sub is_course_owner {
 6314:     my ($cdom,$cnum,$udom,$uname) = @_;
 6315:     if (($udom eq '') || ($uname eq '')) {
 6316:         $udom = $env{'user.domain'};
 6317:         $uname = $env{'user.name'};
 6318:     }
 6319:     unless (($udom eq '') || ($uname eq '')) {
 6320:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 6321:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 6322:                 return 1;
 6323:             } else {
 6324:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 6325:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 6326:                     return 1;
 6327:                 }
 6328:             }
 6329:         }
 6330:     }
 6331:     return;
 6332: }
 6333: 
 6334: sub is_advanced_user {
 6335:     my ($udom,$uname) = @_;
 6336:     if ($udom ne '' && $uname ne '') {
 6337:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 6338:             if (wantarray) {
 6339:                 return ($env{'user.adv'},$env{'user.author'});
 6340:             } else {
 6341:                 return $env{'user.adv'};
 6342:             }
 6343:         }
 6344:     }
 6345:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 6346:     my %allroles;
 6347:     my ($is_adv,$is_author);
 6348:     foreach my $role (keys(%roleshash)) {
 6349:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 6350:         my $area = '/'.$tdomain.'/'.$trest;
 6351:         if ($sec ne '') {
 6352:             $area .= '/'.$sec;
 6353:         }
 6354:         if (($area ne '') && ($trole ne '')) {
 6355:             my $spec=$trole.'.'.$area;
 6356:             if ($trole =~ /^cr\//) {
 6357:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 6358:             } elsif ($trole ne 'gr') {
 6359:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 6360:             }
 6361:             if ($trole eq 'au') {
 6362:                 $is_author = 1;
 6363:             }
 6364:         }
 6365:     }
 6366:     foreach my $role (keys(%allroles)) {
 6367:         last if ($is_adv);
 6368:         foreach my $item (split(/:/,$allroles{$role})) {
 6369:             if ($item ne '') {
 6370:                 my ($privilege,$restrictions)=split(/&/,$item);
 6371:                 if ($privilege eq 'adv') {
 6372:                     $is_adv = 1;
 6373:                     last;
 6374:                 }
 6375:             }
 6376:         }
 6377:     }
 6378:     if (wantarray) {
 6379:         return ($is_adv,$is_author);
 6380:     }
 6381:     return $is_adv;
 6382: }
 6383: 
 6384: sub check_can_request {
 6385:     my ($dom,$can_request,$request_domains) = @_;
 6386:     my $canreq = 0;
 6387:     my ($types,$typename) = &Apache::loncommon::course_types();
 6388:     my @options = ('approval','validate','autolimit');
 6389:     my $optregex = join('|',@options);
 6390:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 6391:         foreach my $type (@{$types}) {
 6392:             if (&usertools_access($env{'user.name'},
 6393:                                   $env{'user.domain'},
 6394:                                   $type,undef,'requestcourses')) {
 6395:                 $canreq ++;
 6396:                 if (ref($request_domains) eq 'HASH') {
 6397:                     push(@{$request_domains->{$type}},$env{'user.domain'});
 6398:                 }
 6399:                 if ($dom eq $env{'user.domain'}) {
 6400:                     $can_request->{$type} = 1;
 6401:                 }
 6402:             }
 6403:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
 6404:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 6405:                 if (@curr > 0) {
 6406:                     foreach my $item (@curr) {
 6407:                         if (ref($request_domains) eq 'HASH') {
 6408:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 6409:                             if ($otherdom ne '') {
 6410:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 6411:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 6412:                                         push(@{$request_domains->{$type}},$otherdom);
 6413:                                     }
 6414:                                 } else {
 6415:                                     push(@{$request_domains->{$type}},$otherdom);
 6416:                                 }
 6417:                             }
 6418:                         }
 6419:                     }
 6420:                     unless($dom eq $env{'user.domain'}) {
 6421:                         $canreq ++;
 6422:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 6423:                             $can_request->{$type} = 1;
 6424:                         }
 6425:                     }
 6426:                 }
 6427:             }
 6428:         }
 6429:     }
 6430:     return $canreq;
 6431: }
 6432: 
 6433: # ---------------------------------------------- Custom access rule evaluation
 6434: 
 6435: sub customaccess {
 6436:     my ($priv,$uri)=@_;
 6437:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 6438:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 6439:     $udom = &LONCAPA::clean_domain($udom);
 6440:     $ucrs = &LONCAPA::clean_username($ucrs);
 6441:     my $access=0;
 6442:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 6443: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 6444: 	if ($type eq 'user') {
 6445: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 6446: 		my ($tdom,$tuname)=split(m{/},$scope);
 6447: 		if ($tdom) {
 6448: 		    if ($tdom ne $env{'user.domain'}) { next; }
 6449: 		}
 6450: 		if ($tuname) {
 6451: 		    if ($tuname ne $env{'user.name'}) { next; }
 6452: 		}
 6453: 		$access=($effect eq 'allow');
 6454: 		last;
 6455: 	    }
 6456: 	} else {
 6457: 	    if ($role) {
 6458: 		if ($role ne $urole) { next; }
 6459: 	    }
 6460: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 6461: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 6462: 		if ($tdom) {
 6463: 		    if ($tdom ne $udom) { next; }
 6464: 		}
 6465: 		if ($tcrs) {
 6466: 		    if ($tcrs ne $ucrs) { next; }
 6467: 		}
 6468: 		if ($tsec) {
 6469: 		    if ($tsec ne $usec) { next; }
 6470: 		}
 6471: 		$access=($effect eq 'allow');
 6472: 		last;
 6473: 	    }
 6474: 	    if ($realm eq '' && $role eq '') {
 6475: 		$access=($effect eq 'allow');
 6476: 	    }
 6477: 	}
 6478:     }
 6479:     return $access;
 6480: }
 6481: 
 6482: # ------------------------------------------------- Check for a user privilege
 6483: 
 6484: sub allowed {
 6485:     my ($priv,$uri,$symb,$role)=@_;
 6486:     my $ver_orguri=$uri;
 6487:     $uri=&deversion($uri);
 6488:     my $orguri=$uri;
 6489:     $uri=&declutter($uri);
 6490: 
 6491:     if ($priv eq 'evb') {
 6492: # Evade communication block restrictions for specified role in a course
 6493:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 6494:             return $1;
 6495:         } else {
 6496:             return;
 6497:         }
 6498:     }
 6499: 
 6500:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 6501: # Free bre access to adm and meta resources
 6502:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 6503: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 6504: 	&& ($priv eq 'bre')) {
 6505: 	return 'F';
 6506:     }
 6507: 
 6508: # Free bre access to user's own portfolio contents
 6509:     my ($space,$domain,$name,@dir)=split('/',$uri);
 6510:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 6511: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 6512:         my %setters;
 6513:         my ($startblock,$endblock) = 
 6514:             &Apache::loncommon::blockcheck(\%setters,'port');
 6515:         if ($startblock && $endblock) {
 6516:             return 'B';
 6517:         } else {
 6518:             return 'F';
 6519:         }
 6520:     }
 6521: 
 6522: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 6523:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 6524:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 6525:         if (exists($env{'request.course.id'})) {
 6526:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6527:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6528:             if (($domain eq $cdom) && ($name eq $cnum)) {
 6529:                 my $courseprivid=$env{'request.course.id'};
 6530:                 $courseprivid=~s/\_/\//;
 6531:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 6532:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 6533:                     return $1; 
 6534:                 } else {
 6535:                     if ($env{'request.course.sec'}) {
 6536:                         $courseprivid.='/'.$env{'request.course.sec'};
 6537:                     }
 6538:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 6539:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 6540:                         return $2;
 6541:                     }
 6542:                 }
 6543:             }
 6544:         }
 6545:     }
 6546: 
 6547: # Free bre to public access
 6548: 
 6549:     if ($priv eq 'bre') {
 6550:         my $copyright=&metadata($uri,'copyright');
 6551: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 6552:            return 'F'; 
 6553:         }
 6554:         if ($copyright eq 'priv') {
 6555:             $uri=~/([^\/]+)\/([^\/]+)\//;
 6556: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 6557: 		return '';
 6558:             }
 6559:         }
 6560:         if ($copyright eq 'domain') {
 6561:             $uri=~/([^\/]+)\/([^\/]+)\//;
 6562: 	    unless (($env{'user.domain'} eq $1) ||
 6563:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 6564: 		return '';
 6565:             }
 6566:         }
 6567:         if ($env{'request.role'}=~ /li\.\//) {
 6568:             # Library role, so allow browsing of resources in this domain.
 6569:             return 'F';
 6570:         }
 6571:         if ($copyright eq 'custom') {
 6572: 	    unless (&customaccess($priv,$uri)) { return ''; }
 6573:         }
 6574:     }
 6575:     # Domain coordinator is trying to create a course
 6576:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 6577:         # uri is the requested domain in this case.
 6578:         # comparison to 'request.role.domain' shows if the user has selected
 6579:         # a role of dc for the domain in question.
 6580:         return 'F' if ($uri eq $env{'request.role.domain'});
 6581:     }
 6582: 
 6583:     my $thisallowed='';
 6584:     my $statecond=0;
 6585:     my $courseprivid='';
 6586: 
 6587:     my $ownaccess;
 6588:     # Community Coordinator or Assistant Co-author browsing resource space.
 6589:     if (($priv eq 'bro') && ($env{'user.author'})) {
 6590:         if ($uri eq '') {
 6591:             $ownaccess = 1;
 6592:         } else {
 6593:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 6594:                 my $udom = $env{'user.domain'};
 6595:                 my $uname = $env{'user.name'};
 6596:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 6597:                     $ownaccess = 1;
 6598:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 6599:                     unless ($uri =~ m{\.\./}) {
 6600:                         $ownaccess = 1;
 6601:                     }
 6602:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 6603:                     my $now = time;
 6604:                     if ($uri =~ m{^([^/]+)/?$}) {
 6605:                         my $adom = $1;
 6606:                         foreach my $key (keys(%env)) {
 6607:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 6608:                                 my ($start,$end) = split('.',$env{$key});
 6609:                                 if (($now >= $start) && (!$end || $end < $now)) {
 6610:                                     $ownaccess = 1;
 6611:                                     last;
 6612:                                 }
 6613:                             }
 6614:                         }
 6615:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 6616:                         my $adom = $1;
 6617:                         my $aname = $2;
 6618:                         foreach my $role ('ca','aa') { 
 6619:                             if ($env{"user.role.$role./$adom/$aname"}) {
 6620:                                 my ($start,$end) =
 6621:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 6622:                                 if (($now >= $start) && (!$end || $end < $now)) {
 6623:                                     $ownaccess = 1;
 6624:                                     last;
 6625:                                 }
 6626:                             }
 6627:                         }
 6628:                     }
 6629:                 }
 6630:             }
 6631:         }
 6632:     }
 6633: 
 6634: # Course
 6635: 
 6636:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 6637:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6638:             $thisallowed.=$1;
 6639:         }
 6640:     }
 6641: 
 6642: # Domain
 6643: 
 6644:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 6645:        =~/\Q$priv\E\&([^\:]*)/) {
 6646:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6647:             $thisallowed.=$1;
 6648:         }
 6649:     }
 6650: 
 6651: # User who is not author or co-author might still be able to edit
 6652: # resource of an author in the domain (e.g., if Domain Coordinator).
 6653:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 6654:         (&allowed('mdc',$env{'request.course.id'}))) {
 6655:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 6656:             $thisallowed.=$1;
 6657:         }
 6658:     }
 6659: 
 6660: # Course: uri itself is a course
 6661:     my $courseuri=$uri;
 6662:     $courseuri=~s/\_(\d)/\/$1/;
 6663:     $courseuri=~s/^([^\/])/\/$1/;
 6664: 
 6665:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 6666:        =~/\Q$priv\E\&([^\:]*)/) {
 6667:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6668:             $thisallowed.=$1;
 6669:         }
 6670:     }
 6671: 
 6672: # URI is an uploaded document for this course, default permissions don't matter
 6673: # not allowing 'edit' access (editupload) to uploaded course docs
 6674:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 6675: 	$thisallowed='';
 6676:         my ($match)=&is_on_map($uri);
 6677:         if ($match) {
 6678:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 6679:                   =~/\Q$priv\E\&([^\:]*)/) {
 6680:                 my @blockers = &has_comm_blocking($priv,$symb,$uri);
 6681:                 if (@blockers > 0) {
 6682:                     $thisallowed = 'B';
 6683:                 } else {
 6684:                     $thisallowed.=$1;
 6685:                 }
 6686:             }
 6687:         } else {
 6688:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 6689:             if ($refuri) {
 6690:                 if ($refuri =~ m|^/adm/|) {
 6691:                     $thisallowed='F';
 6692:                 } else {
 6693:                     $refuri=&declutter($refuri);
 6694:                     my ($match) = &is_on_map($refuri);
 6695:                     if ($match) {
 6696:                         my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 6697:                         if (@blockers > 0) {
 6698:                             $thisallowed = 'B';
 6699:                         } else {
 6700:                             $thisallowed='F';
 6701:                         }
 6702:                     }
 6703:                 }
 6704:             }
 6705:         }
 6706:     }
 6707: 
 6708:     if ($priv eq 'bre'
 6709: 	&& $thisallowed ne 'F' 
 6710: 	&& $thisallowed ne '2'
 6711: 	&& &is_portfolio_url($uri)) {
 6712: 	$thisallowed = &portfolio_access($uri);
 6713:     }
 6714:     
 6715: # Full access at system, domain or course-wide level? Exit.
 6716:     if ($thisallowed=~/F/) {
 6717: 	return 'F';
 6718:     }
 6719: 
 6720: # If this is generating or modifying users, exit with special codes
 6721: 
 6722:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 6723: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 6724: 	    my ($audom,$auname)=split('/',$uri);
 6725: # no author name given, so this just checks on the general right to make a co-author in this domain
 6726: 	    unless ($auname) { return $thisallowed; }
 6727: # an author name is given, so we are about to actually make a co-author for a certain account
 6728: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 6729: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 6730: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 6731: 	}
 6732: 	return $thisallowed;
 6733:     }
 6734: #
 6735: # Gathered so far: system, domain and course wide privileges
 6736: #
 6737: # Course: See if uri or referer is an individual resource that is part of 
 6738: # the course
 6739: 
 6740:     if ($env{'request.course.id'}) {
 6741: 
 6742:        $courseprivid=$env{'request.course.id'};
 6743:        if ($env{'request.course.sec'}) {
 6744:           $courseprivid.='/'.$env{'request.course.sec'};
 6745:        }
 6746:        $courseprivid=~s/\_/\//;
 6747:        my $checkreferer=1;
 6748:        my ($match,$cond)=&is_on_map($uri);
 6749:        if ($match) {
 6750:            $statecond=$cond;
 6751:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 6752:                =~/\Q$priv\E\&([^\:]*)/) {
 6753:                my $value = $1;
 6754:                if ($priv eq 'bre') {
 6755:                    my @blockers = &has_comm_blocking($priv,$symb,$uri);
 6756:                    if (@blockers > 0) {
 6757:                        $thisallowed = 'B';
 6758:                    } else {
 6759:                        $thisallowed.=$value;
 6760:                    }
 6761:                } else {
 6762:                    $thisallowed.=$value;
 6763:                }
 6764:                $checkreferer=0;
 6765:            }
 6766:        }
 6767:        
 6768:        if ($checkreferer) {
 6769: 	  my $refuri=$env{'httpref.'.$orguri};
 6770:             unless ($refuri) {
 6771:                 foreach my $key (keys(%env)) {
 6772: 		    if ($key=~/^httpref\..*\*/) {
 6773: 			my $pattern=$key;
 6774:                         $pattern=~s/^httpref\.\/res\///;
 6775:                         $pattern=~s/\*/\[\^\/\]\+/g;
 6776:                         $pattern=~s/\//\\\//g;
 6777:                         if ($orguri=~/$pattern/) {
 6778: 			    $refuri=$env{$key};
 6779:                         }
 6780:                     }
 6781:                 }
 6782:             }
 6783: 
 6784:          if ($refuri) { 
 6785: 	  $refuri=&declutter($refuri);
 6786:           my ($match,$cond)=&is_on_map($refuri);
 6787:             if ($match) {
 6788:               my $refstatecond=$cond;
 6789:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 6790:                   =~/\Q$priv\E\&([^\:]*)/) {
 6791:                   my $value = $1;
 6792:                   if ($priv eq 'bre') {
 6793:                       my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 6794:                       if (@blockers > 0) {
 6795:                           $thisallowed = 'B';
 6796:                       } else {
 6797:                           $thisallowed.=$value;
 6798:                       }
 6799:                   } else {
 6800:                       $thisallowed.=$value;
 6801:                   }
 6802:                   $uri=$refuri;
 6803:                   $statecond=$refstatecond;
 6804:               }
 6805:           }
 6806:         }
 6807:        }
 6808:    }
 6809: 
 6810: #
 6811: # Gathered now: all privileges that could apply, and condition number
 6812: # 
 6813: #
 6814: # Full or no access?
 6815: #
 6816: 
 6817:     if ($thisallowed=~/F/) {
 6818: 	return 'F';
 6819:     }
 6820: 
 6821:     unless ($thisallowed) {
 6822:         return '';
 6823:     }
 6824: 
 6825: # Restrictions exist, deal with them
 6826: #
 6827: #   C:according to course preferences
 6828: #   R:according to resource settings
 6829: #   L:unless locked
 6830: #   X:according to user session state
 6831: #
 6832: 
 6833: # Possibly locked functionality, check all courses
 6834: # Locks might take effect only after 10 minutes cache expiration for other
 6835: # courses, and 2 minutes for current course
 6836: 
 6837:     my $envkey;
 6838:     if ($thisallowed=~/L/) {
 6839:         foreach $envkey (keys(%env)) {
 6840:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 6841:                my $courseid=$2;
 6842:                my $roleid=$1.'.'.$2;
 6843:                $courseid=~s/^\///;
 6844:                my $expiretime=600;
 6845:                if ($env{'request.role'} eq $roleid) {
 6846: 		  $expiretime=120;
 6847:                }
 6848: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 6849:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 6850:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 6851: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 6852:                }
 6853:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 6854:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 6855: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 6856:                        &log($env{'user.domain'},$env{'user.name'},
 6857:                             $env{'user.home'},
 6858:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 6859:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 6860:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 6861: 		       return '';
 6862:                    }
 6863:                }
 6864:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 6865:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 6866: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 6867:                        &log($env{'user.domain'},$env{'user.name'},
 6868:                             $env{'user.home'},
 6869:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 6870:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 6871:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 6872: 		       return '';
 6873:                    }
 6874:                }
 6875: 	   }
 6876:        }
 6877:     }
 6878:    
 6879: #
 6880: # Rest of the restrictions depend on selected course
 6881: #
 6882: 
 6883:     unless ($env{'request.course.id'}) {
 6884: 	if ($thisallowed eq 'A') {
 6885: 	    return 'A';
 6886:         } elsif ($thisallowed eq 'B') {
 6887:             return 'B';
 6888: 	} else {
 6889: 	    return '1';
 6890: 	}
 6891:     }
 6892: 
 6893: #
 6894: # Now user is definitely in a course
 6895: #
 6896: 
 6897: 
 6898: # Course preferences
 6899: 
 6900:    if ($thisallowed=~/C/) {
 6901:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 6902:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 6903:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 6904: 	   =~/\Q$rolecode\E/) {
 6905: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6906: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 6907: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 6908: 			$env{'request.course.id'});
 6909: 	   }
 6910:            return '';
 6911:        }
 6912: 
 6913:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 6914: 	   =~/\Q$unamedom\E/) {
 6915: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6916: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 6917: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 6918: 			$env{'request.course.id'});
 6919: 	   }
 6920:            return '';
 6921:        }
 6922:    }
 6923: 
 6924: # Resource preferences
 6925: 
 6926:    if ($thisallowed=~/R/) {
 6927:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 6928:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 6929: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6930: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 6931: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 6932: 	   }
 6933: 	   return '';
 6934:        }
 6935:    }
 6936: 
 6937: # Restricted by state or randomout?
 6938: 
 6939:    if ($thisallowed=~/X/) {
 6940:       if ($env{'acc.randomout'}) {
 6941: 	 if (!$symb) { $symb=&symbread($uri,1); }
 6942:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 6943:             return ''; 
 6944:          }
 6945:       }
 6946:       if (&condval($statecond)) {
 6947: 	 return '2';
 6948:       } else {
 6949:          return '';
 6950:       }
 6951:    }
 6952: 
 6953:     if ($thisallowed eq 'A') {
 6954: 	return 'A';
 6955:     } elsif ($thisallowed eq 'B') {
 6956:         return 'B';
 6957:     }
 6958:    return 'F';
 6959: }
 6960: 
 6961: # ------------------------------------------- Check construction space access
 6962: 
 6963: sub constructaccess {
 6964:     my ($url,$setpriv)=@_;
 6965: 
 6966: # We do not allow editing of previous versions of files
 6967:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
 6968: 
 6969: # Get username and domain from URL
 6970:     my ($ownername,$ownerdomain,$ownerhome);
 6971: 
 6972:     ($ownerdomain,$ownername) =
 6973:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
 6974: 
 6975: # The URL does not really point to any authorspace, forget it
 6976:     unless (($ownername) && ($ownerdomain)) { return ''; }
 6977: 
 6978: # Now we need to see if the user has access to the authorspace of
 6979: # $ownername at $ownerdomain
 6980: 
 6981:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
 6982: # Real author for this?
 6983:        $ownerhome = $env{'user.home'};
 6984:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
 6985:           return ($ownername,$ownerdomain,$ownerhome);
 6986:        }
 6987:     } else {
 6988: # Co-author for this?
 6989:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
 6990:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
 6991:             $ownerhome = &homeserver($ownername,$ownerdomain);
 6992:             return ($ownername,$ownerdomain,$ownerhome);
 6993:         }
 6994:     }
 6995: 
 6996: # We don't have any access right now. If we are not possibly going to do anything about this,
 6997: # we might as well leave
 6998:    unless ($setpriv) { return ''; }
 6999: 
 7000: # Backdoor access?
 7001:     my $allowed=&allowed('eco',$ownerdomain);
 7002: # Nope
 7003:     unless ($allowed) { return ''; }
 7004: # Looks like we may have access, but could be locked by the owner of the construction space
 7005:     if ($allowed eq 'U') {
 7006:         my %blocked=&get('environment',['domcoord.author'],
 7007:                          $ownerdomain,$ownername);
 7008: # Is blocked by owner
 7009:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
 7010:     }
 7011:     if (($allowed eq 'F') || ($allowed eq 'U')) {
 7012: # Grant temporary access
 7013:         my $then=$env{'user.login.time'};
 7014:         my $update=$env{'user.update.time'};
 7015:         if (!$update) { $update = $then; }
 7016:         my $refresh=$env{'user.refresh.time'};
 7017:         if (!$refresh) { $refresh = $update; }
 7018:         my $now = time;
 7019:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
 7020:                            $now,'ca','constructaccess');
 7021:         $ownerhome = &homeserver($ownername,$ownerdomain);
 7022:         return($ownername,$ownerdomain,$ownerhome);
 7023:     }
 7024: # No business here
 7025:     return '';
 7026: }
 7027: 
 7028: sub get_comm_blocks {
 7029:     my ($cdom,$cnum) = @_;
 7030:     if ($cdom eq '' || $cnum eq '') {
 7031:         return unless ($env{'request.course.id'});
 7032:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7033:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7034:     }
 7035:     my %commblocks;
 7036:     my $hashid=$cdom.'_'.$cnum;
 7037:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 7038:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 7039:         %commblocks = %{$blocksref};
 7040:     } else {
 7041:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 7042:         my $cachetime = 600;
 7043:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 7044:     }
 7045:     return %commblocks;
 7046: }
 7047: 
 7048: sub has_comm_blocking {
 7049:     my ($priv,$symb,$uri,$blocks) = @_;
 7050:     return unless ($env{'request.course.id'});
 7051:     return unless ($priv eq 'bre');
 7052:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 7053:     my %commblocks;
 7054:     if (ref($blocks) eq 'HASH') {
 7055:         %commblocks = %{$blocks};
 7056:     } else {
 7057:         %commblocks = &get_comm_blocks();
 7058:     }
 7059:     return unless (keys(%commblocks) > 0);
 7060:     if (!$symb) { $symb=&symbread($uri,1); }
 7061:     my ($map,$resid,undef)=&decode_symb($symb);
 7062:     my %tocheck = (
 7063:                     maps      => $map,
 7064:                     resources => $symb,
 7065:                   );
 7066:     my @blockers;
 7067:     my $now = time;
 7068:     my $navmap = Apache::lonnavmaps::navmap->new();
 7069:     foreach my $block (keys(%commblocks)) {
 7070:         if ($block =~ /^(\d+)____(\d+)$/) {
 7071:             my ($start,$end) = ($1,$2);
 7072:             if ($start <= $now && $end >= $now) {
 7073:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 7074:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 7075:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 7076:                             if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
 7077:                                 unless (grep(/^\Q$block\E$/,@blockers)) {
 7078:                                     push(@blockers,$block);
 7079:                                 }
 7080:                             }
 7081:                         }
 7082:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 7083:                             if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
 7084:                                 unless (grep(/^\Q$block\E$/,@blockers)) {  
 7085:                                     push(@blockers,$block);
 7086:                                 }
 7087:                             }
 7088:                         }
 7089:                     }
 7090:                 }
 7091:             }
 7092:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 7093:             my $item = $1;
 7094:             my @to_test;
 7095:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 7096:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 7097:                     my $check_interval;
 7098:                     if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
 7099:                         my @interval;
 7100:                         my $type = 'map';
 7101:                         if ($item eq 'course') {
 7102:                             $type = 'course';
 7103:                             @interval=&EXT("resource.0.interval");
 7104:                         } else {
 7105:                             if ($item =~ /___\d+___/) {
 7106:                                 $type = 'resource';
 7107:                                 @interval=&EXT("resource.0.interval",$item);
 7108:                                 if (ref($navmap)) {                        
 7109:                                     my $res = $navmap->getBySymb($item); 
 7110:                                     push(@to_test,$res);
 7111:                                 }
 7112:                             } else {
 7113:                                 my $mapsymb = &symbread($item,1);
 7114:                                 if ($mapsymb) {
 7115:                                     if (ref($navmap)) {
 7116:                                         my $mapres = $navmap->getBySymb($mapsymb);
 7117:                                         @to_test = $mapres->retrieveResources($mapres,undef,0,1);
 7118:                                         foreach my $res (@to_test) {
 7119:                                             my $symb = $res->symb();
 7120:                                             next if ($symb eq $mapsymb);
 7121:                                             if ($symb ne '') {
 7122:                                                 @interval=&EXT("resource.0.interval",$symb);
 7123:                                                 last;
 7124:                                             }
 7125:                                         }
 7126:                                     }
 7127:                                 }
 7128:                             }
 7129:                         }
 7130:                         if ($interval[0] =~ /\d+/) {
 7131:                             my $first_access;
 7132:                             if ($type eq 'resource') {
 7133:                                 $first_access=&get_first_access($interval[1],$item);
 7134:                             } elsif ($type eq 'map') {
 7135:                                 $first_access=&get_first_access($interval[1],undef,$item);
 7136:                             } else {
 7137:                                 $first_access=&get_first_access($interval[1]);
 7138:                             }
 7139:                             if ($first_access) {
 7140:                                 my $timesup = $first_access+$interval[0];
 7141:                                 if ($timesup > $now) {
 7142:                                     foreach my $res (@to_test) {
 7143:                                         if ($res->is_problem()) {
 7144:                                             if ($res->completable()) {
 7145:                                                 unless (grep(/^\Q$block\E$/,@blockers)) {
 7146:                                                     push(@blockers,$block);
 7147:                                                 }
 7148:                                                 last;
 7149:                                             }
 7150:                                         }
 7151:                                     }
 7152:                                 }
 7153:                             }
 7154:                         }
 7155:                     }
 7156:                 }
 7157:             }
 7158:         }
 7159:     }
 7160:     return @blockers;
 7161: }
 7162: 
 7163: sub check_docs_block {
 7164:     my ($docsblock,$tocheck) =@_;
 7165:     if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
 7166:         return;
 7167:     }
 7168:     if (ref($docsblock->{'maps'}) eq 'HASH') {
 7169:         if ($tocheck->{'maps'}) {
 7170:             if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
 7171:                 return 1;
 7172:             }
 7173:         }
 7174:     }
 7175:     if (ref($docsblock->{'resources'}) eq 'HASH') {
 7176:         if ($tocheck->{'resources'}) {
 7177:             if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
 7178:                 return 1;
 7179:             }
 7180:         }
 7181:     }
 7182:     return;
 7183: }
 7184: 
 7185: #
 7186: #   Removes the versino from a URI and
 7187: #   splits it in to its filename and path to the filename.
 7188: #   Seems like File::Basename could have done this more clearly.
 7189: #   Parameters:
 7190: #      $uri   - input URI
 7191: #   Returns:
 7192: #     Two element list consisting of 
 7193: #     $pathname  - the URI up to and excluding the trailing /
 7194: #     $filename  - The part of the URI following the last /
 7195: #  NOTE:
 7196: #    Another realization of this is simply:
 7197: #    use File::Basename;
 7198: #    ...
 7199: #    $uri = shift;
 7200: #    $filename = basename($uri);
 7201: #    $path     = dirname($uri);
 7202: #    return ($filename, $path);
 7203: #
 7204: #     The implementation below is probably faster however.
 7205: #
 7206: sub split_uri_for_cond {
 7207:     my $uri=&deversion(&declutter(shift));
 7208:     my @uriparts=split(/\//,$uri);
 7209:     my $filename=pop(@uriparts);
 7210:     my $pathname=join('/',@uriparts);
 7211:     return ($pathname,$filename);
 7212: }
 7213: # --------------------------------------------------- Is a resource on the map?
 7214: 
 7215: sub is_on_map {
 7216:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 7217:     #Trying to find the conditional for the file
 7218:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 7219: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 7220:     if ($match) {
 7221: 	return (1,$1);
 7222:     } else {
 7223: 	return (0,0);
 7224:     }
 7225: }
 7226: 
 7227: # --------------------------------------------------------- Get symb from alias
 7228: 
 7229: sub get_symb_from_alias {
 7230:     my $symb=shift;
 7231:     my ($map,$resid,$url)=&decode_symb($symb);
 7232: # Already is a symb
 7233:     if ($url) { return $symb; }
 7234: # Must be an alias
 7235:     my $aliassymb='';
 7236:     my %bighash;
 7237:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7238:                             &GDBM_READER(),0640)) {
 7239:         my $rid=$bighash{'mapalias_'.$symb};
 7240: 	if ($rid) {
 7241: 	    my ($mapid,$resid)=split(/\./,$rid);
 7242: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 7243: 				    $resid,$bighash{'src_'.$rid});
 7244: 	}
 7245:         untie %bighash;
 7246:     }
 7247:     return $aliassymb;
 7248: }
 7249: 
 7250: # ----------------------------------------------------------------- Define Role
 7251: 
 7252: sub definerole {
 7253:   if (allowed('mcr','/')) {
 7254:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 7255:     foreach my $role (split(':',$sysrole)) {
 7256: 	my ($crole,$cqual)=split(/\&/,$role);
 7257:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 7258:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 7259: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 7260:                return "refused:s:$crole&$cqual"; 
 7261:             }
 7262:         }
 7263:     }
 7264:     foreach my $role (split(':',$domrole)) {
 7265: 	my ($crole,$cqual)=split(/\&/,$role);
 7266:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 7267:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 7268: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 7269:                return "refused:d:$crole&$cqual"; 
 7270:             }
 7271:         }
 7272:     }
 7273:     foreach my $role (split(':',$courole)) {
 7274: 	my ($crole,$cqual)=split(/\&/,$role);
 7275:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 7276:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 7277: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 7278:                return "refused:c:$crole&$cqual"; 
 7279:             }
 7280:         }
 7281:     }
 7282:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 7283:                 "$env{'user.domain'}:$env{'user.name'}:".
 7284: 	        "rolesdef_$rolename=".
 7285:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 7286:     return reply($command,$env{'user.home'});
 7287:   } else {
 7288:     return 'refused';
 7289:   }
 7290: }
 7291: 
 7292: # ---------------- Make a metadata query against the network of library servers
 7293: 
 7294: sub metadata_query {
 7295:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
 7296:     my %rhash;
 7297:     my %libserv = &all_library();
 7298:     my @server_list = (defined($server_array) ? @$server_array
 7299:                                               : keys(%libserv) );
 7300:     for my $server (@server_list) {
 7301:         my $domains = ''; 
 7302:         if (ref($domains_hash) eq 'HASH') {
 7303:             $domains = $domains_hash->{$server}; 
 7304:         }
 7305: 	unless ($custom or $customshow) {
 7306: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
 7307: 	    $rhash{$server}=$reply;
 7308: 	}
 7309: 	else {
 7310: 	    my $reply=&reply("querysend:".&escape($query).':'.
 7311: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
 7312: 			     $server);
 7313: 	    $rhash{$server}=$reply;
 7314: 	}
 7315:     }
 7316:     return \%rhash;
 7317: }
 7318: 
 7319: # ----------------------------------------- Send log queries and wait for reply
 7320: 
 7321: sub log_query {
 7322:     my ($uname,$udom,$query,%filters)=@_;
 7323:     my $uhome=&homeserver($uname,$udom);
 7324:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 7325:     my $uhost=&hostname($uhome);
 7326:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 7327:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 7328:                        $uhome);
 7329:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 7330:     return get_query_reply($queryid);
 7331: }
 7332: 
 7333: # -------------------------- Update MySQL table for portfolio file
 7334: 
 7335: sub update_portfolio_table {
 7336:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 7337:     if ($group ne '') {
 7338:         $file_name =~s /^\Q$group\E//;
 7339:     }
 7340:     my $homeserver = &homeserver($uname,$udom);
 7341:     my $queryid=
 7342:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 7343:                ':'.&escape($file_name).':'.$action,$homeserver);
 7344:     my $reply = &get_query_reply($queryid);
 7345:     return $reply;
 7346: }
 7347: 
 7348: # -------------------------- Update MySQL allusers table
 7349: 
 7350: sub update_allusers_table {
 7351:     my ($uname,$udom,$names) = @_;
 7352:     my $homeserver = &homeserver($uname,$udom);
 7353:     my $queryid=
 7354:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 7355:                'lastname='.&escape($names->{'lastname'}).'%%'.
 7356:                'firstname='.&escape($names->{'firstname'}).'%%'.
 7357:                'middlename='.&escape($names->{'middlename'}).'%%'.
 7358:                'generation='.&escape($names->{'generation'}).'%%'.
 7359:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 7360:                'id='.&escape($names->{'id'}),$homeserver);
 7361:     return;
 7362: }
 7363: 
 7364: # ------- Request retrieval of institutional classlists for course(s)
 7365: 
 7366: sub fetch_enrollment_query {
 7367:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 7368:     my $homeserver;
 7369:     my $maxtries = 1;
 7370:     if ($context eq 'automated') {
 7371:         $homeserver = $perlvar{'lonHostID'};
 7372:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 7373:     } else {
 7374:         $homeserver = &homeserver($cnum,$dom);
 7375:     }
 7376:     my $host=&hostname($homeserver);
 7377:     my $cmd = '';
 7378:     foreach my $affiliate (keys(%{$affiliatesref})) {
 7379:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 7380:     }
 7381:     $cmd =~ s/%%$//;
 7382:     $cmd = &escape($cmd);
 7383:     my $query = 'fetchenrollment';
 7384:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 7385:     unless ($queryid=~/^\Q$host\E\_/) { 
 7386:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 7387:         return 'error: '.$queryid;
 7388:     }
 7389:     my $reply = &get_query_reply($queryid);
 7390:     my $tries = 1;
 7391:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 7392:         $reply = &get_query_reply($queryid);
 7393:         $tries ++;
 7394:     }
 7395:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 7396:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 7397:     } else {
 7398:         my @responses = split(/:/,$reply);
 7399:         if ($homeserver eq $perlvar{'lonHostID'}) {
 7400:             foreach my $line (@responses) {
 7401:                 my ($key,$value) = split(/=/,$line,2);
 7402:                 $$replyref{$key} = $value;
 7403:             }
 7404:         } else {
 7405:             my $pathname = LONCAPA::tempdir();
 7406:             foreach my $line (@responses) {
 7407:                 my ($key,$value) = split(/=/,$line);
 7408:                 $$replyref{$key} = $value;
 7409:                 if ($value > 0) {
 7410:                     foreach my $item (@{$$affiliatesref{$key}}) {
 7411:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 7412:                         my $destname = $pathname.'/'.$filename;
 7413:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 7414:                         if ($xml_classlist =~ /^error/) {
 7415:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 7416:                         } else {
 7417:                             if ( open(FILE,">$destname") ) {
 7418:                                 print FILE &unescape($xml_classlist);
 7419:                                 close(FILE);
 7420:                             } else {
 7421:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 7422:                             }
 7423:                         }
 7424:                     }
 7425:                 }
 7426:             }
 7427:         }
 7428:         return 'ok';
 7429:     }
 7430:     return 'error';
 7431: }
 7432: 
 7433: sub get_query_reply {
 7434:     my $queryid=shift;
 7435:     my $replyfile=LONCAPA::tempdir().$queryid;
 7436:     my $reply='';
 7437:     for (1..100) {
 7438: 	sleep 2;
 7439:         if (-e $replyfile.'.end') {
 7440: 	    if (open(my $fh,$replyfile)) {
 7441: 		$reply = join('',<$fh>);
 7442: 		close($fh);
 7443: 	   } else { return 'error: reply_file_error'; }
 7444:            return &unescape($reply);
 7445: 	}
 7446:     }
 7447:     return 'timeout:'.$queryid;
 7448: }
 7449: 
 7450: sub courselog_query {
 7451: #
 7452: # possible filters:
 7453: # url: url or symb
 7454: # username
 7455: # domain
 7456: # action: view, submit, grade
 7457: # start: timestamp
 7458: # end: timestamp
 7459: #
 7460:     my (%filters)=@_;
 7461:     unless ($env{'request.course.id'}) { return 'no_course'; }
 7462:     if ($filters{'url'}) {
 7463: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 7464:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 7465:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 7466:     }
 7467:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7468:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7469:     return &log_query($cname,$cdom,'courselog',%filters);
 7470: }
 7471: 
 7472: sub userlog_query {
 7473: #
 7474: # possible filters:
 7475: # action: log check role
 7476: # start: timestamp
 7477: # end: timestamp
 7478: #
 7479:     my ($uname,$udom,%filters)=@_;
 7480:     return &log_query($uname,$udom,'userlog',%filters);
 7481: }
 7482: 
 7483: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 7484: 
 7485: sub auto_run {
 7486:     my ($cnum,$cdom) = @_;
 7487:     my $response = 0;
 7488:     my $settings;
 7489:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 7490:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 7491:         $settings = $domconfig{'autoenroll'};
 7492:         if ($settings->{'run'} eq '1') {
 7493:             $response = 1;
 7494:         }
 7495:     } else {
 7496:         my $homeserver;
 7497:         if (&is_course($cdom,$cnum)) {
 7498:             $homeserver = &homeserver($cnum,$cdom);
 7499:         } else {
 7500:             $homeserver = &domain($cdom,'primary');
 7501:         }
 7502:         if ($homeserver ne 'no_host') {
 7503:             $response = &reply('autorun:'.$cdom,$homeserver);
 7504:         }
 7505:     }
 7506:     return $response;
 7507: }
 7508: 
 7509: sub auto_get_sections {
 7510:     my ($cnum,$cdom,$inst_coursecode) = @_;
 7511:     my $homeserver;
 7512:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 7513:         $homeserver = &homeserver($cnum,$cdom);
 7514:     }
 7515:     if (!defined($homeserver)) { 
 7516:         if ($cdom =~ /^$match_domain$/) {
 7517:             $homeserver = &domain($cdom,'primary');
 7518:         }
 7519:     }
 7520:     my @secs;
 7521:     if (defined($homeserver)) {
 7522:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 7523:         unless ($response eq 'refused') {
 7524:             @secs = split(/:/,$response);
 7525:         }
 7526:     }
 7527:     return @secs;
 7528: }
 7529: 
 7530: sub auto_new_course {
 7531:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 7532:     my $homeserver = &homeserver($cnum,$cdom);
 7533:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 7534:     return $response;
 7535: }
 7536: 
 7537: sub auto_validate_courseID {
 7538:     my ($cnum,$cdom,$inst_course_id) = @_;
 7539:     my $homeserver = &homeserver($cnum,$cdom);
 7540:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 7541:     return $response;
 7542: }
 7543: 
 7544: sub auto_validate_instcode {
 7545:     my ($cnum,$cdom,$instcode,$owner) = @_;
 7546:     my ($homeserver,$response);
 7547:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 7548:         $homeserver = &homeserver($cnum,$cdom);
 7549:     }
 7550:     if (!defined($homeserver)) {
 7551:         if ($cdom =~ /^$match_domain$/) {
 7552:             $homeserver = &domain($cdom,'primary');
 7553:         }
 7554:     }
 7555:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 7556:                         &escape($instcode).':'.&escape($owner),$homeserver));
 7557:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
 7558:     return ($outcome,$description,$defaultcredits);
 7559: }
 7560: 
 7561: sub auto_create_password {
 7562:     my ($cnum,$cdom,$authparam,$udom) = @_;
 7563:     my ($homeserver,$response);
 7564:     my $create_passwd = 0;
 7565:     my $authchk = '';
 7566:     if ($udom =~ /^$match_domain$/) {
 7567:         $homeserver = &domain($udom,'primary');
 7568:     }
 7569:     if ($homeserver eq '') {
 7570:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 7571:             $homeserver = &homeserver($cnum,$cdom);
 7572:         }
 7573:     }
 7574:     if ($homeserver eq '') {
 7575:         $authchk = 'nodomain';
 7576:     } else {
 7577:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 7578:         if ($response eq 'refused') {
 7579:             $authchk = 'refused';
 7580:         } else {
 7581:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 7582:         }
 7583:     }
 7584:     return ($authparam,$create_passwd,$authchk);
 7585: }
 7586: 
 7587: sub auto_photo_permission {
 7588:     my ($cnum,$cdom,$students) = @_;
 7589:     my $homeserver = &homeserver($cnum,$cdom);
 7590:     my ($outcome,$perm_reqd,$conditions) = 
 7591: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 7592:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7593: 	return (undef,undef);
 7594:     }
 7595:     return ($outcome,$perm_reqd,$conditions);
 7596: }
 7597: 
 7598: sub auto_checkphotos {
 7599:     my ($uname,$udom,$pid) = @_;
 7600:     my $homeserver = &homeserver($uname,$udom);
 7601:     my ($result,$resulttype);
 7602:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 7603: 				   &escape($uname).':'.&escape($pid),
 7604: 				   $homeserver));
 7605:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7606: 	return (undef,undef);
 7607:     }
 7608:     if ($outcome) {
 7609:         ($result,$resulttype) = split(/:/,$outcome);
 7610:     } 
 7611:     return ($result,$resulttype);
 7612: }
 7613: 
 7614: sub auto_photochoice {
 7615:     my ($cnum,$cdom) = @_;
 7616:     my $homeserver = &homeserver($cnum,$cdom);
 7617:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 7618: 						       &escape($cdom),
 7619: 						       $homeserver)));
 7620:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7621: 	return (undef,undef);
 7622:     }
 7623:     return ($update,$comment);
 7624: }
 7625: 
 7626: sub auto_photoupdate {
 7627:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 7628:     my $homeserver = &homeserver($cnum,$dom);
 7629:     my $host=&hostname($homeserver);
 7630:     my $cmd = '';
 7631:     my $maxtries = 1;
 7632:     foreach my $affiliate (keys(%{$affiliatesref})) {
 7633:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 7634:     }
 7635:     $cmd =~ s/%%$//;
 7636:     $cmd = &escape($cmd);
 7637:     my $query = 'institutionalphotos';
 7638:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 7639:     unless ($queryid=~/^\Q$host\E\_/) {
 7640:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 7641:         return 'error: '.$queryid;
 7642:     }
 7643:     my $reply = &get_query_reply($queryid);
 7644:     my $tries = 1;
 7645:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 7646:         $reply = &get_query_reply($queryid);
 7647:         $tries ++;
 7648:     }
 7649:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 7650:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 7651:     } else {
 7652:         my @responses = split(/:/,$reply);
 7653:         my $outcome = shift(@responses); 
 7654:         foreach my $item (@responses) {
 7655:             my ($key,$value) = split(/=/,$item);
 7656:             $$photo{$key} = $value;
 7657:         }
 7658:         return $outcome;
 7659:     }
 7660:     return 'error';
 7661: }
 7662: 
 7663: sub auto_instcode_format {
 7664:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 7665: 	$cat_order) = @_;
 7666:     my $courses = '';
 7667:     my @homeservers;
 7668:     if ($caller eq 'global') {
 7669: 	my %servers = &get_servers($codedom,'library');
 7670: 	foreach my $tryserver (keys(%servers)) {
 7671: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7672: 		push(@homeservers,$tryserver);
 7673: 	    }
 7674:         }
 7675:     } elsif ($caller eq 'requests') {
 7676:         if ($codedom =~ /^$match_domain$/) {
 7677:             my $chome = &domain($codedom,'primary');
 7678:             unless ($chome eq 'no_host') {
 7679:                 push(@homeservers,$chome);
 7680:             }
 7681:         }
 7682:     } else {
 7683:         push(@homeservers,&homeserver($caller,$codedom));
 7684:     }
 7685:     foreach my $code (keys(%{$instcodes})) {
 7686:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 7687:     }
 7688:     chop($courses);
 7689:     my $ok_response = 0;
 7690:     my $response;
 7691:     while (@homeservers > 0 && $ok_response == 0) {
 7692:         my $server = shift(@homeservers); 
 7693:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 7694:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 7695:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 7696: 		split(/:/,$response);
 7697:             %{$codes} = (%{$codes},&str2hash($codes_str));
 7698:             push(@{$codetitles},&str2array($codetitles_str));
 7699:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 7700:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 7701:             $ok_response = 1;
 7702:         }
 7703:     }
 7704:     if ($ok_response) {
 7705:         return 'ok';
 7706:     } else {
 7707:         return $response;
 7708:     }
 7709: }
 7710: 
 7711: sub auto_instcode_defaults {
 7712:     my ($domain,$returnhash,$code_order) = @_;
 7713:     my @homeservers;
 7714: 
 7715:     my %servers = &get_servers($domain,'library');
 7716:     foreach my $tryserver (keys(%servers)) {
 7717: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7718: 	    push(@homeservers,$tryserver);
 7719: 	}
 7720:     }
 7721: 
 7722:     my $response;
 7723:     foreach my $server (@homeservers) {
 7724:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 7725:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 7726: 	
 7727: 	foreach my $pair (split(/\&/,$response)) {
 7728: 	    my ($name,$value)=split(/\=/,$pair);
 7729: 	    if ($name eq 'code_order') {
 7730: 		@{$code_order} = split(/\&/,&unescape($value));
 7731: 	    } else {
 7732: 		$returnhash->{&unescape($name)}=&unescape($value);
 7733: 	    }
 7734: 	}
 7735: 	return 'ok';
 7736:     }
 7737: 
 7738:     return $response;
 7739: }
 7740: 
 7741: sub auto_possible_instcodes {
 7742:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 7743:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 7744:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 7745:         return;
 7746:     }
 7747:     my (@homeservers,$uhome);
 7748:     if (defined(&domain($domain,'primary'))) {
 7749:         $uhome=&domain($domain,'primary');
 7750:         push(@homeservers,&domain($domain,'primary'));
 7751:     } else {
 7752:         my %servers = &get_servers($domain,'library');
 7753:         foreach my $tryserver (keys(%servers)) {
 7754:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7755:                 push(@homeservers,$tryserver);
 7756:             }
 7757:         }
 7758:     }
 7759:     my $response;
 7760:     foreach my $server (@homeservers) {
 7761:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 7762:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 7763:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 7764:             split(':',$response);
 7765:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 7766:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 7767:         foreach my $item (split('&',$cat_title)) {   
 7768:             my ($name,$value)=split('=',$item);
 7769:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 7770:         }
 7771:         foreach my $item (split('&',$cat_order)) {
 7772:             my ($name,$value)=split('=',$item);
 7773:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 7774:         }
 7775:         return 'ok';
 7776:     }
 7777:     return $response;
 7778: }
 7779: 
 7780: sub auto_courserequest_checks {
 7781:     my ($dom) = @_;
 7782:     my ($homeserver,%validations);
 7783:     if ($dom =~ /^$match_domain$/) {
 7784:         $homeserver = &domain($dom,'primary');
 7785:     }
 7786:     unless ($homeserver eq 'no_host') {
 7787:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 7788:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 7789:             my @items = split(/&/,$response);
 7790:             foreach my $item (@items) {
 7791:                 my ($key,$value) = split('=',$item);
 7792:                 $validations{&unescape($key)} = &thaw_unescape($value);
 7793:             }
 7794:         }
 7795:     }
 7796:     return %validations; 
 7797: }
 7798: 
 7799: sub auto_courserequest_validation {
 7800:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
 7801:     my ($homeserver,$response);
 7802:     if ($dom =~ /^$match_domain$/) {
 7803:         $homeserver = &domain($dom,'primary');
 7804:     }
 7805:     unless ($homeserver eq 'no_host') {  
 7806:           
 7807:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 7808:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 7809:                                     ':'.&escape($instcode).':'.&escape($instseclist),
 7810:                                     $homeserver));
 7811:     }
 7812:     return $response;
 7813: }
 7814: 
 7815: sub auto_validate_class_sec {
 7816:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 7817:     my $homeserver = &homeserver($cnum,$cdom);
 7818:     my $ownerlist;
 7819:     if (ref($owners) eq 'ARRAY') {
 7820:         $ownerlist = join(',',@{$owners});
 7821:     } else {
 7822:         $ownerlist = $owners;
 7823:     }
 7824:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 7825:                         &escape($ownerlist).':'.$cdom,$homeserver);
 7826:     return $response;
 7827: }
 7828: 
 7829: # ------------------------------------------------------- Course Group routines
 7830: 
 7831: sub get_coursegroups {
 7832:     my ($cdom,$cnum,$group,$namespace) = @_;
 7833:     return(&dump($namespace,$cdom,$cnum,$group));
 7834: }
 7835: 
 7836: sub modify_coursegroup {
 7837:     my ($cdom,$cnum,$groupsettings) = @_;
 7838:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 7839: }
 7840: 
 7841: sub toggle_coursegroup_status {
 7842:     my ($cdom,$cnum,$group,$action) = @_;
 7843:     my ($from_namespace,$to_namespace);
 7844:     if ($action eq 'delete') {
 7845:         $from_namespace = 'coursegroups';
 7846:         $to_namespace = 'deleted_groups';
 7847:     } else {
 7848:         $from_namespace = 'deleted_groups';
 7849:         $to_namespace = 'coursegroups';
 7850:     }
 7851:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 7852:     if (my $tmp = &error(%curr_group)) {
 7853:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 7854:         return ('read error',$tmp);
 7855:     } else {
 7856:         my %savedsettings = %curr_group; 
 7857:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 7858:         my $deloutcome;
 7859:         if ($result eq 'ok') {
 7860:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 7861:         } else {
 7862:             return ('write error',$result);
 7863:         }
 7864:         if ($deloutcome eq 'ok') {
 7865:             return 'ok';
 7866:         } else {
 7867:             return ('delete error',$deloutcome);
 7868:         }
 7869:     }
 7870: }
 7871: 
 7872: sub modify_group_roles {
 7873:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 7874:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 7875:     my $role = 'gr/'.&escape($userprivs);
 7876:     my ($uname,$udom) = split(/:/,$user);
 7877:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 7878:     if ($result eq 'ok') {
 7879:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 7880:     }
 7881:     return $result;
 7882: }
 7883: 
 7884: sub modify_coursegroup_membership {
 7885:     my ($cdom,$cnum,$membership) = @_;
 7886:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 7887:     return $result;
 7888: }
 7889: 
 7890: sub get_active_groups {
 7891:     my ($udom,$uname,$cdom,$cnum) = @_;
 7892:     my $now = time;
 7893:     my %groups = ();
 7894:     foreach my $key (keys(%env)) {
 7895:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 7896:             my ($start,$end) = split(/\./,$env{$key});
 7897:             if (($end!=0) && ($end<$now)) { next; }
 7898:             if (($start!=0) && ($start>$now)) { next; }
 7899:             if ($1 eq $cdom && $2 eq $cnum) {
 7900:                 $groups{$3} = $env{$key} ;
 7901:             }
 7902:         }
 7903:     }
 7904:     return %groups;
 7905: }
 7906: 
 7907: sub get_group_membership {
 7908:     my ($cdom,$cnum,$group) = @_;
 7909:     return(&dump('groupmembership',$cdom,$cnum,$group));
 7910: }
 7911: 
 7912: sub get_users_groups {
 7913:     my ($udom,$uname,$courseid) = @_;
 7914:     my @usersgroups;
 7915:     my $cachetime=1800;
 7916: 
 7917:     my $hashid="$udom:$uname:$courseid";
 7918:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 7919:     if (defined($cached)) {
 7920:         @usersgroups = split(/:/,$grouplist);
 7921:     } else {  
 7922:         $grouplist = '';
 7923:         my $courseurl = &courseid_to_courseurl($courseid);
 7924:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 7925:         my $access_end = $env{'course.'.$courseid.
 7926:                               '.default_enrollment_end_date'};
 7927:         my $now = time;
 7928:         foreach my $key (keys(%roleshash)) {
 7929:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 7930:                 my $group = $1;
 7931:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 7932:                     my $start = $2;
 7933:                     my $end = $1;
 7934:                     if ($start == -1) { next; } # deleted from group
 7935:                     if (($start!=0) && ($start>$now)) { next; }
 7936:                     if (($end!=0) && ($end<$now)) {
 7937:                         if ($access_end && $access_end < $now) {
 7938:                             if ($access_end - $end < 86400) {
 7939:                                 push(@usersgroups,$group);
 7940:                             }
 7941:                         }
 7942:                         next;
 7943:                     }
 7944:                     push(@usersgroups,$group);
 7945:                 }
 7946:             }
 7947:         }
 7948:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 7949:         $grouplist = join(':',@usersgroups);
 7950:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 7951:     }
 7952:     return @usersgroups;
 7953: }
 7954: 
 7955: sub devalidate_getgroups_cache {
 7956:     my ($udom,$uname,$cdom,$cnum)=@_;
 7957:     my $courseid = $cdom.'_'.$cnum;
 7958: 
 7959:     my $hashid="$udom:$uname:$courseid";
 7960:     &devalidate_cache_new('getgroups',$hashid);
 7961: }
 7962: 
 7963: # ------------------------------------------------------------------ Plain Text
 7964: 
 7965: sub plaintext {
 7966:     my ($short,$type,$cid,$forcedefault) = @_;
 7967:     if ($short =~ m{^cr/}) {
 7968: 	return (split('/',$short))[-1];
 7969:     }
 7970:     if (!defined($cid)) {
 7971:         $cid = $env{'request.course.id'};
 7972:     }
 7973:     my %rolenames = (
 7974:                       Course    => 'std',
 7975:                       Community => 'alt1',
 7976:                     );
 7977:     if ($cid ne '') {
 7978:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 7979:             unless ($forcedefault) {
 7980:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 7981:                 &Apache::lonlocal::mt_escape(\$roletext);
 7982:                 return &Apache::lonlocal::mt($roletext);
 7983:             }
 7984:         }
 7985:     }
 7986:     if ((defined($type)) && (defined($rolenames{$type})) &&
 7987:         (defined($rolenames{$type})) && 
 7988:         (defined($prp{$short}{$rolenames{$type}}))) {
 7989:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 7990:     } elsif ($cid ne '') {
 7991:         my $crstype = $env{'course.'.$cid.'.type'};
 7992:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
 7993:             (defined($prp{$short}{$rolenames{$crstype}}))) {
 7994:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
 7995:         }
 7996:     }
 7997:     return &Apache::lonlocal::mt($prp{$short}{'std'});
 7998: }
 7999: 
 8000: # ----------------------------------------------------------------- Assign Role
 8001: 
 8002: sub assignrole {
 8003:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 8004:         $context)=@_;
 8005:     my $mrole;
 8006:     if ($role =~ /^cr\//) {
 8007:         my $cwosec=$url;
 8008:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 8009: 	unless (&allowed('ccr',$cwosec)) {
 8010:            my $refused = 1;
 8011:            if ($context eq 'requestcourses') {
 8012:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 8013:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
 8014:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
 8015:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 8016:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 8017:                            if ($crsenv{'internal.courseowner'} eq
 8018:                                $env{'user.name'}.':'.$env{'user.domain'}) {
 8019:                                $refused = '';
 8020:                            }
 8021:                        }
 8022:                    }
 8023:                }
 8024:            }
 8025:            if ($refused) {
 8026:                &logthis('Refused custom assignrole: '.
 8027:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
 8028:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
 8029:                return 'refused';
 8030:            }
 8031:         }
 8032:         $mrole='cr';
 8033:     } elsif ($role =~ /^gr\//) {
 8034:         my $cwogrp=$url;
 8035:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 8036:         unless (&allowed('mdg',$cwogrp)) {
 8037:             &logthis('Refused group assignrole: '.
 8038:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 8039:                     $env{'user.name'}.' at '.$env{'user.domain'});
 8040:             return 'refused';
 8041:         }
 8042:         $mrole='gr';
 8043:     } else {
 8044:         my $cwosec=$url;
 8045:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 8046:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 8047:             my $refused;
 8048:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 8049:                 if (!(&allowed('c'.$role,$url))) {
 8050:                     $refused = 1;
 8051:                 }
 8052:             } else {
 8053:                 $refused = 1;
 8054:             }
 8055:             if ($refused) {
 8056:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 8057:                 if (!$selfenroll && $context eq 'course') {
 8058:                     my %crsenv;
 8059:                     if ($role eq 'cc' || $role eq 'co') {
 8060:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 8061:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
 8062:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
 8063:                                 if ($crsenv{'internal.courseowner'} eq 
 8064:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 8065:                                     $refused = '';
 8066:                                 }
 8067:                             }
 8068:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
 8069:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
 8070:                                 if ($crsenv{'internal.courseowner'} eq 
 8071:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 8072:                                     $refused = '';
 8073:                                 }
 8074:                             }
 8075:                         }
 8076:                     }
 8077:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 8078:                     $refused = '';
 8079:                 } elsif ($context eq 'requestcourses') {
 8080:                     my @possroles = ('st','ta','ep','in','cc','co');
 8081:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
 8082:                         my $wrongcc;
 8083:                         if ($cnum =~ /^$match_community$/) {
 8084:                             $wrongcc = 1 if ($role eq 'cc');
 8085:                         } else {
 8086:                             $wrongcc = 1 if ($role eq 'co');
 8087:                         }
 8088:                         unless ($wrongcc) {
 8089:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 8090:                             if ($crsenv{'internal.courseowner'} eq 
 8091:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
 8092:                                 $refused = '';
 8093:                             }
 8094:                         }
 8095:                     }
 8096:                 } elsif ($context eq 'requestauthor') {
 8097:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
 8098:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
 8099:                         if ($env{'environment.requestauthor'} eq 'automatic') {
 8100:                             $refused = '';
 8101:                         } else {
 8102:                             my %domdefaults = &get_domain_defaults($udom);
 8103:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
 8104:                                 my $checkbystatus;
 8105:                                 if ($env{'user.adv'}) { 
 8106:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
 8107:                                     if ($disposition eq 'automatic') {
 8108:                                         $refused = '';
 8109:                                     } elsif ($disposition eq '') {
 8110:                                         $checkbystatus = 1;
 8111:                                     } 
 8112:                                 } else {
 8113:                                     $checkbystatus = 1;
 8114:                                 }
 8115:                                 if ($checkbystatus) {
 8116:                                     if ($env{'environment.inststatus'}) {
 8117:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
 8118:                                         foreach my $type (@inststatuses) {
 8119:                                             if (($type ne '') &&
 8120:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
 8121:                                                 $refused = '';
 8122:                                             }
 8123:                                         }
 8124:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
 8125:                                         $refused = '';
 8126:                                     }
 8127:                                 }
 8128:                             }
 8129:                         }
 8130:                     }
 8131:                 }
 8132:                 if ($refused) {
 8133:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 8134:                              ' '.$role.' '.$end.' '.$start.' by '.
 8135: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 8136:                     return 'refused';
 8137:                 }
 8138:             }
 8139:         } elsif ($role eq 'au') {
 8140:             if ($url ne '/'.$udom.'/') {
 8141:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
 8142:                          ' to assign author role for '.$uname.':'.$udom.
 8143:                          ' in domain: '.$url.' refused (wrong domain).');
 8144:                 return 'refused';
 8145:             }
 8146:         }
 8147:         $mrole=$role;
 8148:     }
 8149:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 8150:                 "$udom:$uname:$url".'_'."$mrole=$role";
 8151:     if ($end) { $command.='_'.$end; }
 8152:     if ($start) {
 8153: 	if ($end) { 
 8154:            $command.='_'.$start; 
 8155:         } else {
 8156:            $command.='_0_'.$start;
 8157:         }
 8158:     }
 8159:     my $origstart = $start;
 8160:     my $origend = $end;
 8161:     my $delflag;
 8162: # actually delete
 8163:     if ($deleteflag) {
 8164: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 8165: # modify command to delete the role
 8166:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 8167:                 "$udom:$uname:$url".'_'."$mrole";
 8168: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 8169: # set start and finish to negative values for userrolelog
 8170:            $start=-1;
 8171:            $end=-1;
 8172:            $delflag = 1;
 8173:         }
 8174:     }
 8175: # send command
 8176:     my $answer=&reply($command,&homeserver($uname,$udom));
 8177: # log new user role if status is ok
 8178:     if ($answer eq 'ok') {
 8179: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 8180:         if (($role eq 'cc') || ($role eq 'in') ||
 8181:             ($role eq 'ep') || ($role eq 'ad') ||
 8182:             ($role eq 'ta') || ($role eq 'st') ||
 8183:             ($role=~/^cr/) || ($role eq 'gr') ||
 8184:             ($role eq 'co')) {
 8185: # for course roles, perform group memberships changes triggered by role change.
 8186:             unless ($role =~ /^gr/) {
 8187:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 8188:                                                  $origstart,$selfenroll,$context);
 8189:             }
 8190:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 8191:                            $selfenroll,$context);
 8192:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
 8193:                  ($role eq 'au') || ($role eq 'dc')) {
 8194:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 8195:                            $context);
 8196:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
 8197:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 8198:                              $context); 
 8199:         }
 8200:         if ($role eq 'cc') {
 8201:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
 8202:         }
 8203:     }
 8204:     return $answer;
 8205: }
 8206: 
 8207: sub autoupdate_coowners {
 8208:     my ($url,$end,$start,$uname,$udom) = @_;
 8209:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
 8210:     if (($cdom ne '') && ($cnum ne '')) {
 8211:         my $now = time;
 8212:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
 8213:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
 8214:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
 8215:             my $instcode = $coursehash{'internal.coursecode'};
 8216:             if ($instcode ne '') {
 8217:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
 8218:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
 8219:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
 8220:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
 8221:                         if ($result eq 'valid') {
 8222:                             if ($coursehash{'internal.co-owners'}) {
 8223:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 8224:                                     push(@newcoowners,$coowner);
 8225:                                 }
 8226:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
 8227:                                     push(@newcoowners,$uname.':'.$udom);
 8228:                                 }
 8229:                                 @newcoowners = sort(@newcoowners);
 8230:                             } else {
 8231:                                 push(@newcoowners,$uname.':'.$udom);
 8232:                             }
 8233:                         } else {
 8234:                             if ($coursehash{'internal.co-owners'}) {
 8235:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 8236:                                     unless ($coowner eq $uname.':'.$udom) {
 8237:                                         push(@newcoowners,$coowner);
 8238:                                     }
 8239:                                 }
 8240:                                 unless (@newcoowners > 0) {
 8241:                                     $delcoowners = 1;
 8242:                                     $coowners = '';
 8243:                                 }
 8244:                             }
 8245:                         }
 8246:                         if (@newcoowners || $delcoowners) {
 8247:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
 8248:                                             $delcoowners,@newcoowners);
 8249:                         }
 8250:                     }
 8251:                 }
 8252:             }
 8253:         }
 8254:     }
 8255: }
 8256: 
 8257: sub store_coowners {
 8258:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
 8259:     my $cid = $cdom.'_'.$cnum;
 8260:     my ($coowners,$delresult,$putresult);
 8261:     if (@newcoowners) {
 8262:         $coowners = join(',',@newcoowners);
 8263:         my %coownershash = (
 8264:                             'internal.co-owners' => $coowners,
 8265:                            );
 8266:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
 8267:         if ($putresult eq 'ok') {
 8268:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
 8269:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
 8270:             }
 8271:         }
 8272:     }
 8273:     if ($delcoowners) {
 8274:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
 8275:         if ($delresult eq 'ok') {
 8276:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
 8277:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
 8278:             }
 8279:         }
 8280:     }
 8281:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
 8282:         my %crsinfo =
 8283:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 8284:         if (ref($crsinfo{$cid}) eq 'HASH') {
 8285:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
 8286:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
 8287:         }
 8288:     }
 8289: }
 8290: 
 8291: # -------------------------------------------------- Modify user authentication
 8292: # Overrides without validation
 8293: 
 8294: sub modifyuserauth {
 8295:     my ($udom,$uname,$umode,$upass)=@_;
 8296:     my $uhome=&homeserver($uname,$udom);
 8297:     unless (&allowed('mau',$udom)) { return 'refused'; }
 8298:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 8299:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 8300:              ' in domain '.$env{'request.role.domain'});  
 8301:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 8302: 		     &escape($upass),$uhome);
 8303:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 8304:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 8305:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 8306:     &log($udom,,$uname,$uhome,
 8307:         'Authentication changed by '.$env{'user.domain'}.', '.
 8308:                                      $env{'user.name'}.', '.$umode.
 8309:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 8310:     unless ($reply eq 'ok') {
 8311:         &logthis('Authentication mode error: '.$reply);
 8312: 	return 'error: '.$reply;
 8313:     }   
 8314:     return 'ok';
 8315: }
 8316: 
 8317: # --------------------------------------------------------------- Modify a user
 8318: 
 8319: sub modifyuser {
 8320:     my ($udom,    $uname, $uid,
 8321:         $umode,   $upass, $first,
 8322:         $middle,  $last,  $gene,
 8323:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
 8324:     $udom= &LONCAPA::clean_domain($udom);
 8325:     $uname=&LONCAPA::clean_username($uname);
 8326:     my $showcandelete = 'none';
 8327:     if (ref($candelete) eq 'ARRAY') {
 8328:         if (@{$candelete} > 0) {
 8329:             $showcandelete = join(', ',@{$candelete});
 8330:         }
 8331:     }
 8332:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 8333:              $umode.', '.$first.', '.$middle.', '.
 8334: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
 8335:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 8336:                                      ' desiredhome not specified'). 
 8337:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 8338:              ' in domain '.$env{'request.role.domain'});
 8339:     my $uhome=&homeserver($uname,$udom,'true');
 8340:     my $newuser;
 8341:     if ($uhome eq 'no_host') {
 8342:         $newuser = 1;
 8343:     }
 8344: # ----------------------------------------------------------------- Create User
 8345:     if (($uhome eq 'no_host') && 
 8346: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 8347:         my $unhome='';
 8348:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 8349:             $unhome = $desiredhome;
 8350: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 8351: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 8352:         } else { # load balancing routine for determining $unhome
 8353:             my $loadm=10000000;
 8354: 	    my %servers = &get_servers($udom,'library');
 8355: 	    foreach my $tryserver (keys(%servers)) {
 8356: 		my $answer=reply('load',$tryserver);
 8357: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 8358: 		    $loadm=$answer;
 8359: 		    $unhome=$tryserver;
 8360: 		}
 8361: 	    }
 8362:         }
 8363:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 8364: 	    return 'error: unable to find a home server for '.$uname.
 8365:                    ' in domain '.$udom;
 8366:         }
 8367:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 8368:                          &escape($upass),$unhome);
 8369: 	unless ($reply eq 'ok') {
 8370:             return 'error: '.$reply;
 8371:         }   
 8372:         $uhome=&homeserver($uname,$udom,'true');
 8373:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 8374: 	    return 'error: unable verify users home machine.';
 8375:         }
 8376:     }   # End of creation of new user
 8377: # ---------------------------------------------------------------------- Add ID
 8378:     if ($uid) {
 8379:        $uid=~tr/A-Z/a-z/;
 8380:        my %uidhash=&idrget($udom,$uname);
 8381:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 8382:          && (!$forceid)) {
 8383: 	  unless ($uid eq $uidhash{$uname}) {
 8384: 	      return 'error: user id "'.$uid.'" does not match '.
 8385:                   'current user id "'.$uidhash{$uname}.'".';
 8386:           }
 8387:        } else {
 8388: 	  &idput($udom,($uname => $uid));
 8389:        }
 8390:     }
 8391: # -------------------------------------------------------------- Add names, etc
 8392:     my @tmp=&get('environment',
 8393: 		   ['firstname','middlename','lastname','generation','id',
 8394:                     'permanentemail','inststatus'],
 8395: 		   $udom,$uname);
 8396:     my (%names,%oldnames);
 8397:     if ($tmp[0] =~ m/^error:.*/) { 
 8398:         %names=(); 
 8399:     } else {
 8400:         %names = @tmp;
 8401:         %oldnames = %names;
 8402:     }
 8403: #
 8404: # If name, email and/or uid are blank (e.g., because an uploaded file
 8405: # of users did not contain them), do not overwrite existing values
 8406: # unless field is in $candelete array ref.  
 8407: #
 8408: 
 8409:     my @fields = ('firstname','middlename','lastname','generation',
 8410:                   'permanentemail','id');
 8411:     my %newvalues;
 8412:     if (ref($candelete) eq 'ARRAY') {
 8413:         foreach my $field (@fields) {
 8414:             if (grep(/^\Q$field\E$/,@{$candelete})) {
 8415:                 if ($field eq 'firstname') {
 8416:                     $names{$field} = $first;
 8417:                 } elsif ($field eq 'middlename') {
 8418:                     $names{$field} = $middle;
 8419:                 } elsif ($field eq 'lastname') {
 8420:                     $names{$field} = $last;
 8421:                 } elsif ($field eq 'generation') { 
 8422:                     $names{$field} = $gene;
 8423:                 } elsif ($field eq 'permanentemail') {
 8424:                     $names{$field} = $email;
 8425:                 } elsif ($field eq 'id') {
 8426:                     $names{$field}  = $uid;
 8427:                 }
 8428:             }
 8429:         }
 8430:     }
 8431:     if ($first)  { $names{'firstname'}  = $first; }
 8432:     if (defined($middle)) { $names{'middlename'} = $middle; }
 8433:     if ($last)   { $names{'lastname'}   = $last; }
 8434:     if (defined($gene))   { $names{'generation'} = $gene; }
 8435:     if ($email) {
 8436:        $email=~s/[^\w\@\.\-\,]//gs;
 8437:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 8438:     }
 8439:     if ($uid) { $names{'id'}  = $uid; }
 8440:     if (defined($inststatus)) {
 8441:         $names{'inststatus'} = '';
 8442:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
 8443:         if (ref($usertypes) eq 'HASH') {
 8444:             my @okstatuses; 
 8445:             foreach my $item (split(/:/,$inststatus)) {
 8446:                 if (defined($usertypes->{$item})) {
 8447:                     push(@okstatuses,$item);  
 8448:                 }
 8449:             }
 8450:             if (@okstatuses) {
 8451:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
 8452:             }
 8453:         }
 8454:     }
 8455:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
 8456:                  $umode.', '.$first.', '.$middle.', '.
 8457:                  $last.', '.$gene.', '.$email.', '.$inststatus;
 8458:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 8459:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 8460:     } else {
 8461:         $logmsg .= ' during self creation';
 8462:     }
 8463:     my $changed;
 8464:     if ($newuser) {
 8465:         $changed = 1;
 8466:     } else {
 8467:         foreach my $field (@fields) {
 8468:             if ($names{$field} ne $oldnames{$field}) {
 8469:                 $changed = 1;
 8470:                 last;
 8471:             }
 8472:         }
 8473:     }
 8474:     unless ($changed) {
 8475:         $logmsg = 'No changes in user information needed for: '.$logmsg;
 8476:         &logthis($logmsg);
 8477:         return 'ok';
 8478:     }
 8479:     my $reply = &put('environment', \%names, $udom,$uname);
 8480:     if ($reply ne 'ok') { 
 8481:         return 'error: '.$reply;
 8482:     }
 8483:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
 8484:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
 8485:     }
 8486:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 8487:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 8488:     $logmsg = 'Success modifying user '.$logmsg;
 8489:     &logthis($logmsg);
 8490:     return 'ok';
 8491: }
 8492: 
 8493: # -------------------------------------------------------------- Modify student
 8494: 
 8495: sub modifystudent {
 8496:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 8497:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 8498:         $selfenroll,$context,$inststatus,$credits)=@_;
 8499:     if (!$cid) {
 8500: 	unless ($cid=$env{'request.course.id'}) {
 8501: 	    return 'not_in_class';
 8502: 	}
 8503:     }
 8504: # --------------------------------------------------------------- Make the user
 8505:     my $reply=&modifyuser
 8506: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 8507:          $desiredhome,$email,$inststatus);
 8508:     unless ($reply eq 'ok') { return $reply; }
 8509:     # This will cause &modify_student_enrollment to get the uid from the
 8510:     # student's environment
 8511:     $uid = undef if (!$forceid);
 8512:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 8513:                                         $gene,$usec,$end,$start,$type,$locktype,
 8514:                                         $cid,$selfenroll,$context,$credits);
 8515:     return $reply;
 8516: }
 8517: 
 8518: sub modify_student_enrollment {
 8519:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
 8520:         $locktype,$cid,$selfenroll,$context,$credits) = @_;
 8521:     my ($cdom,$cnum,$chome);
 8522:     if (!$cid) {
 8523: 	unless ($cid=$env{'request.course.id'}) {
 8524: 	    return 'not_in_class';
 8525: 	}
 8526: 	$cdom=$env{'course.'.$cid.'.domain'};
 8527: 	$cnum=$env{'course.'.$cid.'.num'};
 8528:     } else {
 8529: 	($cdom,$cnum)=split(/_/,$cid);
 8530:     }
 8531:     $chome=$env{'course.'.$cid.'.home'};
 8532:     if (!$chome) {
 8533: 	$chome=&homeserver($cnum,$cdom);
 8534:     }
 8535:     if (!$chome) { return 'unknown_course'; }
 8536:     # Make sure the user exists
 8537:     my $uhome=&homeserver($uname,$udom);
 8538:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 8539: 	return 'error: no such user';
 8540:     }
 8541:     # Get student data if we were not given enough information
 8542:     if (!defined($first)  || $first  eq '' || 
 8543:         !defined($last)   || $last   eq '' || 
 8544:         !defined($uid)    || $uid    eq '' || 
 8545:         !defined($middle) || $middle eq '' || 
 8546:         !defined($gene)   || $gene   eq '') {
 8547:         # They did not supply us with enough data to enroll the student, so
 8548:         # we need to pick up more information.
 8549:         my %tmp = &get('environment',
 8550:                        ['firstname','middlename','lastname', 'generation','id']
 8551:                        ,$udom,$uname);
 8552: 
 8553:         #foreach my $key (keys(%tmp)) {
 8554:         #    &logthis("key $key = ".$tmp{$key});
 8555:         #}
 8556:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 8557:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 8558:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 8559:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 8560:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 8561:     }
 8562:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 8563:     my $user = "$uname:$udom";
 8564:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
 8565:     my $reply=cput('classlist',
 8566: 		   {$user => 
 8567: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
 8568: 		   $cdom,$cnum);
 8569:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
 8570:         &devalidate_getsection_cache($udom,$uname,$cid);
 8571:     } else { 
 8572: 	return 'error: '.$reply;
 8573:     }
 8574:     # Add student role to user
 8575:     my $uurl='/'.$cid;
 8576:     $uurl=~s/\_/\//g;
 8577:     if ($usec) {
 8578: 	$uurl.='/'.$usec;
 8579:     }
 8580:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
 8581:                              $selfenroll,$context);
 8582:     if ($result ne 'ok') {
 8583:         if ($old_entry{$user} ne '') {
 8584:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
 8585:         } else {
 8586:             $reply = &del('classlist',[$user],$cdom,$cnum);
 8587:         }
 8588:     }
 8589:     return $result; 
 8590: }
 8591: 
 8592: sub format_name {
 8593:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 8594:     my $name;
 8595:     if ($first ne 'lastname') {
 8596: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 8597:     } else {
 8598: 	if ($lastname=~/\S/) {
 8599: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 8600: 	    $name=~s/\s+,/,/;
 8601: 	} else {
 8602: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 8603: 	}
 8604:     }
 8605:     $name=~s/^\s+//;
 8606:     $name=~s/\s+$//;
 8607:     $name=~s/\s+/ /g;
 8608:     return $name;
 8609: }
 8610: 
 8611: # ------------------------------------------------- Write to course preferences
 8612: 
 8613: sub writecoursepref {
 8614:     my ($courseid,%prefs)=@_;
 8615:     $courseid=~s/^\///;
 8616:     $courseid=~s/\_/\//g;
 8617:     my ($cdomain,$cnum)=split(/\//,$courseid);
 8618:     my $chome=homeserver($cnum,$cdomain);
 8619:     if (($chome eq '') || ($chome eq 'no_host')) { 
 8620: 	return 'error: no such course';
 8621:     }
 8622:     my $cstring='';
 8623:     foreach my $pref (keys(%prefs)) {
 8624: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 8625:     }
 8626:     $cstring=~s/\&$//;
 8627:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 8628: }
 8629: 
 8630: # ---------------------------------------------------------- Make/modify course
 8631: 
 8632: sub createcourse {
 8633:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 8634:         $course_owner,$crstype,$cnum,$context,$category)=@_;
 8635:     $url=&declutter($url);
 8636:     my $cid='';
 8637:     if ($context eq 'requestcourses') {
 8638:         my $can_create = 0;
 8639:         my ($ownername,$ownerdom) = split(':',$course_owner);
 8640:         if ($udom eq $ownerdom) {
 8641:             if (&usertools_access($ownername,$ownerdom,$category,undef,
 8642:                                   $context)) {
 8643:                 $can_create = 1;
 8644:             }
 8645:         } else {
 8646:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
 8647:                                            $category);
 8648:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
 8649:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
 8650:                 if (@curr > 0) {
 8651:                     my @options = qw(approval validate autolimit);
 8652:                     my $optregex = join('|',@options);
 8653:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
 8654:                         $can_create = 1;
 8655:                     }
 8656:                 }
 8657:             }
 8658:         }
 8659:         if ($can_create) {
 8660:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
 8661:                 unless (&allowed('ccc',$udom)) {
 8662:                     return 'refused'; 
 8663:                 }
 8664:             }
 8665:         } else {
 8666:             return 'refused';
 8667:         }
 8668:     } elsif (!&allowed('ccc',$udom)) {
 8669:         return 'refused';
 8670:     }
 8671: # --------------------------------------------------------------- Get Unique ID
 8672:     my $uname;
 8673:     if ($cnum =~ /^$match_courseid$/) {
 8674:         my $chome=&homeserver($cnum,$udom,'true');
 8675:         if (($chome eq '') || ($chome eq 'no_host')) {
 8676:             $uname = $cnum;
 8677:         } else {
 8678:             $uname = &generate_coursenum($udom,$crstype);
 8679:         }
 8680:     } else {
 8681:         $uname = &generate_coursenum($udom,$crstype);
 8682:     }
 8683:     return $uname if ($uname =~ /^error/);
 8684: # -------------------------------------------------- Check supplied server name
 8685:     if (!defined($course_server)) {
 8686:         if (defined(&domain($udom,'primary'))) {
 8687:             $course_server = &domain($udom,'primary');
 8688:         } else {
 8689:             $course_server = $env{'user.home'}; 
 8690:         }
 8691:     }
 8692:     my %host_servers =
 8693:         &Apache::lonnet::get_servers($udom,'library');
 8694:     unless ($host_servers{$course_server}) {
 8695:         return 'error: invalid home server for course: '.$course_server;
 8696:     }
 8697: # ------------------------------------------------------------- Make the course
 8698:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 8699:                       $course_server);
 8700:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 8701:     my $uhome=&homeserver($uname,$udom,'true');
 8702:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 8703: 	return 'error: no such course';
 8704:     }
 8705: # ----------------------------------------------------------------- Course made
 8706: # log existence
 8707:     my $now = time;
 8708:     my $newcourse = {
 8709:                     $udom.'_'.$uname => {
 8710:                                      description => $description,
 8711:                                      inst_code   => $inst_code,
 8712:                                      owner       => $course_owner,
 8713:                                      type        => $crstype,
 8714:                                      creator     => $env{'user.name'}.':'.
 8715:                                                     $env{'user.domain'},
 8716:                                      created     => $now,
 8717:                                      context     => $context,
 8718:                                                 },
 8719:                     };
 8720:     &courseidput($udom,$newcourse,$uhome,'notime');
 8721: # set toplevel url
 8722:     my $topurl=$url;
 8723:     unless ($nonstandard) {
 8724: # ------------------------------------------ For standard courses, make top url
 8725:         my $mapurl=&clutter($url);
 8726:         if ($mapurl eq '/res/') { $mapurl=''; }
 8727:         $env{'form.initmap'}=(<<ENDINITMAP);
 8728: <map>
 8729: <resource id="1" type="start"></resource>
 8730: <resource id="2" src="$mapurl"></resource>
 8731: <resource id="3" type="finish"></resource>
 8732: <link index="1" from="1" to="2"></link>
 8733: <link index="2" from="2" to="3"></link>
 8734: </map>
 8735: ENDINITMAP
 8736:         $topurl=&declutter(
 8737:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 8738:                           );
 8739:     }
 8740: # ----------------------------------------------------------- Write preferences
 8741:     &writecoursepref($udom.'_'.$uname,
 8742:                      ('description'              => $description,
 8743:                       'url'                      => $topurl,
 8744:                       'internal.creator'         => $env{'user.name'}.':'.
 8745:                                                     $env{'user.domain'},
 8746:                       'internal.created'         => $now,
 8747:                       'internal.creationcontext' => $context)
 8748:                     );
 8749:     return '/'.$udom.'/'.$uname;
 8750: }
 8751: 
 8752: # ------------------------------------------------------------------- Create ID
 8753: sub generate_coursenum {
 8754:     my ($udom,$crstype) = @_;
 8755:     my $domdesc = &domain($udom);
 8756:     return 'error: invalid domain' if ($domdesc eq '');
 8757:     my $first;
 8758:     if ($crstype eq 'Community') {
 8759:         $first = '0';
 8760:     } else {
 8761:         $first = int(1+rand(9)); 
 8762:     } 
 8763:     my $uname=$first.
 8764:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 8765:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
 8766:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 8767: # ----------------------------------------------- Make sure that does not exist
 8768:     my $uhome=&homeserver($uname,$udom,'true');
 8769:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
 8770:         if ($crstype eq 'Community') {
 8771:             $first = '0';
 8772:         } else {
 8773:             $first = int(1+rand(9));
 8774:         }
 8775:         $uname=$first.
 8776:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 8777:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
 8778:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 8779:         $uhome=&homeserver($uname,$udom,'true');
 8780:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
 8781:             return 'error: unable to generate unique course-ID';
 8782:         }
 8783:     }
 8784:     return $uname;
 8785: }
 8786: 
 8787: sub is_course {
 8788:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
 8789:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
 8790: 
 8791:     return unless $cdom and $cnum;
 8792: 
 8793:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
 8794:         '.');
 8795: 
 8796:     return unless(exists($courses{$cdom.'_'.$cnum}));
 8797:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
 8798: }
 8799: 
 8800: sub store_userdata {
 8801:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
 8802:     my $result;
 8803:     if ($datakey ne '') {
 8804:         if (ref($storehash) eq 'HASH') {
 8805:             if ($udom eq '' || $uname eq '') {
 8806:                 $udom = $env{'user.domain'};
 8807:                 $uname = $env{'user.name'};
 8808:             }
 8809:             my $uhome=&homeserver($uname,$udom);
 8810:             if (($uhome eq '') || ($uhome eq 'no_host')) {
 8811:                 $result = 'error: no_host';
 8812:             } else {
 8813:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
 8814:                 $storehash->{'host'} = $perlvar{'lonHostID'};
 8815: 
 8816:                 my $namevalue='';
 8817:                 foreach my $key (keys(%{$storehash})) {
 8818:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 8819:                 }
 8820:                 $namevalue=~s/\&$//;
 8821:                 unless ($namespace eq 'courserequests') {
 8822:                     $datakey = &escape($datakey);
 8823:                 }
 8824:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
 8825:                                   $namevalue,$uhome);
 8826:             }
 8827:         } else {
 8828:             $result = 'error: data to store was not a hash reference'; 
 8829:         }
 8830:     } else {
 8831:         $result= 'error: invalid requestkey'; 
 8832:     }
 8833:     return $result;
 8834: }
 8835: 
 8836: # ---------------------------------------------------------- Assign Custom Role
 8837: 
 8838: sub assigncustomrole {
 8839:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
 8840:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 8841:                        $end,$start,$deleteflag,$selfenroll,$context);
 8842: }
 8843: 
 8844: # ----------------------------------------------------------------- Revoke Role
 8845: 
 8846: sub revokerole {
 8847:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
 8848:     my $now=time;
 8849:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
 8850: }
 8851: 
 8852: # ---------------------------------------------------------- Revoke Custom Role
 8853: 
 8854: sub revokecustomrole {
 8855:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
 8856:     my $now=time;
 8857:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 8858:            $deleteflag,$selfenroll,$context);
 8859: }
 8860: 
 8861: # ------------------------------------------------------------ Disk usage
 8862: sub diskusage {
 8863:     my ($udom,$uname,$directorypath,$getpropath)=@_;
 8864:     $directorypath =~ s/\/$//;
 8865:     my $listing=&reply('du2:'.&escape($directorypath).':'
 8866:                        .&escape($getpropath).':'.&escape($uname).':'
 8867:                        .&escape($udom),homeserver($uname,$udom));
 8868:     if ($listing eq 'unknown_cmd') {
 8869:         if ($getpropath) {
 8870:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
 8871:         }
 8872:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
 8873:     }
 8874:     return $listing;
 8875: }
 8876: 
 8877: sub is_locked {
 8878:     my ($file_name, $domain, $user, $which) = @_;
 8879:     my @check;
 8880:     my $is_locked;
 8881:     push (@check,$file_name);
 8882:     my %locked = &get('file_permissions',\@check,
 8883: 		      $env{'user.domain'},$env{'user.name'});
 8884:     my ($tmp)=keys(%locked);
 8885:     if ($tmp=~/^error:/) { undef(%locked); }
 8886:     
 8887:     if (ref($locked{$file_name}) eq 'ARRAY') {
 8888:         $is_locked = 'false';
 8889:         foreach my $entry (@{$locked{$file_name}}) {
 8890:            if (ref($entry) eq 'ARRAY') {
 8891:                $is_locked = 'true';
 8892:                if (ref($which) eq 'ARRAY') {
 8893:                    push(@{$which},$entry);
 8894:                } else {
 8895:                    last;
 8896:                }
 8897:            }
 8898:        }
 8899:     } else {
 8900:         $is_locked = 'false';
 8901:     }
 8902:     return $is_locked;
 8903: }
 8904: 
 8905: sub declutter_portfile {
 8906:     my ($file) = @_;
 8907:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 8908:     return $file;
 8909: }
 8910: 
 8911: # ------------------------------------------------------------- Mark as Read Only
 8912: 
 8913: sub mark_as_readonly {
 8914:     my ($domain,$user,$files,$what) = @_;
 8915:     my %current_permissions = &dump('file_permissions',$domain,$user);
 8916:     my ($tmp)=keys(%current_permissions);
 8917:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 8918:     foreach my $file (@{$files}) {
 8919: 	$file = &declutter_portfile($file);
 8920:         push(@{$current_permissions{$file}},$what);
 8921:     }
 8922:     &put('file_permissions',\%current_permissions,$domain,$user);
 8923:     return;
 8924: }
 8925: 
 8926: # ------------------------------------------------------------Save Selected Files
 8927: 
 8928: sub save_selected_files {
 8929:     my ($user, $path, @files) = @_;
 8930:     my $filename = $user."savedfiles";
 8931:     my @other_files = &files_not_in_path($user, $path);
 8932:     open (OUT, '>'.$tmpdir.$filename);
 8933:     foreach my $file (@files) {
 8934:         print (OUT $env{'form.currentpath'}.$file."\n");
 8935:     }
 8936:     foreach my $file (@other_files) {
 8937:         print (OUT $file."\n");
 8938:     }
 8939:     close (OUT);
 8940:     return 'ok';
 8941: }
 8942: 
 8943: sub clear_selected_files {
 8944:     my ($user) = @_;
 8945:     my $filename = $user."savedfiles";
 8946:     open (OUT, '>'.LONCAPA::tempdir().$filename);
 8947:     print (OUT undef);
 8948:     close (OUT);
 8949:     return ("ok");    
 8950: }
 8951: 
 8952: sub files_in_path {
 8953:     my ($user, $path) = @_;
 8954:     my $filename = $user."savedfiles";
 8955:     my %return_files;
 8956:     open (IN, '<'.LONCAPA::tempdir().$filename);
 8957:     while (my $line_in = <IN>) {
 8958:         chomp ($line_in);
 8959:         my @paths_and_file = split (m!/!, $line_in);
 8960:         my $file_part = pop (@paths_and_file);
 8961:         my $path_part = join ('/', @paths_and_file);
 8962:         $path_part.='/';
 8963:         my $path_and_file = $path_part.$file_part;
 8964:         if ($path_part eq $path) {
 8965:             $return_files{$file_part}= 'selected';
 8966:         }
 8967:     }
 8968:     close (IN);
 8969:     return (\%return_files);
 8970: }
 8971: 
 8972: # called in portfolio select mode, to show files selected NOT in current directory
 8973: sub files_not_in_path {
 8974:     my ($user, $path) = @_;
 8975:     my $filename = $user."savedfiles";
 8976:     my @return_files;
 8977:     my $path_part;
 8978:     open(IN, '<'.LONCAPA::.$filename);
 8979:     while (my $line = <IN>) {
 8980:         #ok, I know it's clunky, but I want it to work
 8981:         my @paths_and_file = split(m|/|, $line);
 8982:         my $file_part = pop(@paths_and_file);
 8983:         chomp($file_part);
 8984:         my $path_part = join('/', @paths_and_file);
 8985:         $path_part .= '/';
 8986:         my $path_and_file = $path_part.$file_part;
 8987:         if ($path_part ne $path) {
 8988:             push(@return_files, ($path_and_file));
 8989:         }
 8990:     }
 8991:     close(OUT);
 8992:     return (@return_files);
 8993: }
 8994: 
 8995: #----------------------------------------------Get portfolio file permissions
 8996: 
 8997: sub get_portfile_permissions {
 8998:     my ($domain,$user) = @_;
 8999:     my %current_permissions = &dump('file_permissions',$domain,$user);
 9000:     my ($tmp)=keys(%current_permissions);
 9001:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 9002:     return \%current_permissions;
 9003: }
 9004: 
 9005: #---------------------------------------------Get portfolio file access controls
 9006: 
 9007: sub get_access_controls {
 9008:     my ($current_permissions,$group,$file) = @_;
 9009:     my %access;
 9010:     my $real_file = $file;
 9011:     $file =~ s/\.meta$//;
 9012:     if (defined($file)) {
 9013:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 9014:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 9015:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 9016:             }
 9017:         }
 9018:     } else {
 9019:         foreach my $key (keys(%{$current_permissions})) {
 9020:             if ($key =~ /\0accesscontrol$/) {
 9021:                 if (defined($group)) {
 9022:                     if ($key !~ m-^\Q$group\E/-) {
 9023:                         next;
 9024:                     }
 9025:                 }
 9026:                 my ($fullpath) = split(/\0/,$key);
 9027:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 9028:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 9029:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 9030:                     }
 9031:                 }
 9032:             }
 9033:         }
 9034:     }
 9035:     return %access;
 9036: }
 9037: 
 9038: sub modify_access_controls {
 9039:     my ($file_name,$changes,$domain,$user)=@_;
 9040:     my ($outcome,$deloutcome);
 9041:     my %store_permissions;
 9042:     my %new_values;
 9043:     my %new_control;
 9044:     my %translation;
 9045:     my @deletions = ();
 9046:     my $now = time;
 9047:     if (exists($$changes{'activate'})) {
 9048:         if (ref($$changes{'activate'}) eq 'HASH') {
 9049:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 9050:             my $numnew = scalar(@newitems);
 9051:             for (my $i=0; $i<$numnew; $i++) {
 9052:                 my $newkey = $newitems[$i];
 9053:                 my $newid = &Apache::loncommon::get_cgi_id();
 9054:                 if ($newkey =~ /^\d+:/) { 
 9055:                     $newkey =~ s/^(\d+)/$newid/;
 9056:                     $translation{$1} = $newid;
 9057:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 9058:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 9059:                     $translation{$1} = $newid;
 9060:                 }
 9061:                 $new_values{$file_name."\0".$newkey} = 
 9062:                                           $$changes{'activate'}{$newitems[$i]};
 9063:                 $new_control{$newkey} = $now;
 9064:             }
 9065:         }
 9066:     }
 9067:     my %todelete;
 9068:     my %changed_items;
 9069:     foreach my $action ('delete','update') {
 9070:         if (exists($$changes{$action})) {
 9071:             if (ref($$changes{$action}) eq 'HASH') {
 9072:                 foreach my $key (keys(%{$$changes{$action}})) {
 9073:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 9074:                     if ($action eq 'delete') { 
 9075:                         $todelete{$itemnum} = 1;
 9076:                     } else {
 9077:                         $changed_items{$itemnum} = $key;
 9078:                     }
 9079:                 }
 9080:             }
 9081:         }
 9082:     }
 9083:     # get lock on access controls for file.
 9084:     my $lockhash = {
 9085:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 9086:                                                        ':'.$env{'user.domain'},
 9087:                    }; 
 9088:     my $tries = 0;
 9089:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 9090:    
 9091:     while (($gotlock ne 'ok') && $tries <3) {
 9092:         $tries ++;
 9093:         sleep 1;
 9094:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 9095:     }
 9096:     if ($gotlock eq 'ok') {
 9097:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 9098:         my ($tmp)=keys(%curr_permissions);
 9099:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 9100:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 9101:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 9102:             if (ref($curr_controls) eq 'HASH') {
 9103:                 foreach my $control_item (keys(%{$curr_controls})) {
 9104:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 9105:                     if (defined($todelete{$itemnum})) {
 9106:                         push(@deletions,$file_name."\0".$control_item);
 9107:                     } else {
 9108:                         if (defined($changed_items{$itemnum})) {
 9109:                             $new_control{$changed_items{$itemnum}} = $now;
 9110:                             push(@deletions,$file_name."\0".$control_item);
 9111:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 9112:                         } else {
 9113:                             $new_control{$control_item} = $$curr_controls{$control_item};
 9114:                         }
 9115:                     }
 9116:                 }
 9117:             }
 9118:         }
 9119:         my ($group);
 9120:         if (&is_course($domain,$user)) {
 9121:             ($group,my $file) = split(/\//,$file_name,2);
 9122:         }
 9123:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 9124:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 9125:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 9126:         #  remove lock
 9127:         my @del_lock = ($file_name."\0".'locked_access_records');
 9128:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 9129:         my $sqlresult =
 9130:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
 9131:                                     $group);
 9132:     } else {
 9133:         $outcome = "error: could not obtain lockfile\n";  
 9134:     }
 9135:     return ($outcome,$deloutcome,\%new_values,\%translation);
 9136: }
 9137: 
 9138: sub make_public_indefinitely {
 9139:     my ($requrl) = @_;
 9140:     my $now = time;
 9141:     my $action = 'activate';
 9142:     my $aclnum = 0;
 9143:     if (&is_portfolio_url($requrl)) {
 9144:         my (undef,$udom,$unum,$file_name,$group) =
 9145:             &parse_portfolio_url($requrl);
 9146:         my $current_perms = &get_portfile_permissions($udom,$unum);
 9147:         my %access_controls = &get_access_controls($current_perms,
 9148:                                                    $group,$file_name);
 9149:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 9150:             my ($num,$scope,$end,$start) = 
 9151:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 9152:             if ($scope eq 'public') {
 9153:                 if ($start <= $now && $end == 0) {
 9154:                     $action = 'none';
 9155:                 } else {
 9156:                     $action = 'update';
 9157:                     $aclnum = $num;
 9158:                 }
 9159:                 last;
 9160:             }
 9161:         }
 9162:         if ($action eq 'none') {
 9163:              return 'ok';
 9164:         } else {
 9165:             my %changes;
 9166:             my $newend = 0;
 9167:             my $newstart = $now;
 9168:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 9169:             $changes{$action}{$newkey} = {
 9170:                 type => 'public',
 9171:                 time => {
 9172:                     start => $newstart,
 9173:                     end   => $newend,
 9174:                 },
 9175:             };
 9176:             my ($outcome,$deloutcome,$new_values,$translation) =
 9177:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 9178:             return $outcome;
 9179:         }
 9180:     } else {
 9181:         return 'invalid';
 9182:     }
 9183: }
 9184: 
 9185: #------------------------------------------------------Get Marked as Read Only
 9186: 
 9187: sub get_marked_as_readonly {
 9188:     my ($domain,$user,$what,$group) = @_;
 9189:     my $current_permissions = &get_portfile_permissions($domain,$user);
 9190:     my @readonly_files;
 9191:     my $cmp1=$what;
 9192:     if (ref($what)) { $cmp1=join('',@{$what}) };
 9193:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 9194:         if (defined($group)) {
 9195:             if ($file_name !~ m-^\Q$group\E/-) {
 9196:                 next;
 9197:             }
 9198:         }
 9199:         if (ref($value) eq "ARRAY"){
 9200:             foreach my $stored_what (@{$value}) {
 9201:                 my $cmp2=$stored_what;
 9202:                 if (ref($stored_what) eq 'ARRAY') {
 9203:                     $cmp2=join('',@{$stored_what});
 9204:                 }
 9205:                 if ($cmp1 eq $cmp2) {
 9206:                     push(@readonly_files, $file_name);
 9207:                     last;
 9208:                 } elsif (!defined($what)) {
 9209:                     push(@readonly_files, $file_name);
 9210:                     last;
 9211:                 }
 9212:             }
 9213:         }
 9214:     }
 9215:     return @readonly_files;
 9216: }
 9217: #-----------------------------------------------------------Get Marked as Read Only Hash
 9218: 
 9219: sub get_marked_as_readonly_hash {
 9220:     my ($current_permissions,$group,$what) = @_;
 9221:     my %readonly_files;
 9222:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 9223:         if (defined($group)) {
 9224:             if ($file_name !~ m-^\Q$group\E/-) {
 9225:                 next;
 9226:             }
 9227:         }
 9228:         if (ref($value) eq "ARRAY"){
 9229:             foreach my $stored_what (@{$value}) {
 9230:                 if (ref($stored_what) eq 'ARRAY') {
 9231:                     foreach my $lock_descriptor(@{$stored_what}) {
 9232:                         if ($lock_descriptor eq 'graded') {
 9233:                             $readonly_files{$file_name} = 'graded';
 9234:                         } elsif ($lock_descriptor eq 'handback') {
 9235:                             $readonly_files{$file_name} = 'handback';
 9236:                         } else {
 9237:                             if (!exists($readonly_files{$file_name})) {
 9238:                                 $readonly_files{$file_name} = 'locked';
 9239:                             }
 9240:                         }
 9241:                     }
 9242:                 } 
 9243:             }
 9244:         } 
 9245:     }
 9246:     return %readonly_files;
 9247: }
 9248: # ------------------------------------------------------------ Unmark as Read Only
 9249: 
 9250: sub unmark_as_readonly {
 9251:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 9252:     # for portfolio submissions, $what contains [$symb,$crsid] 
 9253:     my ($domain,$user,$what,$file_name,$group) = @_;
 9254:     $file_name = &declutter_portfile($file_name);
 9255:     my $symb_crs = $what;
 9256:     if (ref($what)) { $symb_crs=join('',@$what); }
 9257:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 9258:     my ($tmp)=keys(%current_permissions);
 9259:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 9260:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 9261:     foreach my $file (@readonly_files) {
 9262: 	my $clean_file = &declutter_portfile($file);
 9263: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 9264: 	my $current_locks = $current_permissions{$file};
 9265:         my @new_locks;
 9266:         my @del_keys;
 9267:         if (ref($current_locks) eq "ARRAY"){
 9268:             foreach my $locker (@{$current_locks}) {
 9269:                 my $compare=$locker;
 9270:                 if (ref($locker) eq 'ARRAY') {
 9271:                     $compare=join('',@{$locker});
 9272:                     if ($compare ne $symb_crs) {
 9273:                         push(@new_locks, $locker);
 9274:                     }
 9275:                 }
 9276:             }
 9277:             if (scalar(@new_locks) > 0) {
 9278:                 $current_permissions{$file} = \@new_locks;
 9279:             } else {
 9280:                 push(@del_keys, $file);
 9281:                 &del('file_permissions',\@del_keys, $domain, $user);
 9282:                 delete($current_permissions{$file});
 9283:             }
 9284:         }
 9285:     }
 9286:     &put('file_permissions',\%current_permissions,$domain,$user);
 9287:     return;
 9288: }
 9289: 
 9290: # ------------------------------------------------------------ Directory lister
 9291: 
 9292: sub dirlist {
 9293:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
 9294:     $uri=~s/^\///;
 9295:     $uri=~s/\/$//;
 9296:     my ($udom, $uname);
 9297:     if ($getuserdir) {
 9298:         $udom = $userdomain;
 9299:         $uname = $username;
 9300:     } else {
 9301:         (undef,$udom,$uname)=split(/\//,$uri);
 9302:         if(defined($userdomain)) {
 9303:             $udom = $userdomain;
 9304:         }
 9305:         if(defined($username)) {
 9306:             $uname = $username;
 9307:         }
 9308:     }
 9309:     my ($dirRoot,$listing,@listing_results);
 9310: 
 9311:     $dirRoot = $perlvar{'lonDocRoot'};
 9312:     if (defined($getpropath)) {
 9313:         $dirRoot = &propath($udom,$uname);
 9314:         $dirRoot =~ s/\/$//;
 9315:     } elsif (defined($getuserdir)) {
 9316:         my $subdir=$uname.'__';
 9317:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 9318:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
 9319:                    ."/$udom/$subdir/$uname";
 9320:     } elsif (defined($alternateRoot)) {
 9321:         $dirRoot = $alternateRoot;
 9322:     }
 9323: 
 9324:     if($udom) {
 9325:         if($uname) {
 9326:             my $uhome = &homeserver($uname,$udom);
 9327:             if ($uhome eq 'no_host') {
 9328:                 return ([],'no_host');
 9329:             }
 9330:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
 9331:                               .$getuserdir.':'.&escape($dirRoot)
 9332:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
 9333:             if ($listing eq 'unknown_cmd') {
 9334:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
 9335:             } else {
 9336:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 9337:             }
 9338:             if ($listing eq 'unknown_cmd') {
 9339:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
 9340:                 @listing_results = split(/:/,$listing);
 9341:             } else {
 9342:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 9343:             }
 9344:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
 9345:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
 9346:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 9347:                 return ([],$listing);
 9348:             } else {
 9349:                 return (\@listing_results);
 9350:             }
 9351:         } elsif(!$alternateRoot) {
 9352:             my (%allusers,%listerror);
 9353: 	    my %servers = &get_servers($udom,'library');
 9354:  	    foreach my $tryserver (keys(%servers)) {
 9355:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
 9356:                                   &escape($udom),$tryserver);
 9357:                 if ($listing eq 'unknown_cmd') {
 9358: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 9359: 				      $udom, $tryserver);
 9360:                 } else {
 9361:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
 9362:                 }
 9363: 		if ($listing eq 'unknown_cmd') {
 9364: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 9365: 				      $udom, $tryserver);
 9366: 		    @listing_results = split(/:/,$listing);
 9367: 		} else {
 9368: 		    @listing_results =
 9369: 			map { &unescape($_); } split(/:/,$listing);
 9370: 		}
 9371:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
 9372:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
 9373:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 9374:                     $listerror{$tryserver} = $listing;
 9375:                 } else {
 9376: 		    foreach my $line (@listing_results) {
 9377: 			my ($entry) = split(/&/,$line,2);
 9378: 			$allusers{$entry} = 1;
 9379: 		    }
 9380: 		}
 9381:             }
 9382:             my @alluserslist=();
 9383:             foreach my $user (sort(keys(%allusers))) {
 9384:                 push(@alluserslist,$user.'&user');
 9385:             }
 9386:             return (\@alluserslist);
 9387:         } else {
 9388:             return ([],'missing username');
 9389:         }
 9390:     } elsif(!defined($getpropath)) {
 9391:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
 9392:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
 9393:         return (\@all_domains);
 9394:     } else {
 9395:         return ([],'missing domain');
 9396:     }
 9397: }
 9398: 
 9399: # --------------------------------------------- GetFileTimestamp
 9400: # This function utilizes dirlist and returns the date stamp for
 9401: # when it was last modified.  It will also return an error of -1
 9402: # if an error occurs
 9403: 
 9404: sub GetFileTimestamp {
 9405:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
 9406:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 9407:     $studentName   = &LONCAPA::clean_username($studentName);
 9408:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
 9409:                                     undef,$getuserdir);
 9410:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 9411:         return -1;
 9412:     }
 9413:     if (ref($fileref) eq 'ARRAY') {
 9414:         my @stats = split('&',$fileref->[0]);
 9415:         # @stats contains first the filename, then the stat output
 9416:         return $stats[10]; # so this is 10 instead of 9.
 9417:     } else {
 9418:         return -1;
 9419:     }
 9420: }
 9421: 
 9422: sub stat_file {
 9423:     my ($uri) = @_;
 9424:     $uri = &clutter_with_no_wrapper($uri);
 9425: 
 9426:     my ($udom,$uname,$file);
 9427:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 9428: 	($udom,$uname,$file) =
 9429: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 9430: 	$file = 'userfiles/'.$file;
 9431:     }
 9432:     if ($uri =~ m-^/res/-) {
 9433: 	($udom,$uname) = 
 9434: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 9435: 	$file = $uri;
 9436:     }
 9437: 
 9438:     if (!$udom || !$uname || !$file) {
 9439: 	# unable to handle the uri
 9440: 	return ();
 9441:     }
 9442:     my $getpropath;
 9443:     if ($file =~ /^userfiles\//) {
 9444:         $getpropath = 1;
 9445:     }
 9446:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
 9447:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 9448:         return ();
 9449:     } else {
 9450:         if (ref($listref) eq 'ARRAY') {
 9451:             my @stats = split('&',$listref->[0]);
 9452: 	    shift(@stats); #filename is first
 9453: 	    return @stats;
 9454:         }
 9455:     }
 9456:     return ();
 9457: }
 9458: 
 9459: # -------------------------------------------------------- Value of a Condition
 9460: 
 9461: # gets the value of a specific preevaluated condition
 9462: #    stored in the string  $env{user.state.<cid>}
 9463: # or looks up a condition reference in the bighash and if if hasn't
 9464: # already been evaluated recurses into docondval to get the value of
 9465: # the condition, then memoizing it to 
 9466: #   $env{user.state.<cid>.<condition>}
 9467: sub directcondval {
 9468:     my $number=shift;
 9469:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 9470: 	&Apache::lonuserstate::evalstate();
 9471:     }
 9472:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 9473: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 9474:     } elsif ($number =~ /^_/) {
 9475: 	my $sub_condition;
 9476: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9477: 		&GDBM_READER(),0640)) {
 9478: 	    $sub_condition=$bighash{'conditions'.$number};
 9479: 	    untie(%bighash);
 9480: 	}
 9481: 	my $value = &docondval($sub_condition);
 9482: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
 9483: 	return $value;
 9484:     }
 9485:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 9486:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 9487:     } else {
 9488:        return 2;
 9489:     }
 9490: }
 9491: 
 9492: # get the collection of conditions for this resource
 9493: sub condval {
 9494:     my $condidx=shift;
 9495:     my $allpathcond='';
 9496:     foreach my $cond (split(/\|/,$condidx)) {
 9497: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 9498: 	    $allpathcond.=
 9499: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 9500: 	}
 9501:     }
 9502:     $allpathcond=~s/\|$//;
 9503:     return &docondval($allpathcond);
 9504: }
 9505: 
 9506: #evaluates an expression of conditions
 9507: sub docondval {
 9508:     my ($allpathcond) = @_;
 9509:     my $result=0;
 9510:     if ($env{'request.course.id'}
 9511: 	&& defined($allpathcond)) {
 9512: 	my $operand='|';
 9513: 	my @stack;
 9514: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 9515: 	    if ($chunk eq '(') {
 9516: 		push @stack,($operand,$result);
 9517: 	    } elsif ($chunk eq ')') {
 9518: 		my $before=pop @stack;
 9519: 		if (pop @stack eq '&') {
 9520: 		    $result=$result>$before?$before:$result;
 9521: 		} else {
 9522: 		    $result=$result>$before?$result:$before;
 9523: 		}
 9524: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 9525: 		$operand=$chunk;
 9526: 	    } else {
 9527: 		my $new=directcondval($chunk);
 9528: 		if ($operand eq '&') {
 9529: 		    $result=$result>$new?$new:$result;
 9530: 		} else {
 9531: 		    $result=$result>$new?$result:$new;
 9532: 		}
 9533: 	    }
 9534: 	}
 9535:     }
 9536:     return $result;
 9537: }
 9538: 
 9539: # ---------------------------------------------------- Devalidate courseresdata
 9540: 
 9541: sub devalidatecourseresdata {
 9542:     my ($coursenum,$coursedomain)=@_;
 9543:     my $hashid=$coursenum.':'.$coursedomain;
 9544:     &devalidate_cache_new('courseres',$hashid);
 9545: }
 9546: 
 9547: 
 9548: # --------------------------------------------------- Course Resourcedata Query
 9549: #
 9550: #  Parameters:
 9551: #      $coursenum    - Number of the course.
 9552: #      $coursedomain - Domain at which the course was created.
 9553: #  Returns:
 9554: #     A hash of the course parameters along (I think) with timestamps
 9555: #     and version info.
 9556: 
 9557: sub get_courseresdata {
 9558:     my ($coursenum,$coursedomain)=@_;
 9559:     my $coursehom=&homeserver($coursenum,$coursedomain);
 9560:     my $hashid=$coursenum.':'.$coursedomain;
 9561:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 9562:     my %dumpreply;
 9563:     unless (defined($cached)) {
 9564: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 9565: 	$result=\%dumpreply;
 9566: 	my ($tmp) = keys(%dumpreply);
 9567: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 9568: 	    &do_cache_new('courseres',$hashid,$result,600);
 9569: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 9570: 	    return $tmp;
 9571: 	} elsif ($tmp =~ /^(error)/) {
 9572: 	    $result=undef;
 9573: 	    &do_cache_new('courseres',$hashid,$result,600);
 9574: 	}
 9575:     }
 9576:     return $result;
 9577: }
 9578: 
 9579: sub devalidateuserresdata {
 9580:     my ($uname,$udom)=@_;
 9581:     my $hashid="$udom:$uname";
 9582:     &devalidate_cache_new('userres',$hashid);
 9583: }
 9584: 
 9585: sub get_userresdata {
 9586:     my ($uname,$udom)=@_;
 9587:     #most student don\'t have any data set, check if there is some data
 9588:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 9589: 
 9590:     my $hashid="$udom:$uname";
 9591:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 9592:     if (!defined($cached)) {
 9593: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 9594: 	$result=\%resourcedata;
 9595: 	&do_cache_new('userres',$hashid,$result,600);
 9596:     }
 9597:     my ($tmp)=keys(%$result);
 9598:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 9599: 	return $result;
 9600:     }
 9601:     #error 2 occurs when the .db doesn't exist
 9602:     if ($tmp!~/error: 2 /) {
 9603: 	&logthis("<font color=\"blue\">WARNING:".
 9604: 		 " Trying to get resource data for ".
 9605: 		 $uname." at ".$udom.": ".
 9606: 		 $tmp."</font>");
 9607:     } elsif ($tmp=~/error: 2 /) {
 9608: 	#&EXT_cache_set($udom,$uname);
 9609: 	&do_cache_new('userres',$hashid,undef,600);
 9610: 	undef($tmp); # not really an error so don't send it back
 9611:     }
 9612:     return $tmp;
 9613: }
 9614: #----------------------------------------------- resdata - return resource data
 9615: #  Purpose:
 9616: #    Return resource data for either users or for a course.
 9617: #  Parameters:
 9618: #     $name      - Course/user name.
 9619: #     $domain    - Name of the domain the user/course is registered on.
 9620: #     $type      - Type of thing $name is (must be 'course' or 'user'
 9621: #     @which     - Array of names of resources desired.
 9622: #  Returns:
 9623: #     The value of the first reasource in @which that is found in the
 9624: #     resource hash.
 9625: #  Exceptional Conditions:
 9626: #     If the $type passed in is not valid (not the string 'course' or 
 9627: #     'user', an undefined  reference is returned.
 9628: #     If none of the resources are found, an undef is returned
 9629: sub resdata {
 9630:     my ($name,$domain,$type,@which)=@_;
 9631:     my $result;
 9632:     if ($type eq 'course') {
 9633: 	$result=&get_courseresdata($name,$domain);
 9634:     } elsif ($type eq 'user') {
 9635: 	$result=&get_userresdata($name,$domain);
 9636:     }
 9637:     if (!ref($result)) { return $result; }    
 9638:     foreach my $item (@which) {
 9639: 	if (defined($result->{$item->[0]})) {
 9640: 	    return [$result->{$item->[0]},$item->[1]];
 9641: 	}
 9642:     }
 9643:     return undef;
 9644: }
 9645: 
 9646: sub get_numsuppfiles {
 9647:     my ($cnum,$cdom,$ignorecache)=@_;
 9648:     my $hashid=$cnum.':'.$cdom;
 9649:     my ($suppcount,$cached);
 9650:     unless ($ignorecache) {
 9651:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
 9652:     }
 9653:     unless (defined($cached)) {
 9654:         my $chome=&homeserver($cnum,$cdom);
 9655:         unless ($chome eq 'no_host') {
 9656:             ($suppcount,my $errors) = (0,0);
 9657:             my $suppmap = 'supplemental.sequence';
 9658:             ($suppcount,$errors) = 
 9659:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
 9660:         }
 9661:         &do_cache_new('suppcount',$hashid,$suppcount,600);
 9662:     }
 9663:     return $suppcount;
 9664: }
 9665: 
 9666: #
 9667: # EXT resource caching routines
 9668: #
 9669: 
 9670: sub clear_EXT_cache_status {
 9671:     &delenv('cache.EXT.');
 9672: }
 9673: 
 9674: sub EXT_cache_status {
 9675:     my ($target_domain,$target_user) = @_;
 9676:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 9677:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 9678:         # We know already the user has no data
 9679:         return 1;
 9680:     } else {
 9681:         return 0;
 9682:     }
 9683: }
 9684: 
 9685: sub EXT_cache_set {
 9686:     my ($target_domain,$target_user) = @_;
 9687:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 9688:     #&appenv({$cachename => time});
 9689: }
 9690: 
 9691: # --------------------------------------------------------- Value of a Variable
 9692: sub EXT {
 9693: 
 9694:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
 9695:     unless ($varname) { return ''; }
 9696:     #get real user name/domain, courseid and symb
 9697:     my $courseid;
 9698:     my $publicuser;
 9699:     if ($symbparm) {
 9700: 	$symbparm=&get_symb_from_alias($symbparm);
 9701:     }
 9702:     if (!($uname && $udom)) {
 9703:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 9704:       if (!$symbparm) {	$symbparm=$cursymb; }
 9705:     } else {
 9706: 	$courseid=$env{'request.course.id'};
 9707:     }
 9708:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 9709:     my $rest;
 9710:     if (defined($therest[0])) {
 9711:        $rest=join('.',@therest);
 9712:     } else {
 9713:        $rest='';
 9714:     }
 9715: 
 9716:     my $qualifierrest=$qualifier;
 9717:     if ($rest) { $qualifierrest.='.'.$rest; }
 9718:     my $spacequalifierrest=$space;
 9719:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 9720:     if ($realm eq 'user') {
 9721: # --------------------------------------------------------------- user.resource
 9722: 	if ($space eq 'resource') {
 9723: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 9724: 		  || defined($Apache::lonhomework::parsing_a_task))
 9725: 		 &&
 9726: 		 ($symbparm eq &symbread()) ) {	
 9727: 		# if we are in the middle of processing the resource the
 9728: 		# get the value we are planning on committing
 9729:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 9730:                     return $Apache::lonhomework::results{$qualifierrest};
 9731:                 } else {
 9732:                     return $Apache::lonhomework::history{$qualifierrest};
 9733:                 }
 9734: 	    } else {
 9735: 		my %restored;
 9736: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 9737: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 9738: 		} else {
 9739: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 9740: 		}
 9741: 		return $restored{$qualifierrest};
 9742: 	    }
 9743: # ----------------------------------------------------------------- user.access
 9744:         } elsif ($space eq 'access') {
 9745: 	    # FIXME - not supporting calls for a specific user
 9746:             return &allowed($qualifier,$rest);
 9747: # ------------------------------------------ user.preferences, user.environment
 9748:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 9749: 	    if (($uname eq $env{'user.name'}) &&
 9750: 		($udom eq $env{'user.domain'})) {
 9751: 		return $env{join('.',('environment',$qualifierrest))};
 9752: 	    } else {
 9753: 		my %returnhash;
 9754: 		if (!$publicuser) {
 9755: 		    %returnhash=&userenvironment($udom,$uname,
 9756: 						 $qualifierrest);
 9757: 		}
 9758: 		return $returnhash{$qualifierrest};
 9759: 	    }
 9760: # ----------------------------------------------------------------- user.course
 9761:         } elsif ($space eq 'course') {
 9762: 	    # FIXME - not supporting calls for a specific user
 9763:             return $env{join('.',('request.course',$qualifier))};
 9764: # ------------------------------------------------------------------- user.role
 9765:         } elsif ($space eq 'role') {
 9766: 	    # FIXME - not supporting calls for a specific user
 9767:             my ($role,$where)=split(/\./,$env{'request.role'});
 9768:             if ($qualifier eq 'value') {
 9769: 		return $role;
 9770:             } elsif ($qualifier eq 'extent') {
 9771:                 return $where;
 9772:             }
 9773: # ----------------------------------------------------------------- user.domain
 9774:         } elsif ($space eq 'domain') {
 9775:             return $udom;
 9776: # ------------------------------------------------------------------- user.name
 9777:         } elsif ($space eq 'name') {
 9778:             return $uname;
 9779: # ---------------------------------------------------- Any other user namespace
 9780:         } else {
 9781: 	    my %reply;
 9782: 	    if (!$publicuser) {
 9783: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 9784: 	    }
 9785: 	    return $reply{$qualifierrest};
 9786:         }
 9787:     } elsif ($realm eq 'query') {
 9788: # ---------------------------------------------- pull stuff out of query string
 9789:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 9790: 						[$spacequalifierrest]);
 9791: 	return $env{'form.'.$spacequalifierrest}; 
 9792:    } elsif ($realm eq 'request') {
 9793: # ------------------------------------------------------------- request.browser
 9794:         if ($space eq 'browser') {
 9795:             return $env{'browser.'.$qualifier};
 9796: # ------------------------------------------------------------ request.filename
 9797:         } else {
 9798:             return $env{'request.'.$spacequalifierrest};
 9799:         }
 9800:     } elsif ($realm eq 'course') {
 9801: # ---------------------------------------------------------- course.description
 9802:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 9803:     } elsif ($realm eq 'resource') {
 9804: 
 9805: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 9806: 	    if (!$symbparm) { $symbparm=&symbread(); }
 9807: 	}
 9808: 
 9809:         if ($qualifier eq '') {
 9810: 	    if ($space eq 'title') {
 9811: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 9812: 	        return &gettitle($symbparm);
 9813: 	    }
 9814: 	
 9815: 	    if ($space eq 'map') {
 9816: 	        my ($map) = &decode_symb($symbparm);
 9817: 	        return &symbread($map);
 9818: 	    }
 9819:             if ($space eq 'maptitle') {
 9820:                 my ($map) = &decode_symb($symbparm);
 9821:                 return &gettitle($map);
 9822:             }
 9823: 	    if ($space eq 'filename') {
 9824: 	        if ($symbparm) {
 9825: 		    return &clutter((&decode_symb($symbparm))[2]);
 9826: 	        }
 9827: 	        return &hreflocation('',$env{'request.filename'});
 9828: 	    }
 9829: 
 9830:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
 9831:                 if ($space eq 'visibleparts') {
 9832:                     my $navmap = Apache::lonnavmaps::navmap->new();
 9833:                     my $item;
 9834:                     if (ref($navmap)) {
 9835:                         my $res = $navmap->getBySymb($symbparm);
 9836:                         my $parts = $res->parts();
 9837:                         if (ref($parts) eq 'ARRAY') {
 9838:                             $item = join(',',@{$parts});
 9839:                         }
 9840:                         undef($navmap);
 9841:                     }
 9842:                     return $item;
 9843:                 }
 9844:             }
 9845:         }
 9846: 
 9847: 	my ($section, $group, @groups);
 9848: 	my ($courselevelm,$courselevel);
 9849:         if (($courseid eq '') && ($cid)) {
 9850:             $courseid = $cid;
 9851:         }
 9852: 	if (($symbparm && $courseid) && 
 9853: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
 9854: 
 9855: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 9856: 
 9857: # ----------------------------------------------------- Cascading lookup scheme
 9858: 	    my $symbp=$symbparm;
 9859: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 9860: 
 9861: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 9862: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 9863: 
 9864: 	    if (($env{'user.name'} eq $uname) &&
 9865: 		($env{'user.domain'} eq $udom)) {
 9866: 		$section=$env{'request.course.sec'};
 9867:                 @groups = split(/:/,$env{'request.course.groups'});  
 9868:                 @groups=&sort_course_groups($courseid,@groups); 
 9869: 	    } else {
 9870: 		if (! defined($usection)) {
 9871: 		    $section=&getsection($udom,$uname,$courseid);
 9872: 		} else {
 9873: 		    $section = $usection;
 9874: 		}
 9875:                 @groups = &get_users_groups($udom,$uname,$courseid);
 9876: 	    }
 9877: 
 9878: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 9879: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 9880: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 9881: 
 9882: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 9883: 	    my $courselevelr=$courseid.'.'.$symbparm;
 9884: 	    $courselevelm=$courseid.'.'.$mapparm;
 9885: 
 9886: # ----------------------------------------------------------- first, check user
 9887: 
 9888: 	    my $userreply=&resdata($uname,$udom,'user',
 9889: 				       ([$courselevelr,'resource'],
 9890: 					[$courselevelm,'map'     ],
 9891: 					[$courselevel, 'course'  ]));
 9892: 	    if (defined($userreply)) { return &get_reply($userreply); }
 9893: 
 9894: # ------------------------------------------------ second, check some of course
 9895:             my $coursereply;
 9896:             if (@groups > 0) {
 9897:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 9898:                                        $mapparm,$spacequalifierrest);
 9899:                 if (defined($coursereply)) { return &get_reply($coursereply); }
 9900:             }
 9901: 
 9902: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 9903: 				  $env{'course.'.$courseid.'.domain'},
 9904: 				  'course',
 9905: 				  ([$seclevelr,   'resource'],
 9906: 				   [$seclevelm,   'map'     ],
 9907: 				   [$seclevel,    'course'  ],
 9908: 				   [$courselevelr,'resource']));
 9909: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 9910: 
 9911: # ------------------------------------------------------ third, check map parms
 9912: 	    my %parmhash=();
 9913: 	    my $thisparm='';
 9914: 	    if (tie(%parmhash,'GDBM_File',
 9915: 		    $env{'request.course.fn'}.'_parms.db',
 9916: 		    &GDBM_READER(),0640)) {
 9917: 		$thisparm=$parmhash{$symbparm};
 9918: 		untie(%parmhash);
 9919: 	    }
 9920: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
 9921: 	}
 9922: # ------------------------------------------ fourth, look in resource metadata
 9923: 
 9924: 	$spacequalifierrest=~s/\./\_/;
 9925: 	my $filename;
 9926: 	if (!$symbparm) { $symbparm=&symbread(); }
 9927: 	if ($symbparm) {
 9928: 	    $filename=(&decode_symb($symbparm))[2];
 9929: 	} else {
 9930: 	    $filename=$env{'request.filename'};
 9931: 	}
 9932: 	my $metadata=&metadata($filename,$spacequalifierrest);
 9933: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 9934: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 9935: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 9936: 
 9937: # ---------------------------------------------- fourth, look in rest of course
 9938: 	if ($symbparm && defined($courseid) && 
 9939: 	    $courseid eq $env{'request.course.id'}) {
 9940: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 9941: 				     $env{'course.'.$courseid.'.domain'},
 9942: 				     'course',
 9943: 				     ([$courselevelm,'map'   ],
 9944: 				      [$courselevel, 'course']));
 9945: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 9946: 	}
 9947: # ------------------------------------------------------------------ Cascade up
 9948: 	unless ($space eq '0') {
 9949: 	    my @parts=split(/_/,$space);
 9950: 	    my $id=pop(@parts);
 9951: 	    my $part=join('_',@parts);
 9952: 	    if ($part eq '') { $part='0'; }
 9953: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 9954: 				 $symbparm,$udom,$uname,$section,1);
 9955: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
 9956: 	}
 9957: 	if ($recurse) { return undef; }
 9958: 	my $pack_def=&packages_tab_default($filename,$varname);
 9959: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
 9960: # ---------------------------------------------------- Any other user namespace
 9961:     } elsif ($realm eq 'environment') {
 9962: # ----------------------------------------------------------------- environment
 9963: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 9964: 	    return $env{'environment.'.$spacequalifierrest};
 9965: 	} else {
 9966: 	    if ($uname eq 'anonymous' && $udom eq '') {
 9967: 		return '';
 9968: 	    }
 9969: 	    my %returnhash=&userenvironment($udom,$uname,
 9970: 					    $spacequalifierrest);
 9971: 	    return $returnhash{$spacequalifierrest};
 9972: 	}
 9973:     } elsif ($realm eq 'system') {
 9974: # ----------------------------------------------------------------- system.time
 9975: 	if ($space eq 'time') {
 9976: 	    return time;
 9977:         }
 9978:     } elsif ($realm eq 'server') {
 9979: # ----------------------------------------------------------------- system.time
 9980: 	if ($space eq 'name') {
 9981: 	    return $ENV{'SERVER_NAME'};
 9982:         }
 9983:     }
 9984:     return '';
 9985: }
 9986: 
 9987: sub get_reply {
 9988:     my ($reply_value) = @_;
 9989:     if (ref($reply_value) eq 'ARRAY') {
 9990:         if (wantarray) {
 9991: 	    return @$reply_value;
 9992:         }
 9993:         return $reply_value->[0];
 9994:     } else {
 9995:         return $reply_value;
 9996:     }
 9997: }
 9998: 
 9999: sub check_group_parms {
10000:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
10001:     my @groupitems = ();
10002:     my $resultitem;
10003:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
10004:     foreach my $group (@{$groups}) {
10005:         foreach my $level (@levels) {
10006:              my $item = $courseid.'.['.$group.'].'.$level->[0];
10007:              push(@groupitems,[$item,$level->[1]]);
10008:         }
10009:     }
10010:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
10011:                             $env{'course.'.$courseid.'.domain'},
10012:                                      'course',@groupitems);
10013:     return $coursereply;
10014: }
10015: 
10016: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
10017:     my ($courseid,@groups) = @_;
10018:     @groups = sort(@groups);
10019:     return @groups;
10020: }
10021: 
10022: sub packages_tab_default {
10023:     my ($uri,$varname)=@_;
10024:     my (undef,$part,$name)=split(/\./,$varname);
10025: 
10026:     my (@extension,@specifics,$do_default);
10027:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
10028: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
10029: 	if ($pack_type eq 'default') {
10030: 	    $do_default=1;
10031: 	} elsif ($pack_type eq 'extension') {
10032: 	    push(@extension,[$package,$pack_type,$pack_part]);
10033: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
10034: 	    # only look at packages defaults for packages that this id is
10035: 	    push(@specifics,[$package,$pack_type,$pack_part]);
10036: 	}
10037:     }
10038:     # first look for a package that matches the requested part id
10039:     foreach my $package (@specifics) {
10040: 	my (undef,$pack_type,$pack_part)=@{$package};
10041: 	next if ($pack_part ne $part);
10042: 	if (defined($packagetab{"$pack_type&$name&default"})) {
10043: 	    return $packagetab{"$pack_type&$name&default"};
10044: 	}
10045:     }
10046:     # look for any possible matching non extension_ package
10047:     foreach my $package (@specifics) {
10048: 	my (undef,$pack_type,$pack_part)=@{$package};
10049: 	if (defined($packagetab{"$pack_type&$name&default"})) {
10050: 	    return $packagetab{"$pack_type&$name&default"};
10051: 	}
10052: 	if ($pack_type eq 'part') { $pack_part='0'; }
10053: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
10054: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
10055: 	}
10056:     }
10057:     # look for any posible extension_ match
10058:     foreach my $package (@extension) {
10059: 	my ($package,$pack_type)=@{$package};
10060: 	if (defined($packagetab{"$pack_type&$name&default"})) {
10061: 	    return $packagetab{"$pack_type&$name&default"};
10062: 	}
10063: 	if (defined($packagetab{$package."&$name&default"})) {
10064: 	    return $packagetab{$package."&$name&default"};
10065: 	}
10066:     }
10067:     # look for a global default setting
10068:     if ($do_default && defined($packagetab{"default&$name&default"})) {
10069: 	return $packagetab{"default&$name&default"};
10070:     }
10071:     return undef;
10072: }
10073: 
10074: sub add_prefix_and_part {
10075:     my ($prefix,$part)=@_;
10076:     my $keyroot;
10077:     if (defined($prefix) && $prefix !~ /^__/) {
10078: 	# prefix that has a part already
10079: 	$keyroot=$prefix;
10080:     } elsif (defined($prefix)) {
10081: 	# prefix that is missing a part
10082: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
10083:     } else {
10084: 	# no prefix at all
10085: 	if (defined($part)) { $keyroot='_'.$part; }
10086:     }
10087:     return $keyroot;
10088: }
10089: 
10090: # ---------------------------------------------------------------- Get metadata
10091: 
10092: my %metaentry;
10093: my %importedpartids;
10094: sub metadata {
10095:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
10096:     $uri=&declutter($uri);
10097:     # if it is a non metadata possible uri return quickly
10098:     if (($uri eq '') || 
10099: 	(($uri =~ m|^/*adm/|) && 
10100: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
10101:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
10102: 	return undef;
10103:     }
10104:     if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) 
10105: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
10106: 	return undef;
10107:     }
10108:     my $filename=$uri;
10109:     $uri=~s/\.meta$//;
10110: #
10111: # Is the metadata already cached?
10112: # Look at timestamp of caching
10113: # Everything is cached by the main uri, libraries are never directly cached
10114: #
10115:     if (!defined($liburi)) {
10116: 	my ($result,$cached)=&is_cached_new('meta',$uri);
10117: 	if (defined($cached)) { return $result->{':'.$what}; }
10118:     }
10119:     {
10120: # Imported parts would go here
10121:         my %importedids=();
10122:         my @origfileimportpartids=();
10123:         my $importedparts=0;
10124: #
10125: # Is this a recursive call for a library?
10126: #
10127: #	if (! exists($metacache{$uri})) {
10128: #	    $metacache{$uri}={};
10129: #	}
10130: 	my $cachetime = 60*60;
10131:         if ($liburi) {
10132: 	    $liburi=&declutter($liburi);
10133:             $filename=$liburi;
10134:         } else {
10135: 	    &devalidate_cache_new('meta',$uri);
10136: 	    undef(%metaentry);
10137: 	}
10138:         my %metathesekeys=();
10139:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
10140: 	my $metastring;
10141: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
10142: 	    my $which = &hreflocation('','/'.($liburi || $uri));
10143: 	    $metastring = 
10144: 		&Apache::lonnet::ssi_body($which,
10145: 					  ('grade_target' => 'meta'));
10146: 	    $cachetime = 1; # only want this cached in the child not long term
10147: 	} elsif (($uri !~ m -^(editupload)/-) && 
10148:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
10149: 	    my $file=&filelocation('',&clutter($filename));
10150: 	    #push(@{$metaentry{$uri.'.file'}},$file);
10151: 	    $metastring=&getfile($file);
10152: 	}
10153:         my $parser=HTML::LCParser->new(\$metastring);
10154:         my $token;
10155:         undef %metathesekeys;
10156:         while ($token=$parser->get_token) {
10157: 	    if ($token->[0] eq 'S') {
10158: 		if (defined($token->[2]->{'package'})) {
10159: #
10160: # This is a package - get package info
10161: #
10162: 		    my $package=$token->[2]->{'package'};
10163: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10164: 		    if (defined($token->[2]->{'id'})) { 
10165: 			$keyroot.='_'.$token->[2]->{'id'}; 
10166: 		    }
10167: 		    if ($metaentry{':packages'}) {
10168: 			$metaentry{':packages'}.=','.$package.$keyroot;
10169: 		    } else {
10170: 			$metaentry{':packages'}=$package.$keyroot;
10171: 		    }
10172: 		    foreach my $pack_entry (keys(%packagetab)) {
10173: 			my $part=$keyroot;
10174: 			$part=~s/^\_//;
10175: 			if ($pack_entry=~/^\Q$package\E\&/ || 
10176: 			    $pack_entry=~/^\Q$package\E_0\&/) {
10177: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
10178: 			    # ignore package.tab specified default values
10179:                             # here &package_tab_default() will fetch those
10180: 			    if ($subp eq 'default') { next; }
10181: 			    my $value=$packagetab{$pack_entry};
10182: 			    my $unikey;
10183: 			    if ($pack =~ /_0$/) {
10184: 				$unikey='parameter_0_'.$name;
10185: 				$part=0;
10186: 			    } else {
10187: 				$unikey='parameter'.$keyroot.'_'.$name;
10188: 			    }
10189: 			    if ($subp eq 'display') {
10190: 				$value.=' [Part: '.$part.']';
10191: 			    }
10192: 			    $metaentry{':'.$unikey.'.part'}=$part;
10193: 			    $metathesekeys{$unikey}=1;
10194: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10195: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
10196: 			    }
10197: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
10198: 				$metaentry{':'.$unikey}=
10199: 				    $metaentry{':'.$unikey.'.default'};
10200: 			    }
10201: 			}
10202: 		    }
10203: 		} else {
10204: #
10205: # This is not a package - some other kind of start tag
10206: #
10207: 		    my $entry=$token->[1];
10208: 		    my $unikey='';
10209: 
10210: 		    if ($entry eq 'import') {
10211: #
10212: # Importing a library here
10213: #
10214:                         my $location=$parser->get_text('/import');
10215:                         my $dir=$filename;
10216:                         $dir=~s|[^/]*$||;
10217:                         $location=&filelocation($dir,$location);
10218:                        
10219:                         my $importmode=$token->[2]->{'importmode'};
10220:                         if ($importmode eq 'problem') {
10221: # Import as problem/response
10222:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10223:                         } elsif ($importmode eq 'part') {
10224: # Import as part(s)
10225:                            $importedparts=1;
10226: # We need to get the original file and the imported file to get the part order correct
10227: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
10228: # Load and inspect original file
10229:                            if ($#origfileimportpartids<0) {
10230:                               undef(%importedpartids);
10231:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
10232:                               my $origfile=&getfile($origfilelocation);
10233:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10234:                            }
10235: 
10236: # Load and inspect imported file
10237:                            my $impfile=&getfile($location);
10238:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10239:                            if ($#impfilepartids>=0) {
10240: # This problem had parts
10241:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
10242:                            } else {
10243: # Importing by turning a single problem into a problem part
10244: # It gets the import-tags ID as part-ID
10245:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
10246:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
10247:                            }
10248:                         } else {
10249: # Normal import
10250:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10251:                            if (defined($token->[2]->{'id'})) {
10252:                               $unikey.='_'.$token->[2]->{'id'};
10253:                            }
10254:                         }
10255: 
10256: 			if ($depthcount<20) {
10257: 			    my $metadata = 
10258: 				&metadata($uri,'keys', $location,$unikey,
10259: 					  $depthcount+1);
10260: 			    foreach my $meta (split(',',$metadata)) {
10261: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
10262: 				$metathesekeys{$meta}=1;
10263: 			    }
10264: 			
10265:                         }
10266: 		    } else {
10267: #
10268: # Not importing, some other kind of non-package, non-library start tag
10269: # 
10270:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
10271:                         if (defined($token->[2]->{'id'})) {
10272:                             $unikey.='_'.$token->[2]->{'id'};
10273:                         }
10274: 			if (defined($token->[2]->{'name'})) { 
10275: 			    $unikey.='_'.$token->[2]->{'name'}; 
10276: 			}
10277: 			$metathesekeys{$unikey}=1;
10278: 			foreach my $param (@{$token->[3]}) {
10279: 			    $metaentry{':'.$unikey.'.'.$param} =
10280: 				$token->[2]->{$param};
10281: 			}
10282: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
10283: 			my $default=$metaentry{':'.$unikey.'.default'};
10284: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
10285: 		 # only ws inside the tag, and not in default, so use default
10286: 		 # as value
10287: 			    $metaentry{':'.$unikey}=$default;
10288: 			} elsif ( $internaltext =~ /\S/ ) {
10289: 		  # something interesting inside the tag
10290: 			    $metaentry{':'.$unikey}=$internaltext;
10291: 			} else {
10292: 		  # no interesting values, don't set a default
10293: 			}
10294: # end of not-a-package not-a-library import
10295: 		    }
10296: # end of not-a-package start tag
10297: 		}
10298: # the next is the end of "start tag"
10299: 	    }
10300: 	}
10301: 	my ($extension) = ($uri =~ /\.(\w+)$/);
10302: 	$extension = lc($extension);
10303: 	if ($extension eq 'htm') { $extension='html'; }
10304: 
10305: 	foreach my $key (keys(%packagetab)) {
10306: 	    #no specific packages #how's our extension
10307: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
10308: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
10309: 					 \%metathesekeys);
10310: 	}
10311: 
10312: 	if (!exists($metaentry{':packages'})
10313: 	    || $packagetab{"import_defaults&extension_$extension"}) {
10314: 	    foreach my $key (keys(%packagetab)) {
10315: 		#no specific packages well let's get default then
10316: 		if ($key!~/^default&/) { next; }
10317: 		&metadata_create_package_def($uri,$key,'default',
10318: 					     \%metathesekeys);
10319: 	    }
10320: 	}
10321: # are there custom rights to evaluate
10322: 	if ($metaentry{':copyright'} eq 'custom') {
10323: 
10324:     #
10325:     # Importing a rights file here
10326:     #
10327: 	    unless ($depthcount) {
10328: 		my $location=$metaentry{':customdistributionfile'};
10329: 		my $dir=$filename;
10330: 		$dir=~s|[^/]*$||;
10331: 		$location=&filelocation($dir,$location);
10332: 		my $rights_metadata =
10333: 		    &metadata($uri,'keys',$location,'_rights',
10334: 			      $depthcount+1);
10335: 		foreach my $rights (split(',',$rights_metadata)) {
10336: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
10337: 		    $metathesekeys{$rights}=1;
10338: 		}
10339: 	    }
10340: 	}
10341: 	# uniqifiy package listing
10342: 	my %seen;
10343: 	my @uniq_packages =
10344: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
10345: 	$metaentry{':packages'} = join(',',@uniq_packages);
10346: 
10347:         if ($importedparts) {
10348: # We had imported parts and need to rebuild partorder
10349:            $metaentry{':partorder'}='';
10350:            $metathesekeys{'partorder'}=1;
10351:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
10352:                if ($origfileimportpartids[$index] eq 'part') {
10353: # original part, part of the problem
10354:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
10355:                } else {
10356: # we have imported parts at this position
10357:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
10358:                }
10359:            }
10360:            $metaentry{':partorder'}=~s/^\,//;
10361:         }
10362: 
10363: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
10364: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
10365: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
10366: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
10367: # this is the end of "was not already recently cached
10368:     }
10369:     return $metaentry{':'.$what};
10370: }
10371: 
10372: sub metadata_create_package_def {
10373:     my ($uri,$key,$package,$metathesekeys)=@_;
10374:     my ($pack,$name,$subp)=split(/\&/,$key);
10375:     if ($subp eq 'default') { next; }
10376:     
10377:     if (defined($metaentry{':packages'})) {
10378: 	$metaentry{':packages'}.=','.$package;
10379:     } else {
10380: 	$metaentry{':packages'}=$package;
10381:     }
10382:     my $value=$packagetab{$key};
10383:     my $unikey;
10384:     $unikey='parameter_0_'.$name;
10385:     $metaentry{':'.$unikey.'.part'}=0;
10386:     $$metathesekeys{$unikey}=1;
10387:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10388: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
10389:     }
10390:     if (defined($metaentry{':'.$unikey.'.default'})) {
10391: 	$metaentry{':'.$unikey}=
10392: 	    $metaentry{':'.$unikey.'.default'};
10393:     }
10394: }
10395: 
10396: sub metadata_generate_part0 {
10397:     my ($metadata,$metacache,$uri) = @_;
10398:     my %allnames;
10399:     foreach my $metakey (keys(%$metadata)) {
10400: 	if ($metakey=~/^parameter\_(.*)/) {
10401: 	  my $part=$$metacache{':'.$metakey.'.part'};
10402: 	  my $name=$$metacache{':'.$metakey.'.name'};
10403: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
10404: 	    $allnames{$name}=$part;
10405: 	  }
10406: 	}
10407:     }
10408:     foreach my $name (keys(%allnames)) {
10409:       $$metadata{"parameter_0_$name"}=1;
10410:       my $key=":parameter_0_$name";
10411:       $$metacache{"$key.part"}='0';
10412:       $$metacache{"$key.name"}=$name;
10413:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
10414: 					   $allnames{$name}.'_'.$name.
10415: 					   '.type'};
10416:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
10417: 			     '.display'};
10418:       my $expr='[Part: '.$allnames{$name}.']';
10419:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
10420:       $$metacache{"$key.display"}=$olddis;
10421:     }
10422: }
10423: 
10424: # ------------------------------------------------------ Devalidate title cache
10425: 
10426: sub devalidate_title_cache {
10427:     my ($url)=@_;
10428:     if (!$env{'request.course.id'}) { return; }
10429:     my $symb=&symbread($url);
10430:     if (!$symb) { return; }
10431:     my $key=$env{'request.course.id'}."\0".$symb;
10432:     &devalidate_cache_new('title',$key);
10433: }
10434: 
10435: # ------------------------------------------------- Get the title of a course
10436: 
10437: sub current_course_title {
10438:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
10439: }
10440: # ------------------------------------------------- Get the title of a resource
10441: 
10442: sub gettitle {
10443:     my $urlsymb=shift;
10444:     my $symb=&symbread($urlsymb);
10445:     if ($symb) {
10446: 	my $key=$env{'request.course.id'}."\0".$symb;
10447: 	my ($result,$cached)=&is_cached_new('title',$key);
10448: 	if (defined($cached)) { 
10449: 	    return $result;
10450: 	}
10451: 	my ($map,$resid,$url)=&decode_symb($symb);
10452: 	my $title='';
10453: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
10454: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
10455: 	} else {
10456: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10457: 		    &GDBM_READER(),0640)) {
10458: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
10459: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
10460: 		untie(%bighash);
10461: 	    }
10462: 	}
10463: 	$title=~s/\&colon\;/\:/gs;
10464: 	if ($title) {
10465: # Remember both $symb and $title for dynamic metadata
10466:             $accesshash{$symb.'___crstitle'}=$title;
10467:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
10468: # Cache this title and then return it
10469: 	    return &do_cache_new('title',$key,$title,600);
10470: 	}
10471: 	$urlsymb=$url;
10472:     }
10473:     my $title=&metadata($urlsymb,'title');
10474:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
10475:     return $title;
10476: }
10477: 
10478: sub get_slot {
10479:     my ($which,$cnum,$cdom)=@_;
10480:     if (!$cnum || !$cdom) {
10481: 	(undef,my $courseid)=&whichuser();
10482: 	$cdom=$env{'course.'.$courseid.'.domain'};
10483: 	$cnum=$env{'course.'.$courseid.'.num'};
10484:     }
10485:     my $key=join("\0",'slots',$cdom,$cnum,$which);
10486:     my %slotinfo;
10487:     if (exists($remembered{$key})) {
10488: 	$slotinfo{$which} = $remembered{$key};
10489:     } else {
10490: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
10491: 	&Apache::lonhomework::showhash(%slotinfo);
10492: 	my ($tmp)=keys(%slotinfo);
10493: 	if ($tmp=~/^error:/) { return (); }
10494: 	$remembered{$key} = $slotinfo{$which};
10495:     }
10496:     if (ref($slotinfo{$which}) eq 'HASH') {
10497: 	return %{$slotinfo{$which}};
10498:     }
10499:     return $slotinfo{$which};
10500: }
10501: 
10502: sub get_reservable_slots {
10503:     my ($cnum,$cdom,$uname,$udom) = @_;
10504:     my $now = time;
10505:     my $reservable_info;
10506:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
10507:     if (exists($remembered{$key})) {
10508:         $reservable_info = $remembered{$key};
10509:     } else {
10510:         my %resv;
10511:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
10512:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
10513:         $reservable_info = \%resv;
10514:         $remembered{$key} = $reservable_info;
10515:     }
10516:     return $reservable_info;
10517: }
10518: 
10519: sub get_course_slots {
10520:     my ($cnum,$cdom) = @_;
10521:     my $hashid=$cnum.':'.$cdom;
10522:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
10523:     if (defined($cached)) {
10524:         if (ref($result) eq 'HASH') {
10525:             return %{$result};
10526:         }
10527:     } else {
10528:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
10529:         my ($tmp) = keys(%slots);
10530:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
10531:             &do_cache_new('allslots',$hashid,\%slots,600);
10532:             return %slots;
10533:         }
10534:     }
10535:     return;
10536: }
10537: 
10538: sub devalidate_slots_cache {
10539:     my ($cnum,$cdom)=@_;
10540:     my $hashid=$cnum.':'.$cdom;
10541:     &devalidate_cache_new('allslots',$hashid);
10542: }
10543: 
10544: sub get_coursechange {
10545:     my ($cdom,$cnum) = @_;
10546:     if ($cdom eq '' || $cnum eq '') {
10547:         return unless ($env{'request.course.id'});
10548:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10549:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10550:     }
10551:     my $hashid=$cdom.'_'.$cnum;
10552:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
10553:     if ((defined($cached)) && ($change ne '')) {
10554:         return $change;
10555:     } else {
10556:         my %crshash;
10557:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
10558:         if ($crshash{'internal.contentchange'} eq '') {
10559:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
10560:             if ($change eq '') {
10561:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
10562:                 $change = $crshash{'internal.created'};
10563:             }
10564:         } else {
10565:             $change = $crshash{'internal.contentchange'};
10566:         }
10567:         my $cachetime = 600;
10568:         &do_cache_new('crschange',$hashid,$change,$cachetime);
10569:     }
10570:     return $change;
10571: }
10572: 
10573: sub devalidate_coursechange_cache {
10574:     my ($cnum,$cdom)=@_;
10575:     my $hashid=$cnum.':'.$cdom;
10576:     &devalidate_cache_new('crschange',$hashid);
10577: }
10578: 
10579: # ------------------------------------------------- Update symbolic store links
10580: 
10581: sub symblist {
10582:     my ($mapname,%newhash)=@_;
10583:     $mapname=&deversion(&declutter($mapname));
10584:     my %hash;
10585:     if (($env{'request.course.fn'}) && (%newhash)) {
10586:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
10587:                       &GDBM_WRCREAT(),0640)) {
10588: 	    foreach my $url (keys(%newhash)) {
10589: 		next if ($url eq 'last_known'
10590: 			 && $env{'form.no_update_last_known'});
10591: 		$hash{declutter($url)}=&encode_symb($mapname,
10592: 						    $newhash{$url}->[1],
10593: 						    $newhash{$url}->[0]);
10594:             }
10595:             if (untie(%hash)) {
10596: 		return 'ok';
10597:             }
10598:         }
10599:     }
10600:     return 'error';
10601: }
10602: 
10603: # --------------------------------------------------------------- Verify a symb
10604: 
10605: sub symbverify {
10606:     my ($symb,$thisurl,$encstate)=@_;
10607:     my $thisfn=$thisurl;
10608:     $thisfn=&declutter($thisfn);
10609: # direct jump to resource in page or to a sequence - will construct own symbs
10610:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
10611: # check URL part
10612:     my ($map,$resid,$url)=&decode_symb($symb);
10613: 
10614:     unless ($url eq $thisfn) { return 0; }
10615: 
10616:     $symb=&symbclean($symb);
10617:     $thisurl=&deversion($thisurl);
10618:     $thisfn=&deversion($thisfn);
10619: 
10620:     my %bighash;
10621:     my $okay=0;
10622: 
10623:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10624:                             &GDBM_READER(),0640)) {
10625:         my $noclutter;
10626:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
10627:             $thisurl =~ s/\?.+$//;
10628:             if ($map =~ m{^uploaded/.+\.page$}) {
10629:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
10630:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
10631:                 $noclutter = 1;
10632:             }
10633:         }
10634:         my $ids;
10635:         if ($noclutter) {
10636:             $ids=$bighash{'ids_'.$thisurl};
10637:         } else {
10638:             $ids=$bighash{'ids_'.&clutter($thisurl)};
10639:         }
10640:         unless ($ids) {
10641:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
10642:             $ids=$bighash{$idkey};
10643:         }
10644:         if ($ids) {
10645: # ------------------------------------------------------------------- Has ID(s)
10646:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
10647:                 $symb =~ s/\?.+$//;
10648:             }
10649: 	    foreach my $id (split(/\,/,$ids)) {
10650: 	       my ($mapid,$resid)=split(/\./,$id);
10651:                if (
10652:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
10653:    eq $symb) {
10654:                    if (ref($encstate)) {
10655:                        $$encstate = $bighash{'encrypted_'.$id};
10656:                    }
10657: 		   if (($env{'request.role.adv'}) ||
10658: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
10659:                        ($thisurl eq '/adm/navmaps')) {
10660: 		       $okay=1;
10661:                        last;
10662: 		   }
10663: 	       }
10664: 	   }
10665:         }
10666: 	untie(%bighash);
10667:     }
10668:     return $okay;
10669: }
10670: 
10671: # --------------------------------------------------------------- Clean-up symb
10672: 
10673: sub symbclean {
10674:     my $symb=shift;
10675:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10676: # remove version from map
10677:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
10678: 
10679: # remove version from URL
10680:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
10681: 
10682: # remove wrapper
10683: 
10684:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
10685:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
10686:     return $symb;
10687: }
10688: 
10689: # ---------------------------------------------- Split symb to find map and url
10690: 
10691: sub encode_symb {
10692:     my ($map,$resid,$url)=@_;
10693:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
10694: }
10695: 
10696: sub decode_symb {
10697:     my $symb=shift;
10698:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10699:     my ($map,$resid,$url)=split(/___/,$symb);
10700:     return (&fixversion($map),$resid,&fixversion($url));
10701: }
10702: 
10703: sub fixversion {
10704:     my $fn=shift;
10705:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
10706:     my %bighash;
10707:     my $uri=&clutter($fn);
10708:     my $key=$env{'request.course.id'}.'_'.$uri;
10709: # is this cached?
10710:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
10711:     if (defined($cached)) { return $result; }
10712: # unfortunately not cached, or expired
10713:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10714: 	    &GDBM_READER(),0640)) {
10715:  	if ($bighash{'version_'.$uri}) {
10716:  	    my $version=$bighash{'version_'.$uri};
10717:  	    unless (($version eq 'mostrecent') || 
10718: 		    ($version==&getversion($uri))) {
10719:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
10720:  	    }
10721:  	}
10722:  	untie %bighash;
10723:     }
10724:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
10725: }
10726: 
10727: sub deversion {
10728:     my $url=shift;
10729:     $url=~s/\.\d+\.(\w+)$/\.$1/;
10730:     return $url;
10731: }
10732: 
10733: # ------------------------------------------------------ Return symb list entry
10734: 
10735: sub symbread {
10736:     my ($thisfn,$donotrecurse)=@_;
10737:     my $cache_str;
10738:     if ($thisfn ne '') {
10739:         $cache_str='request.symbread.cached.'.$thisfn;
10740:         if ($env{$cache_str} ne '') {
10741:             return $env{$cache_str};
10742:         }
10743:     } else {
10744: # no filename provided? try from environment
10745:         if ($env{'request.symb'}) {
10746: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
10747: 	}
10748: 	$thisfn=$env{'request.filename'};
10749:     }
10750:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
10751: # is that filename actually a symb? Verify, clean, and return
10752:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
10753: 	if (&symbverify($thisfn,$1)) {
10754: 	    return $env{$cache_str}=&symbclean($thisfn);
10755: 	}
10756:     }
10757:     $thisfn=declutter($thisfn);
10758:     my %hash;
10759:     my %bighash;
10760:     my $syval='';
10761:     if (($env{'request.course.fn'}) && ($thisfn)) {
10762:         my $targetfn = $thisfn;
10763:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
10764:             $targetfn = 'adm/wrapper/'.$thisfn;
10765:         }
10766: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
10767: 	    $targetfn=$1;
10768: 	}
10769:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
10770:                       &GDBM_READER(),0640)) {
10771: 	    $syval=$hash{$targetfn};
10772:             untie(%hash);
10773:         }
10774: # ---------------------------------------------------------- There was an entry
10775:         if ($syval) {
10776: 	    #unless ($syval=~/\_\d+$/) {
10777: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
10778: 		    #&appenv({'request.ambiguous' => $thisfn});
10779: 		    #return $env{$cache_str}='';
10780: 		#}    
10781: 		#$syval.=$1;
10782: 	    #}
10783:         } else {
10784: # ------------------------------------------------------- Was not in symb table
10785:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10786:                             &GDBM_READER(),0640)) {
10787: # ---------------------------------------------- Get ID(s) for current resource
10788:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
10789:               unless ($ids) { 
10790:                  $ids=$bighash{'ids_/'.$thisfn};
10791:               }
10792:               unless ($ids) {
10793: # alias?
10794: 		  $ids=$bighash{'mapalias_'.$thisfn};
10795:               }
10796:               if ($ids) {
10797: # ------------------------------------------------------------------- Has ID(s)
10798:                  my @possibilities=split(/\,/,$ids);
10799:                  if ($#possibilities==0) {
10800: # ----------------------------------------------- There is only one possibility
10801: 		     my ($mapid,$resid)=split(/\./,$ids);
10802: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
10803: 						    $resid,$thisfn);
10804:                  } elsif (!$donotrecurse) {
10805: # ------------------------------------------ There is more than one possibility
10806:                      my $realpossible=0;
10807:                      foreach my $id (@possibilities) {
10808: 			 my $file=$bighash{'src_'.$id};
10809:                          if (&allowed('bre',$file)) {
10810:          		    my ($mapid,$resid)=split(/\./,$id);
10811:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
10812: 				$realpossible++;
10813:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
10814: 						    $resid,$thisfn);
10815:                             }
10816: 			 }
10817:                      }
10818: 		     if ($realpossible!=1) { $syval=''; }
10819:                  } else {
10820:                      $syval='';
10821:                  }
10822: 	      }
10823:               untie(%bighash)
10824:            }
10825:         }
10826:         if ($syval) {
10827: 	    return $env{$cache_str}=$syval;
10828:         }
10829:     }
10830:     &appenv({'request.ambiguous' => $thisfn});
10831:     return $env{$cache_str}='';
10832: }
10833: 
10834: # ---------------------------------------------------------- Return random seed
10835: 
10836: sub numval {
10837:     my $txt=shift;
10838:     $txt=~tr/A-J/0-9/;
10839:     $txt=~tr/a-j/0-9/;
10840:     $txt=~tr/K-T/0-9/;
10841:     $txt=~tr/k-t/0-9/;
10842:     $txt=~tr/U-Z/0-5/;
10843:     $txt=~tr/u-z/0-5/;
10844:     $txt=~s/\D//g;
10845:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
10846:     return int($txt);
10847: }
10848: 
10849: sub numval2 {
10850:     my $txt=shift;
10851:     $txt=~tr/A-J/0-9/;
10852:     $txt=~tr/a-j/0-9/;
10853:     $txt=~tr/K-T/0-9/;
10854:     $txt=~tr/k-t/0-9/;
10855:     $txt=~tr/U-Z/0-5/;
10856:     $txt=~tr/u-z/0-5/;
10857:     $txt=~s/\D//g;
10858:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10859:     my $total;
10860:     foreach my $val (@txts) { $total+=$val; }
10861:     if ($_64bit) { if ($total > 2**32) { return -1; } }
10862:     return int($total);
10863: }
10864: 
10865: sub numval3 {
10866:     use integer;
10867:     my $txt=shift;
10868:     $txt=~tr/A-J/0-9/;
10869:     $txt=~tr/a-j/0-9/;
10870:     $txt=~tr/K-T/0-9/;
10871:     $txt=~tr/k-t/0-9/;
10872:     $txt=~tr/U-Z/0-5/;
10873:     $txt=~tr/u-z/0-5/;
10874:     $txt=~s/\D//g;
10875:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10876:     my $total;
10877:     foreach my $val (@txts) { $total+=$val; }
10878:     if ($_64bit) { $total=(($total<<32)>>32); }
10879:     return $total;
10880: }
10881: 
10882: sub digest {
10883:     my ($data)=@_;
10884:     my $digest=&Digest::MD5::md5($data);
10885:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
10886:     my ($e,$f);
10887:     {
10888:         use integer;
10889:         $e=($a+$b);
10890:         $f=($c+$d);
10891:         if ($_64bit) {
10892:             $e=(($e<<32)>>32);
10893:             $f=(($f<<32)>>32);
10894:         }
10895:     }
10896:     if (wantarray) {
10897: 	return ($e,$f);
10898:     } else {
10899: 	my $g;
10900: 	{
10901: 	    use integer;
10902: 	    $g=($e+$f);
10903: 	    if ($_64bit) {
10904: 		$g=(($g<<32)>>32);
10905: 	    }
10906: 	}
10907: 	return $g;
10908:     }
10909: }
10910: 
10911: sub latest_rnd_algorithm_id {
10912:     return '64bit5';
10913: }
10914: 
10915: sub get_rand_alg {
10916:     my ($courseid)=@_;
10917:     if (!$courseid) { $courseid=(&whichuser())[1]; }
10918:     if ($courseid) {
10919: 	return $env{"course.$courseid.rndseed"};
10920:     }
10921:     return &latest_rnd_algorithm_id();
10922: }
10923: 
10924: sub validCODE {
10925:     my ($CODE)=@_;
10926:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
10927:     return 0;
10928: }
10929: 
10930: sub getCODE {
10931:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
10932:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
10933: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
10934: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
10935: 	return $Apache::lonhomework::history{'resource.CODE'};
10936:     }
10937:     return undef;
10938: }
10939: #
10940: #  Determines the random seed for a specific context:
10941: #
10942: # parameters:
10943: #   symb      - in course context the symb for the seed.
10944: #   course_id - The course id of the form domain_coursenum.
10945: #   domain    - Domain for the user.
10946: #   course    - Course for the user.
10947: #   cenv      - environment of the course.
10948: #
10949: # NOTE:
10950: #   All parameters are picked out of the environment if missing
10951: #   or not defined.
10952: #   If a symb cannot be determined the current time is used instead.
10953: #
10954: #  For a given well defined symb, courside, domain, username,
10955: #  and course environment, the seed is reproducible.
10956: #
10957: sub rndseed {
10958:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
10959:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
10960:     if (!defined($symb)) {
10961: 	unless ($symb=$wsymb) { return time; }
10962:     }
10963:     if (!defined $courseid) { 
10964: 	$courseid=$wcourseid; 
10965:     }
10966:     if (!defined $domain) { $domain=$wdomain; }
10967:     if (!defined $username) { $username=$wusername }
10968: 
10969:     my $which;
10970:     if (defined($cenv->{'rndseed'})) {
10971: 	$which = $cenv->{'rndseed'};
10972:     } else {
10973: 	$which =&get_rand_alg($courseid);
10974:     }
10975:     if (defined(&getCODE())) {
10976: 
10977: 	if ($which eq '64bit5') {
10978: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
10979: 	} elsif ($which eq '64bit4') {
10980: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
10981: 	} else {
10982: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
10983: 	}
10984:     } elsif ($which eq '64bit5') {
10985: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
10986:     } elsif ($which eq '64bit4') {
10987: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
10988:     } elsif ($which eq '64bit3') {
10989: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
10990:     } elsif ($which eq '64bit2') {
10991: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
10992:     } elsif ($which eq '64bit') {
10993: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
10994:     }
10995:     return &rndseed_32bit($symb,$courseid,$domain,$username);
10996: }
10997: 
10998: sub rndseed_32bit {
10999:     my ($symb,$courseid,$domain,$username)=@_;
11000:     {
11001: 	use integer;
11002: 	my $symbchck=unpack("%32C*",$symb) << 27;
11003: 	my $symbseed=numval($symb) << 22;
11004: 	my $namechck=unpack("%32C*",$username) << 17;
11005: 	my $nameseed=numval($username) << 12;
11006: 	my $domainseed=unpack("%32C*",$domain) << 7;
11007: 	my $courseseed=unpack("%32C*",$courseid);
11008: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
11009: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11010: 	#&logthis("rndseed :$num:$symb");
11011: 	if ($_64bit) { $num=(($num<<32)>>32); }
11012: 	return $num;
11013:     }
11014: }
11015: 
11016: sub rndseed_64bit {
11017:     my ($symb,$courseid,$domain,$username)=@_;
11018:     {
11019: 	use integer;
11020: 	my $symbchck=unpack("%32S*",$symb) << 21;
11021: 	my $symbseed=numval($symb) << 10;
11022: 	my $namechck=unpack("%32S*",$username);
11023: 	
11024: 	my $nameseed=numval($username) << 21;
11025: 	my $domainseed=unpack("%32S*",$domain) << 10;
11026: 	my $courseseed=unpack("%32S*",$courseid);
11027: 	
11028: 	my $num1=$symbchck+$symbseed+$namechck;
11029: 	my $num2=$nameseed+$domainseed+$courseseed;
11030: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11031: 	#&logthis("rndseed :$num:$symb");
11032: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11033: 	return "$num1,$num2";
11034:     }
11035: }
11036: 
11037: sub rndseed_64bit2 {
11038:     my ($symb,$courseid,$domain,$username)=@_;
11039:     {
11040: 	use integer;
11041: 	# strings need to be an even # of cahracters long, it it is odd the
11042:         # last characters gets thrown away
11043: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
11044: 	my $symbseed=numval($symb) << 10;
11045: 	my $namechck=unpack("%32S*",$username.' ');
11046: 	
11047: 	my $nameseed=numval($username) << 21;
11048: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
11049: 	my $courseseed=unpack("%32S*",$courseid.' ');
11050: 	
11051: 	my $num1=$symbchck+$symbseed+$namechck;
11052: 	my $num2=$nameseed+$domainseed+$courseseed;
11053: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11054: 	#&logthis("rndseed :$num:$symb");
11055: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11056: 	return "$num1,$num2";
11057:     }
11058: }
11059: 
11060: sub rndseed_64bit3 {
11061:     my ($symb,$courseid,$domain,$username)=@_;
11062:     {
11063: 	use integer;
11064: 	# strings need to be an even # of cahracters long, it it is odd the
11065:         # last characters gets thrown away
11066: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
11067: 	my $symbseed=numval2($symb) << 10;
11068: 	my $namechck=unpack("%32S*",$username.' ');
11069: 	
11070: 	my $nameseed=numval2($username) << 21;
11071: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
11072: 	my $courseseed=unpack("%32S*",$courseid.' ');
11073: 	
11074: 	my $num1=$symbchck+$symbseed+$namechck;
11075: 	my $num2=$nameseed+$domainseed+$courseseed;
11076: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11077: 	#&logthis("rndseed :$num1:$num2:$_64bit");
11078: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11079: 	
11080: 	return "$num1:$num2";
11081:     }
11082: }
11083: 
11084: sub rndseed_64bit4 {
11085:     my ($symb,$courseid,$domain,$username)=@_;
11086:     {
11087: 	use integer;
11088: 	# strings need to be an even # of cahracters long, it it is odd the
11089:         # last characters gets thrown away
11090: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
11091: 	my $symbseed=numval3($symb) << 10;
11092: 	my $namechck=unpack("%32S*",$username.' ');
11093: 	
11094: 	my $nameseed=numval3($username) << 21;
11095: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
11096: 	my $courseseed=unpack("%32S*",$courseid.' ');
11097: 	
11098: 	my $num1=$symbchck+$symbseed+$namechck;
11099: 	my $num2=$nameseed+$domainseed+$courseseed;
11100: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11101: 	#&logthis("rndseed :$num1:$num2:$_64bit");
11102: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11103: 	
11104: 	return "$num1:$num2";
11105:     }
11106: }
11107: 
11108: sub rndseed_64bit5 {
11109:     my ($symb,$courseid,$domain,$username)=@_;
11110:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
11111:     return "$num1:$num2";
11112: }
11113: 
11114: sub rndseed_CODE_64bit {
11115:     my ($symb,$courseid,$domain,$username)=@_;
11116:     {
11117: 	use integer;
11118: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
11119: 	my $symbseed=numval2($symb);
11120: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11121: 	my $CODEseed=numval(&getCODE());
11122: 	my $courseseed=unpack("%32S*",$courseid.' ');
11123: 	my $num1=$symbseed+$CODEchck;
11124: 	my $num2=$CODEseed+$courseseed+$symbchck;
11125: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11126: 	#&logthis("rndseed :$num1:$num2:$symb");
11127: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
11128: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
11129: 	return "$num1:$num2";
11130:     }
11131: }
11132: 
11133: sub rndseed_CODE_64bit4 {
11134:     my ($symb,$courseid,$domain,$username)=@_;
11135:     {
11136: 	use integer;
11137: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
11138: 	my $symbseed=numval3($symb);
11139: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11140: 	my $CODEseed=numval3(&getCODE());
11141: 	my $courseseed=unpack("%32S*",$courseid.' ');
11142: 	my $num1=$symbseed+$CODEchck;
11143: 	my $num2=$CODEseed+$courseseed+$symbchck;
11144: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11145: 	#&logthis("rndseed :$num1:$num2:$symb");
11146: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
11147: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
11148: 	return "$num1:$num2";
11149:     }
11150: }
11151: 
11152: sub rndseed_CODE_64bit5 {
11153:     my ($symb,$courseid,$domain,$username)=@_;
11154:     my $code = &getCODE();
11155:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
11156:     return "$num1:$num2";
11157: }
11158: 
11159: sub setup_random_from_rndseed {
11160:     my ($rndseed)=@_;
11161:     if ($rndseed =~/([,:])/) {
11162: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
11163: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
11164:     } else {
11165: 	&Math::Random::random_set_seed_from_phrase($rndseed);
11166:     }
11167: }
11168: 
11169: sub latest_receipt_algorithm_id {
11170:     return 'receipt3';
11171: }
11172: 
11173: sub recunique {
11174:     my $fucourseid=shift;
11175:     my $unique;
11176:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
11177: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
11178: 	$unique=$env{"course.$fucourseid.internal.encseed"};
11179:     } else {
11180: 	$unique=$perlvar{'lonReceipt'};
11181:     }
11182:     return unpack("%32C*",$unique);
11183: }
11184: 
11185: sub recprefix {
11186:     my $fucourseid=shift;
11187:     my $prefix;
11188:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
11189: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
11190: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
11191:     } else {
11192: 	$prefix=$perlvar{'lonHostID'};
11193:     }
11194:     return unpack("%32C*",$prefix);
11195: }
11196: 
11197: sub ireceipt {
11198:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
11199: 
11200:     my $return =&recprefix($fucourseid).'-';
11201: 
11202:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
11203: 	$env{'request.state'} eq 'construct') {
11204: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
11205: 	return $return;
11206:     }
11207: 
11208:     my $cuname=unpack("%32C*",$funame);
11209:     my $cudom=unpack("%32C*",$fudom);
11210:     my $cucourseid=unpack("%32C*",$fucourseid);
11211:     my $cusymb=unpack("%32C*",$fusymb);
11212:     my $cunique=&recunique($fucourseid);
11213:     my $cpart=unpack("%32S*",$part);
11214:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
11215: 
11216: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
11217: 			       
11218: 	$return.= ($cunique%$cuname+
11219: 		   $cunique%$cudom+
11220: 		   $cusymb%$cuname+
11221: 		   $cusymb%$cudom+
11222: 		   $cucourseid%$cuname+
11223: 		   $cucourseid%$cudom+
11224: 		   $cpart%$cuname+
11225: 		   $cpart%$cudom);
11226:     } else {
11227: 	$return.= ($cunique%$cuname+
11228: 		   $cunique%$cudom+
11229: 		   $cusymb%$cuname+
11230: 		   $cusymb%$cudom+
11231: 		   $cucourseid%$cuname+
11232: 		   $cucourseid%$cudom);
11233:     }
11234:     return $return;
11235: }
11236: 
11237: sub receipt {
11238:     my ($part)=@_;
11239:     my ($symb,$courseid,$domain,$name) = &whichuser();
11240:     return &ireceipt($name,$domain,$courseid,$symb,$part);
11241: }
11242: 
11243: sub whichuser {
11244:     my ($passedsymb)=@_;
11245:     my ($symb,$courseid,$domain,$name,$publicuser);
11246:     if (defined($env{'form.grade_symb'})) {
11247: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
11248: 	my $allowed=&allowed('vgr',$tmp_courseid);
11249: 	if (!$allowed &&
11250: 	    exists($env{'request.course.sec'}) &&
11251: 	    $env{'request.course.sec'} !~ /^\s*$/) {
11252: 	    $allowed=&allowed('vgr',$tmp_courseid.
11253: 			      '/'.$env{'request.course.sec'});
11254: 	}
11255: 	if ($allowed) {
11256: 	    ($symb)=&get_env_multiple('form.grade_symb');
11257: 	    $courseid=$tmp_courseid;
11258: 	    ($domain)=&get_env_multiple('form.grade_domain');
11259: 	    ($name)=&get_env_multiple('form.grade_username');
11260: 	    return ($symb,$courseid,$domain,$name,$publicuser);
11261: 	}
11262:     }
11263:     if (!$passedsymb) {
11264: 	$symb=&symbread();
11265:     } else {
11266: 	$symb=$passedsymb;
11267:     }
11268:     $courseid=$env{'request.course.id'};
11269:     $domain=$env{'user.domain'};
11270:     $name=$env{'user.name'};
11271:     if ($name eq 'public' && $domain eq 'public') {
11272: 	if (!defined($env{'form.username'})) {
11273: 	    $env{'form.username'}.=time.rand(10000000);
11274: 	}
11275: 	$name.=$env{'form.username'};
11276:     }
11277:     return ($symb,$courseid,$domain,$name,$publicuser);
11278: 
11279: }
11280: 
11281: # ------------------------------------------------------------ Serves up a file
11282: # returns either the contents of the file or 
11283: # -1 if the file doesn't exist
11284: #
11285: # if the target is a file that was uploaded via DOCS, 
11286: # a check will be made to see if a current copy exists on the local server,
11287: # if it does this will be served, otherwise a copy will be retrieved from
11288: # the home server for the course and stored in /home/httpd/html/userfiles on
11289: # the local server.   
11290: 
11291: sub getfile {
11292:     my ($file) = @_;
11293:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
11294:     &repcopy($file);
11295:     return &readfile($file);
11296: }
11297: 
11298: sub repcopy_userfile {
11299:     my ($file)=@_;
11300:     my $londocroot = $perlvar{'lonDocRoot'};
11301:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
11302:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
11303:     my ($cdom,$cnum,$filename) = 
11304: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
11305:     my $uri="/uploaded/$cdom/$cnum/$filename";
11306:     if (-e "$file") {
11307: # we already have a local copy, check it out
11308: 	my @fileinfo = stat($file);
11309: 	my $rtncode;
11310: 	my $info;
11311: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
11312: 	if ($lwpresp ne 'ok') {
11313: # there is no such file anymore, even though we had a local copy
11314: 	    if ($rtncode eq '404') {
11315: 		unlink($file);
11316: 	    }
11317: 	    return -1;
11318: 	}
11319: 	if ($info < $fileinfo[9]) {
11320: # nice, the file we have is up-to-date, just say okay
11321: 	    return 'ok';
11322: 	} else {
11323: # the file is outdated, get rid of it
11324: 	    unlink($file);
11325: 	}
11326:     }
11327: # one way or the other, at this point, we don't have the file
11328: # construct the correct path for the file
11329:     my @parts = ($cdom,$cnum); 
11330:     if ($filename =~ m|^(.+)/[^/]+$|) {
11331: 	push @parts, split(/\//,$1);
11332:     }
11333:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
11334:     foreach my $part (@parts) {
11335: 	$path .= '/'.$part;
11336: 	if (!-e $path) {
11337: 	    mkdir($path,0770);
11338: 	}
11339:     }
11340: # now the path exists for sure
11341: # get a user agent
11342:     my $ua=new LWP::UserAgent;
11343:     my $transferfile=$file.'.in.transfer';
11344: # FIXME: this should flock
11345:     if (-e $transferfile) { return 'ok'; }
11346:     my $request;
11347:     $uri=~s/^\///;
11348:     my $homeserver = &homeserver($cnum,$cdom);
11349:     my $protocol = $protocol{$homeserver};
11350:     $protocol = 'http' if ($protocol ne 'https');
11351:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
11352:     my $response=$ua->request($request,$transferfile);
11353: # did it work?
11354:     if ($response->is_error()) {
11355: 	unlink($transferfile);
11356: 	&logthis("Userfile repcopy failed for $uri");
11357: 	return -1;
11358:     }
11359: # worked, rename the transfer file
11360:     rename($transferfile,$file);
11361:     return 'ok';
11362: }
11363: 
11364: sub tokenwrapper {
11365:     my $uri=shift;
11366:     $uri=~s|^https?\://([^/]+)||;
11367:     $uri=~s|^/||;
11368:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
11369:     my $token=$1;
11370:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
11371:     if ($udom && $uname && $file) {
11372: 	$file=~s|(\?\.*)*$||;
11373:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
11374:         my $homeserver = &homeserver($uname,$udom);
11375:         my $protocol = $protocol{$homeserver};
11376:         $protocol = 'http' if ($protocol ne 'https');
11377:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
11378:                (($uri=~/\?/)?'&':'?').'token='.$token.
11379:                                '&tokenissued='.$perlvar{'lonHostID'};
11380:     } else {
11381:         return '/adm/notfound.html';
11382:     }
11383: }
11384: 
11385: # call with reqtype HEAD: get last modification time
11386: # call with reqtype GET: get the file contents
11387: # Do not call this with reqtype GET for large files! It loads everything into memory
11388: #
11389: sub getuploaded {
11390:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
11391:     $uri=~s/^\///;
11392:     my $homeserver = &homeserver($cnum,$cdom);
11393:     my $protocol = $protocol{$homeserver};
11394:     $protocol = 'http' if ($protocol ne 'https');
11395:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
11396:     my $ua=new LWP::UserAgent;
11397:     my $request=new HTTP::Request($reqtype,$uri);
11398:     my $response=$ua->request($request);
11399:     $$rtncode = $response->code;
11400:     if (! $response->is_success()) {
11401: 	return 'failed';
11402:     }      
11403:     if ($reqtype eq 'HEAD') {
11404: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
11405:     } elsif ($reqtype eq 'GET') {
11406: 	$$info = $response->content;
11407:     }
11408:     return 'ok';
11409: }
11410: 
11411: sub readfile {
11412:     my $file = shift;
11413:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
11414:     my $fh;
11415:     open($fh,"<$file");
11416:     my $a='';
11417:     while (my $line = <$fh>) { $a .= $line; }
11418:     return $a;
11419: }
11420: 
11421: sub filelocation {
11422:     my ($dir,$file) = @_;
11423:     my $location;
11424:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
11425: 
11426:     if ($file =~ m-^/adm/-) {
11427: 	$file=~s-^/adm/wrapper/-/-;
11428: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
11429:     }
11430: 
11431:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
11432:         $location = $file;
11433:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
11434:         my ($udom,$uname,$filename)=
11435:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
11436:         my $home=&homeserver($uname,$udom);
11437:         my $is_me=0;
11438:         my @ids=&current_machine_ids();
11439:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
11440:         if ($is_me) {
11441:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
11442:         } else {
11443:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
11444:   	      $udom.'/'.$uname.'/'.$filename;
11445:         }
11446:     } elsif ($file =~ m-^/adm/-) {
11447: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
11448:     } else {
11449:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
11450:         $file=~s:^/(res|priv)/:/:;
11451:         my $space=$1;
11452:         if ( !( $file =~ m:^/:) ) {
11453:             $location = $dir. '/'.$file;
11454:         } else {
11455:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
11456:         }
11457:     }
11458:     $location=~s://+:/:g; # remove duplicate /
11459:     while ($location=~m{/\.\./}) {
11460: 	if ($location =~ m{/[^/]+/\.\./}) {
11461: 	    $location=~ s{/[^/]+/\.\./}{/}g;
11462: 	} else {
11463: 	    $location=~ s{/\.\./}{/}g;
11464: 	}
11465:     } #remove dir/..
11466:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
11467:     return $location;
11468: }
11469: 
11470: sub hreflocation {
11471:     my ($dir,$file)=@_;
11472:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
11473: 	$file=filelocation($dir,$file);
11474:     } elsif ($file=~m-^/adm/-) {
11475: 	$file=~s-^/adm/wrapper/-/-;
11476: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
11477:     }
11478:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
11479: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
11480:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
11481: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
11482: 	        {/uploaded/$1/$2/}x;
11483:     }
11484:     if ($file=~ m{^/userfiles/}) {
11485: 	$file =~ s{^/userfiles/}{/uploaded/};
11486:     }
11487:     return $file;
11488: }
11489: 
11490: 
11491: 
11492: 
11493: 
11494: sub current_machine_domains {
11495:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
11496: }
11497: 
11498: sub machine_domains {
11499:     my ($hostname) = @_;
11500:     my @domains;
11501:     my %hostname = &all_hostnames();
11502:     while( my($id, $name) = each(%hostname)) {
11503: #	&logthis("-$id-$name-$hostname-");
11504: 	if ($hostname eq $name) {
11505: 	    push(@domains,&host_domain($id));
11506: 	}
11507:     }
11508:     return @domains;
11509: }
11510: 
11511: sub current_machine_ids {
11512:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
11513: }
11514: 
11515: sub machine_ids {
11516:     my ($hostname) = @_;
11517:     $hostname ||= &hostname($perlvar{'lonHostID'});
11518:     my @ids;
11519:     my %name_to_host = &all_names();
11520:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
11521: 	return @{ $name_to_host{$hostname} };
11522:     }
11523:     return;
11524: }
11525: 
11526: sub additional_machine_domains {
11527:     my @domains;
11528:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
11529:     while( my $line = <$fh>) {
11530:         $line =~ s/\s//g;
11531:         push(@domains,$line);
11532:     }
11533:     return @domains;
11534: }
11535: 
11536: sub default_login_domain {
11537:     my $domain = $perlvar{'lonDefDomain'};
11538:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
11539:     foreach my $posdom (&current_machine_domains(),
11540:                         &additional_machine_domains()) {
11541:         if (lc($posdom) eq lc($testdomain)) {
11542:             $domain=$posdom;
11543:             last;
11544:         }
11545:     }
11546:     return $domain;
11547: }
11548: 
11549: # ------------------------------------------------------------- Declutters URLs
11550: 
11551: sub declutter {
11552:     my $thisfn=shift;
11553:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
11554:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
11555:     $thisfn=~s/^\///;
11556:     $thisfn=~s|^adm/wrapper/||;
11557:     $thisfn=~s|^adm/coursedocs/showdoc/||;
11558:     $thisfn=~s/^res\///;
11559:     $thisfn=~s/^priv\///;
11560:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
11561:         $thisfn=~s/\?.+$//;
11562:     }
11563:     return $thisfn;
11564: }
11565: 
11566: # ------------------------------------------------------------- Clutter up URLs
11567: 
11568: sub clutter {
11569:     my $thisfn='/'.&declutter(shift);
11570:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
11571: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
11572:        $thisfn='/res'.$thisfn; 
11573:     }
11574:     if ($thisfn !~m|^/adm|) {
11575: 	if ($thisfn =~ m|^/ext/|) {
11576: 	    $thisfn='/adm/wrapper'.$thisfn;
11577: 	} else {
11578: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
11579: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
11580: 	    if ($embstyle eq 'ssi'
11581: 		|| ($embstyle eq 'hdn')
11582: 		|| ($embstyle eq 'rat')
11583: 		|| ($embstyle eq 'prv')
11584: 		|| ($embstyle eq 'ign')) {
11585: 		#do nothing with these
11586: 	    } elsif (($embstyle eq 'img') 
11587: 		|| ($embstyle eq 'emb')
11588: 		|| ($embstyle eq 'wrp')) {
11589: 		$thisfn='/adm/wrapper'.$thisfn;
11590: 	    } elsif ($embstyle eq 'unk'
11591: 		     && $thisfn!~/\.(sequence|page)$/) {
11592: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
11593: 	    } else {
11594: #		&logthis("Got a blank emb style");
11595: 	    }
11596: 	}
11597:     }
11598:     return $thisfn;
11599: }
11600: 
11601: sub clutter_with_no_wrapper {
11602:     my $uri = &clutter(shift);
11603:     if ($uri =~ m-^/adm/-) {
11604: 	$uri =~ s-^/adm/wrapper/-/-;
11605: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
11606:     }
11607:     return $uri;
11608: }
11609: 
11610: sub freeze_escape {
11611:     my ($value)=@_;
11612:     if (ref($value)) {
11613: 	$value=&nfreeze($value);
11614: 	return '__FROZEN__'.&escape($value);
11615:     }
11616:     return &escape($value);
11617: }
11618: 
11619: 
11620: sub thaw_unescape {
11621:     my ($value)=@_;
11622:     if ($value =~ /^__FROZEN__/) {
11623: 	substr($value,0,10,undef);
11624: 	$value=&unescape($value);
11625: 	return &thaw($value);
11626:     }
11627:     return &unescape($value);
11628: }
11629: 
11630: sub correct_line_ends {
11631:     my ($result)=@_;
11632:     $$result =~s/\r\n/\n/mg;
11633:     $$result =~s/\r/\n/mg;
11634: }
11635: # ================================================================ Main Program
11636: 
11637: sub goodbye {
11638:    &logthis("Starting Shut down");
11639: #not converted to using infrastruture and probably shouldn't be
11640:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
11641: #converted
11642: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
11643:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
11644: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
11645: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
11646: #1.1 only
11647: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
11648: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
11649: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
11650: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
11651:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
11652:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
11653:    &logthis(sprintf("%-20s is %s",'hits',$hits));
11654:    &flushcourselogs();
11655:    &logthis("Shutting down");
11656: }
11657: 
11658: sub get_dns {
11659:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
11660:     if (!$ignore_cache) {
11661: 	my ($content,$cached)=
11662: 	    &Apache::lonnet::is_cached_new('dns',$url);
11663: 	if ($cached) {
11664: 	    &$func($content,$hashref);
11665: 	    return;
11666: 	}
11667:     }
11668: 
11669:     my %alldns;
11670:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11671:     foreach my $dns (<$config>) {
11672: 	next if ($dns !~ /^\^(\S*)/x);
11673:         my $line = $1;
11674:         my ($host,$protocol) = split(/:/,$line);
11675:         if ($protocol ne 'https') {
11676:             $protocol = 'http';
11677:         }
11678: 	$alldns{$host} = $protocol;
11679:     }
11680:     while (%alldns) {
11681: 	my ($dns) = keys(%alldns);
11682: 	my $ua=new LWP::UserAgent;
11683:         $ua->timeout(30);
11684: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
11685: 	my $response=$ua->request($request);
11686:         delete($alldns{$dns});
11687: 	next if ($response->is_error());
11688: 	my @content = split("\n",$response->content);
11689: 	unless ($nocache) {
11690: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
11691: 	}
11692: 	&$func(\@content,$hashref);
11693: 	return;
11694:     }
11695:     close($config);
11696:     my $which = (split('/',$url))[3];
11697:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
11698:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
11699:     my @content = <$config>;
11700:     &$func(\@content,$hashref);
11701:     return;
11702: }
11703: 
11704: # ------------------------------------------------------Get DNS checksums file
11705: sub parse_dns_checksums_tab {
11706:     my ($lines,$hashref) = @_;
11707:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
11708:     my $loncaparev = &get_server_loncaparev($machine_dom);
11709:     my ($release,$timestamp) = split(/\-/,$loncaparev);
11710:     my (%chksum,%revnum);
11711:     if (ref($lines) eq 'ARRAY') {
11712:         chomp(@{$lines});
11713:         my $version = shift(@{$lines});
11714:         if ($version eq $release) {  
11715:             foreach my $line (@{$lines}) {
11716:                 my ($file,$version,$shasum) = split(/,/,$line);
11717:                 $chksum{$file} = $shasum;
11718:                 $revnum{$file} = $version;
11719:             }
11720:             if (ref($hashref) eq 'HASH') {
11721:                 %{$hashref} = (
11722:                                 sums     => \%chksum,
11723:                                 versions => \%revnum,
11724:                               );
11725:             }
11726:         }
11727:     }
11728:     return;
11729: }
11730: 
11731: sub fetch_dns_checksums {
11732:     my %checksums;
11733:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
11734:     my $loncaparev = &get_server_loncaparev($machine_dom);
11735:     my ($release,$timestamp) = split(/\-/,$loncaparev);
11736:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
11737:              \%checksums);
11738:     return \%checksums;
11739: }
11740: 
11741: # ------------------------------------------------------------ Read domain file
11742: {
11743:     my $loaded;
11744:     my %domain;
11745: 
11746:     sub parse_domain_tab {
11747: 	my ($lines) = @_;
11748: 	foreach my $line (@$lines) {
11749: 	    next if ($line =~ /^(\#|\s*$ )/x);
11750: 
11751: 	    chomp($line);
11752: 	    my ($name,@elements) = split(/:/,$line,9);
11753: 	    my %this_domain;
11754: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
11755: 			       'lang_def', 'city', 'longi', 'lati',
11756: 			       'primary') {
11757: 		$this_domain{$field} = shift(@elements);
11758: 	    }
11759: 	    $domain{$name} = \%this_domain;
11760: 	}
11761:     }
11762: 
11763:     sub reset_domain_info {
11764: 	undef($loaded);
11765: 	undef(%domain);
11766:     }
11767: 
11768:     sub load_domain_tab {
11769: 	my ($ignore_cache) = @_;
11770: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
11771: 	my $fh;
11772: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
11773: 	    my @lines = <$fh>;
11774: 	    &parse_domain_tab(\@lines);
11775: 	}
11776: 	close($fh);
11777: 	$loaded = 1;
11778:     }
11779: 
11780:     sub domain {
11781: 	&load_domain_tab() if (!$loaded);
11782: 
11783: 	my ($name,$what) = @_;
11784: 	return if ( !exists($domain{$name}) );
11785: 
11786: 	if (!$what) {
11787: 	    return $domain{$name}{'description'};
11788: 	}
11789: 	return $domain{$name}{$what};
11790:     }
11791: 
11792:     sub domain_info {
11793:         &load_domain_tab() if (!$loaded);
11794:         return %domain;
11795:     }
11796: 
11797: }
11798: 
11799: 
11800: # ------------------------------------------------------------- Read hosts file
11801: {
11802:     my %hostname;
11803:     my %hostdom;
11804:     my %libserv;
11805:     my $loaded;
11806:     my %name_to_host;
11807:     my %internetdom;
11808:     my %LC_dns_serv;
11809: 
11810:     sub parse_hosts_tab {
11811: 	my ($file) = @_;
11812: 	foreach my $configline (@$file) {
11813: 	    next if ($configline =~ /^(\#|\s*$ )/x);
11814:             chomp($configline);
11815: 	    if ($configline =~ /^\^/) {
11816:                 if ($configline =~ /^\^([\w.\-]+)/) {
11817:                     $LC_dns_serv{$1} = 1;
11818:                 }
11819:                 next;
11820:             }
11821: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
11822: 	    $name=~s/\s//g;
11823: 	    if ($id && $domain && $role && $name) {
11824: 		$hostname{$id}=$name;
11825: 		push(@{$name_to_host{$name}}, $id);
11826: 		$hostdom{$id}=$domain;
11827: 		if ($role eq 'library') { $libserv{$id}=$name; }
11828:                 if (defined($protocol)) {
11829:                     if ($protocol eq 'https') {
11830:                         $protocol{$id} = $protocol;
11831:                     } else {
11832:                         $protocol{$id} = 'http'; 
11833:                     }
11834:                 } else {
11835:                     $protocol{$id} = 'http';
11836:                 }
11837:                 if (defined($intdom)) {
11838:                     $internetdom{$id} = $intdom;
11839:                 }
11840: 	    }
11841: 	}
11842:     }
11843:     
11844:     sub reset_hosts_info {
11845: 	&purge_remembered();
11846: 	&reset_domain_info();
11847: 	&reset_hosts_ip_info();
11848: 	undef(%name_to_host);
11849: 	undef(%hostname);
11850: 	undef(%hostdom);
11851: 	undef(%libserv);
11852: 	undef($loaded);
11853:     }
11854: 
11855:     sub load_hosts_tab {
11856: 	my ($ignore_cache) = @_;
11857: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
11858: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11859: 	my @config = <$config>;
11860: 	&parse_hosts_tab(\@config);
11861: 	close($config);
11862: 	$loaded=1;
11863:     }
11864: 
11865:     sub hostname {
11866: 	&load_hosts_tab() if (!$loaded);
11867: 
11868: 	my ($lonid) = @_;
11869: 	return $hostname{$lonid};
11870:     }
11871: 
11872:     sub all_hostnames {
11873: 	&load_hosts_tab() if (!$loaded);
11874: 
11875: 	return %hostname;
11876:     }
11877: 
11878:     sub all_names {
11879: 	&load_hosts_tab() if (!$loaded);
11880: 
11881: 	return %name_to_host;
11882:     }
11883: 
11884:     sub all_host_domain {
11885:         &load_hosts_tab() if (!$loaded);
11886:         return %hostdom;
11887:     }
11888: 
11889:     sub is_library {
11890: 	&load_hosts_tab() if (!$loaded);
11891: 
11892: 	return exists($libserv{$_[0]});
11893:     }
11894: 
11895:     sub all_library {
11896: 	&load_hosts_tab() if (!$loaded);
11897: 
11898: 	return %libserv;
11899:     }
11900: 
11901:     sub unique_library {
11902: 	#2x reverse removes all hostnames that appear more than once
11903:         my %unique = reverse &all_library();
11904:         return reverse %unique;
11905:     }
11906: 
11907:     sub get_servers {
11908: 	&load_hosts_tab() if (!$loaded);
11909: 
11910: 	my ($domain,$type) = @_;
11911: 	my %possible_hosts = ($type eq 'library') ? %libserv
11912: 	                                          : %hostname;
11913: 	my %result;
11914: 	if (ref($domain) eq 'ARRAY') {
11915: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
11916: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
11917: 		    $result{$host} = $hostname;
11918: 		}
11919: 	    }
11920: 	} else {
11921: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
11922: 		if ($hostdom{$host} eq $domain) {
11923: 		    $result{$host} = $hostname;
11924: 		}
11925: 	    }
11926: 	}
11927: 	return %result;
11928:     }
11929: 
11930:     sub get_unique_servers {
11931:         my %unique = reverse &get_servers(@_);
11932: 	return reverse %unique;
11933:     }
11934: 
11935:     sub host_domain {
11936: 	&load_hosts_tab() if (!$loaded);
11937: 
11938: 	my ($lonid) = @_;
11939: 	return $hostdom{$lonid};
11940:     }
11941: 
11942:     sub all_domains {
11943: 	&load_hosts_tab() if (!$loaded);
11944: 
11945: 	my %seen;
11946: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
11947: 	return @uniq;
11948:     }
11949: 
11950:     sub internet_dom {
11951:         &load_hosts_tab() if (!$loaded);
11952: 
11953:         my ($lonid) = @_;
11954:         return $internetdom{$lonid};
11955:     }
11956: 
11957:     sub is_LC_dns {
11958:         &load_hosts_tab() if (!$loaded);
11959: 
11960:         my ($hostname) = @_;
11961:         return exists($LC_dns_serv{$hostname});
11962:     }
11963: 
11964: }
11965: 
11966: { 
11967:     my %iphost;
11968:     my %name_to_ip;
11969:     my %lonid_to_ip;
11970: 
11971:     sub get_hosts_from_ip {
11972: 	my ($ip) = @_;
11973: 	my %iphosts = &get_iphost();
11974: 	if (ref($iphosts{$ip})) {
11975: 	    return @{$iphosts{$ip}};
11976: 	}
11977: 	return;
11978:     }
11979:     
11980:     sub reset_hosts_ip_info {
11981: 	undef(%iphost);
11982: 	undef(%name_to_ip);
11983: 	undef(%lonid_to_ip);
11984:     }
11985: 
11986:     sub get_host_ip {
11987: 	my ($lonid) = @_;
11988: 	if (exists($lonid_to_ip{$lonid})) {
11989: 	    return $lonid_to_ip{$lonid};
11990: 	}
11991: 	my $name=&hostname($lonid);
11992:    	my $ip = gethostbyname($name);
11993: 	return if (!$ip || length($ip) ne 4);
11994: 	$ip=inet_ntoa($ip);
11995: 	$name_to_ip{$name}   = $ip;
11996: 	$lonid_to_ip{$lonid} = $ip;
11997: 	return $ip;
11998:     }
11999:     
12000:     sub get_iphost {
12001: 	my ($ignore_cache) = @_;
12002: 
12003: 	if (!$ignore_cache) {
12004: 	    if (%iphost) {
12005: 		return %iphost;
12006: 	    }
12007: 	    my ($ip_info,$cached)=
12008: 		&Apache::lonnet::is_cached_new('iphost','iphost');
12009: 	    if ($cached) {
12010: 		%iphost      = %{$ip_info->[0]};
12011: 		%name_to_ip  = %{$ip_info->[1]};
12012: 		%lonid_to_ip = %{$ip_info->[2]};
12013: 		return %iphost;
12014: 	    }
12015: 	}
12016: 
12017: 	# get yesterday's info for fallback
12018: 	my %old_name_to_ip;
12019: 	my ($ip_info,$cached)=
12020: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
12021: 	if ($cached) {
12022: 	    %old_name_to_ip = %{$ip_info->[1]};
12023: 	}
12024: 
12025: 	my %name_to_host = &all_names();
12026: 	foreach my $name (keys(%name_to_host)) {
12027: 	    my $ip;
12028: 	    if (!exists($name_to_ip{$name})) {
12029: 		$ip = gethostbyname($name);
12030: 		if (!$ip || length($ip) ne 4) {
12031: 		    if (defined($old_name_to_ip{$name})) {
12032: 			$ip = $old_name_to_ip{$name};
12033: 			&logthis("Can't find $name defaulting to old $ip");
12034: 		    } else {
12035: 			&logthis("Name $name no IP found");
12036: 			next;
12037: 		    }
12038: 		} else {
12039: 		    $ip=inet_ntoa($ip);
12040: 		}
12041: 		$name_to_ip{$name} = $ip;
12042: 	    } else {
12043: 		$ip = $name_to_ip{$name};
12044: 	    }
12045: 	    foreach my $id (@{ $name_to_host{$name} }) {
12046: 		$lonid_to_ip{$id} = $ip;
12047: 	    }
12048: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
12049: 	}
12050: 	&do_cache_new('iphost','iphost',
12051: 		      [\%iphost,\%name_to_ip,\%lonid_to_ip],
12052: 		      48*60*60);
12053: 
12054: 	return %iphost;
12055:     }
12056: 
12057:     #
12058:     #  Given a DNS returns the loncapa host name for that DNS 
12059:     # 
12060:     sub host_from_dns {
12061:         my ($dns) = @_;
12062:         my @hosts;
12063:         my $ip;
12064: 
12065:         if (exists($name_to_ip{$dns})) {
12066:             $ip = $name_to_ip{$dns};
12067:         }
12068:         if (!$ip) {
12069:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
12070:             if (length($ip) == 4) { 
12071: 	        $ip   = &IO::Socket::inet_ntoa($ip);
12072:             }
12073:         }
12074:         if ($ip) {
12075: 	    @hosts = get_hosts_from_ip($ip);
12076: 	    return $hosts[0];
12077:         }
12078:         return undef;
12079:     }
12080: 
12081:     sub get_internet_names {
12082:         my ($lonid) = @_;
12083:         return if ($lonid eq '');
12084:         my ($idnref,$cached)=
12085:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
12086:         if ($cached) {
12087:             return $idnref;
12088:         }
12089:         my $ip = &get_host_ip($lonid);
12090:         my @hosts = &get_hosts_from_ip($ip);
12091:         my %iphost = &get_iphost();
12092:         my (@idns,%seen);
12093:         foreach my $id (@hosts) {
12094:             my $dom = &host_domain($id);
12095:             my $prim_id = &domain($dom,'primary');
12096:             my $prim_ip = &get_host_ip($prim_id);
12097:             next if ($seen{$prim_ip});
12098:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
12099:                 foreach my $id (@{$iphost{$prim_ip}}) {
12100:                     my $intdom = &internet_dom($id);
12101:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
12102:                         push(@idns,$intdom);
12103:                     }
12104:                 }
12105:             }
12106:             $seen{$prim_ip} = 1;
12107:         }
12108:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
12109:     }
12110: 
12111: }
12112: 
12113: sub all_loncaparevs {
12114:     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);
12115: }
12116: 
12117: # ---------------------------------------------------------- Read loncaparev table
12118: {
12119:     sub load_loncaparevs { 
12120:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
12121:             if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
12122:                 while (my $configline=<$config>) {
12123:                     chomp($configline);
12124:                     my ($hostid,$loncaparev)=split(/:/,$configline);
12125:                     $loncaparevs{$hostid}=$loncaparev;
12126:                 }
12127:                 close($config);
12128:             }
12129:         }
12130:     }
12131: }
12132: 
12133: # ---------------------------------------------------------- Read serverhostID table
12134: {
12135:     sub load_serverhomeIDs {
12136:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
12137:             if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
12138:                 while (my $configline=<$config>) {
12139:                     chomp($configline);
12140:                     my ($name,$id)=split(/:/,$configline);
12141:                     $serverhomeIDs{$name}=$id;
12142:                 }
12143:                 close($config);
12144:             }
12145:         }
12146:     }
12147: }
12148: 
12149: 
12150: BEGIN {
12151: 
12152: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
12153:     unless ($readit) {
12154: {
12155:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
12156:     %perlvar = (%perlvar,%{$configvars});
12157: }
12158: 
12159: 
12160: # ------------------------------------------------------ Read spare server file
12161: {
12162:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
12163: 
12164:     while (my $configline=<$config>) {
12165:        chomp($configline);
12166:        if ($configline) {
12167: 	   my ($host,$type) = split(':',$configline,2);
12168: 	   if (!defined($type) || $type eq '') { $type = 'default' };
12169: 	   push(@{ $spareid{$type} }, $host);
12170:        }
12171:     }
12172:     close($config);
12173: }
12174: # ------------------------------------------------------------ Read permissions
12175: {
12176:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
12177: 
12178:     while (my $configline=<$config>) {
12179: 	chomp($configline);
12180: 	if ($configline) {
12181: 	    my ($role,$perm)=split(/ /,$configline);
12182: 	    if ($perm ne '') { $pr{$role}=$perm; }
12183: 	}
12184:     }
12185:     close($config);
12186: }
12187: 
12188: # -------------------------------------------- Read plain texts for permissions
12189: {
12190:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
12191: 
12192:     while (my $configline=<$config>) {
12193: 	chomp($configline);
12194: 	if ($configline) {
12195: 	    my ($short,@plain)=split(/:/,$configline);
12196:             %{$prp{$short}} = ();
12197: 	    if (@plain > 0) {
12198:                 $prp{$short}{'std'} = $plain[0];
12199:                 for (my $i=1; $i<@plain; $i++) {
12200:                     $prp{$short}{'alt'.$i} = $plain[$i];  
12201:                 }
12202:             }
12203: 	}
12204:     }
12205:     close($config);
12206: }
12207: 
12208: # ---------------------------------------------------------- Read package table
12209: {
12210:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
12211: 
12212:     while (my $configline=<$config>) {
12213: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
12214: 	chomp($configline);
12215: 	my ($short,$plain)=split(/:/,$configline);
12216: 	my ($pack,$name)=split(/\&/,$short);
12217: 	if ($plain ne '') {
12218: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
12219: 	    $packagetab{$short}=$plain; 
12220: 	}
12221:     }
12222:     close($config);
12223: }
12224: 
12225: # ---------------------------------------------------------- Read loncaparev table
12226: 
12227: &load_loncaparevs();
12228: 
12229: # ---------------------------------------------------------- Read serverhostID table
12230: 
12231: &load_serverhomeIDs();
12232: 
12233: # ---------------------------------------------------------- Read releaseslist XML
12234: {
12235:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
12236:     if (-e $file) {
12237:         my $parser = HTML::LCParser->new($file);
12238:         while (my $token = $parser->get_token()) {
12239:             if ($token->[0] eq 'S') {
12240:                 my $item = $token->[1];
12241:                 my $name = $token->[2]{'name'};
12242:                 my $value = $token->[2]{'value'};
12243:                 if ($item ne '' && $name ne '' && $value ne '') {
12244:                     my $release = $parser->get_text();
12245:                     $release =~ s/(^\s*|\s*$ )//gx;
12246:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
12247:                 }
12248:             }
12249:         }
12250:     }
12251: }
12252: 
12253: # ---------------------------------------------------------- Read managers table
12254: {
12255:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
12256:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
12257:             while (my $configline=<$config>) {
12258:                 chomp($configline);
12259:                 next if ($configline =~ /^\#/);
12260:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
12261:                     $managerstab{$configline} = 1;
12262:                 }
12263:             }
12264:             close($config);
12265:         }
12266:     }
12267: }
12268: 
12269: # ------------- set up temporary directory
12270: {
12271:     $tmpdir = LONCAPA::tempdir();
12272: 
12273: }
12274: 
12275: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
12276: 				'compress_threshold'=> 20_000,
12277:  			        });
12278: 
12279: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
12280: $dumpcount=0;
12281: $locknum=0;
12282: 
12283: &logtouch();
12284: &logthis('<font color="yellow">INFO: Read configuration</font>');
12285: $readit=1;
12286:     {
12287: 	use integer;
12288: 	my $test=(2**32)+1;
12289: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
12290: 	&logthis(" Detected 64bit platform ($_64bit)");
12291:     }
12292: 
12293:     {
12294:         eval {
12295:             ($apache) =
12296:                 (Apache2::ServerUtil::get_server_version() =~ m{Apache/(\d+\.\d+)});
12297:         };
12298:         if ($@) {
12299:            $apache = 1.3;
12300:         }
12301:     }
12302: 
12303: }
12304: }
12305: 
12306: 1;
12307: __END__
12308: 
12309: =pod
12310: 
12311: =head1 NAME
12312: 
12313: Apache::lonnet - Subroutines to ask questions about things in the network.
12314: 
12315: =head1 SYNOPSIS
12316: 
12317: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
12318: 
12319:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
12320: 
12321: Common parameters:
12322: 
12323: =over 4
12324: 
12325: =item *
12326: 
12327: $uname : an internal username (if $cname expecting a course Id specifically)
12328: 
12329: =item *
12330: 
12331: $udom : a domain (if $cdom expecting a course's domain specifically)
12332: 
12333: =item *
12334: 
12335: $symb : a resource instance identifier
12336: 
12337: =item *
12338: 
12339: $namespace : the name of a .db file that contains the data needed or
12340: being set.
12341: 
12342: =back
12343: 
12344: =head1 OVERVIEW
12345: 
12346: lonnet provides subroutines which interact with the
12347: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
12348: about classes, users, and resources.
12349: 
12350: For many of these objects you can also use this to store data about
12351: them or modify them in various ways.
12352: 
12353: =head2 Symbs
12354: 
12355: To identify a specific instance of a resource, LON-CAPA uses symbols
12356: or "symbs"X<symb>. These identifiers are built from the URL of the
12357: map, the resource number of the resource in the map, and the URL of
12358: the resource itself. The latter is somewhat redundant, but might help
12359: if maps change.
12360: 
12361: An example is
12362: 
12363:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
12364: 
12365: The respective map entry is
12366: 
12367:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
12368:   title="Problem 2">
12369:  </resource>
12370: 
12371: Symbs are used by the random number generator, as well as to store and
12372: restore data specific to a certain instance of for example a problem.
12373: 
12374: =head2 Storing And Retrieving Data
12375: 
12376: X<store()>X<cstore()>X<restore()>Three of the most important functions
12377: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
12378: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
12379: is is the non-critical message twin of cstore. These functions are for
12380: handlers to store a perl hash to a user's permanent data space in an
12381: easy manner, and to retrieve it again on another call. It is expected
12382: that a handler would use this once at the beginning to retrieve data,
12383: and then again once at the end to send only the new data back.
12384: 
12385: The data is stored in the user's data directory on the user's
12386: homeserver under the ID of the course.
12387: 
12388: The hash that is returned by restore will have all of the previous
12389: value for all of the elements of the hash.
12390: 
12391: Example:
12392: 
12393:  #creating a hash
12394:  my %hash;
12395:  $hash{'foo'}='bar';
12396: 
12397:  #storing it
12398:  &Apache::lonnet::cstore(\%hash);
12399: 
12400:  #changing a value
12401:  $hash{'foo'}='notbar';
12402: 
12403:  #adding a new value
12404:  $hash{'bar'}='foo';
12405:  &Apache::lonnet::cstore(\%hash);
12406: 
12407:  #retrieving the hash
12408:  my %history=&Apache::lonnet::restore();
12409: 
12410:  #print the hash
12411:  foreach my $key (sort(keys(%history))) {
12412:    print("\%history{$key} = $history{$key}");
12413:  }
12414: 
12415: Will print out:
12416: 
12417:  %history{1:foo} = bar
12418:  %history{1:keys} = foo:timestamp
12419:  %history{1:timestamp} = 990455579
12420:  %history{2:bar} = foo
12421:  %history{2:foo} = notbar
12422:  %history{2:keys} = foo:bar:timestamp
12423:  %history{2:timestamp} = 990455580
12424:  %history{bar} = foo
12425:  %history{foo} = notbar
12426:  %history{timestamp} = 990455580
12427:  %history{version} = 2
12428: 
12429: Note that the special hash entries C<keys>, C<version> and
12430: C<timestamp> were added to the hash. C<version> will be equal to the
12431: total number of versions of the data that have been stored. The
12432: C<timestamp> attribute will be the UNIX time the hash was
12433: stored. C<keys> is available in every historical section to list which
12434: keys were added or changed at a specific historical revision of a
12435: hash.
12436: 
12437: B<Warning>: do not store the hash that restore returns directly. This
12438: will cause a mess since it will restore the historical keys as if the
12439: were new keys. I.E. 1:foo will become 1:1:foo etc.
12440: 
12441: Calling convention:
12442: 
12443:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
12444:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname);
12445: 
12446: For more detailed information, see lonnet specific documentation.
12447: 
12448: =head1 RETURN MESSAGES
12449: 
12450: =over 4
12451: 
12452: =item * B<con_lost>: unable to contact remote host
12453: 
12454: =item * B<con_delayed>: unable to contact remote host, message will be delivered
12455: when the connection is brought back up
12456: 
12457: =item * B<con_failed>: unable to contact remote host and unable to save message
12458: for later delivery
12459: 
12460: =item * B<error:>: an error a occurred, a description of the error follows the :
12461: 
12462: =item * B<no_such_host>: unable to fund a host associated with the user/domain
12463: that was requested
12464: 
12465: =back
12466: 
12467: =head1 PUBLIC SUBROUTINES
12468: 
12469: =head2 Session Environment Functions
12470: 
12471: =over 4
12472: 
12473: =item * 
12474: X<appenv()>
12475: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
12476: the user envirnoment file, and will be restored for each access this
12477: user makes during this session, also modifies the %env for the current
12478: process. Optional rolesarrayref - if defined contains a reference to an array
12479: of roles which are exempt from the restriction on modifying user.role entries 
12480: in the user's environment.db and in %env.    
12481: 
12482: =item *
12483: X<delenv()>
12484: B<delenv($delthis,$regexp)>: removes all items from the session
12485: environment file that begin with $delthis. If the 
12486: optional second arg - $regexp - is true, $delthis is treated as a 
12487: regular expression, otherwise \Q$delthis\E is used. 
12488: The values are also deleted from the current processes %env.
12489: 
12490: =item * get_env_multiple($name) 
12491: 
12492: gets $name from the %env hash, it seemlessly handles the cases where multiple
12493: values may be defined and end up as an array ref.
12494: 
12495: returns an array of values
12496: 
12497: =back
12498: 
12499: =head2 User Information
12500: 
12501: =over 4
12502: 
12503: =item *
12504: X<queryauthenticate()>
12505: B<queryauthenticate($uname,$udom)>: try to determine user's current 
12506: authentication scheme
12507: 
12508: =item *
12509: X<authenticate()>
12510: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
12511: authenticate user from domain's lib servers (first use the current
12512: one). C<$upass> should be the users password.
12513: $checkdefauth is optional (value is 1 if a check should be made to
12514:    authenticate user using default authentication method, and allow
12515:    account creation if username does not have account in the domain).
12516: $clientcancheckhost is optional (value is 1 if checking whether the
12517:    server can host will occur on the client side in lonauth.pm).   
12518: 
12519: =item *
12520: X<homeserver()>
12521: B<homeserver($uname,$udom)>: find the server which has
12522: the user's directory and files (there must be only one), this caches
12523: the answer, and also caches if there is a borken connection.
12524: 
12525: =item *
12526: X<idget()>
12527: B<idget($udom,@ids)>: find the usernames behind a list of IDs
12528: (IDs are a unique resource in a domain, there must be only 1 ID per
12529: username, and only 1 username per ID in a specific domain) (returns
12530: hash: id=>name,id=>name)
12531: 
12532: =item *
12533: X<idrget()>
12534: B<idrget($udom,@unames)>: find the IDs behind a list of
12535: usernames (returns hash: name=>id,name=>id)
12536: 
12537: =item *
12538: X<idput()>
12539: B<idput($udom,%ids)>: store away a list of names and associated IDs
12540: 
12541: =item *
12542: X<rolesinit()>
12543: B<rolesinit($udom,$username)>: get user privileges.
12544: returns user role, first access and timer interval hashes
12545: 
12546: =item *
12547: X<privileged()>
12548: B<privileged($username,$domain)>: returns a true if user has a
12549: privileged and active role (i.e. su or dc), false otherwise.
12550: 
12551: =item *
12552: X<getsection()>
12553: B<getsection($udom,$uname,$cname)>: finds the section of student in the
12554: course $cname, return section name/number or '' for "not in course"
12555: and '-1' for "no section"
12556: 
12557: =item *
12558: X<userenvironment()>
12559: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
12560: passed in @what from the requested user's environment, returns a hash
12561: 
12562: =item * 
12563: X<userlog_query()>
12564: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
12565: activity.log file. %filters defines filters applied when parsing the
12566: log file. These can be start or end timestamps, or the type of action
12567: - log to look for Login or Logout events, check for Checkin or
12568: Checkout, role for role selection. The response is in the form
12569: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
12570: escaped strings of the action recorded in the activity.log file.
12571: 
12572: =back
12573: 
12574: =head2 User Roles
12575: 
12576: =over 4
12577: 
12578: =item *
12579: 
12580: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
12581:  F: full access
12582:  U,I,K: authentication modes (cxx only)
12583:  '': forbidden
12584:  1: user needs to choose course
12585:  2: browse allowed
12586:  A: passphrase authentication needed
12587: 
12588: =item *
12589: 
12590: constructaccess($url,$setpriv) : check for access to construction space URL
12591: 
12592: See if the owner domain and name in the URL match those in the
12593: expected environment.  If so, return three element list
12594: ($ownername,$ownerdomain,$ownerhome).
12595: 
12596: Otherwise return the null string.
12597: 
12598: If second argument 'setpriv' is true, it assigns the privileges,
12599: and returns the same three element list, unless the owner has
12600: blocked "ad hoc" Domain Coordinator access to the Author Space,
12601: in which case the null string is returned.
12602: 
12603: =item *
12604: 
12605: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
12606: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
12607: and course level
12608: 
12609: =item *
12610: 
12611: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
12612: (rolesplain.tab); plain text explanation of a user role term.
12613: $type is Course (default) or Community.
12614: If $forcedefault evaluates to true, text returned will be default 
12615: text for $type. Otherwise, if this is a course, the text returned 
12616: will be a custom name for the role (if defined in the course's 
12617: environment).  If no custom name is defined the default is returned.
12618:    
12619: =item *
12620: 
12621: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
12622: All arguments are optional. Returns a hash of a roles, either for
12623: co-author/assistant author roles for a user's Construction Space
12624: (default), or if $context is 'userroles', roles for the user himself,
12625: In the hash, keys are set to colon-separated $uname,$udom,$role, and
12626: (optionally) if $withsec is true, a fourth colon-separated item - $section.
12627: For each key, value is set to colon-separated start and end times for
12628: the role.  If no username and domain are specified, will default to
12629: current user/domain. Types, roles, and roledoms are references to arrays
12630: of role statuses (active, future or previous), roles 
12631: (e.g., cc,in, st etc.) and domains of the roles which can be used
12632: to restrict the list of roles reported. If no array ref is 
12633: provided for types, will default to return only active roles.
12634: 
12635: =item *
12636: 
12637: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
12638: user: $uname:$udom has a role in the course: $cdom_$cnum. 
12639: 
12640: Additional optional arguments are: $type (if role checking is to be restricted 
12641: to certain user status types -- previous (expired roles), active (currently
12642: available roles) or future (roles available in the future), and
12643: $hideprivileged -- if true will not report course roles for users who
12644: have active Domain Coordinator role in course's domain or in additional
12645: domains (specified in 'Domains to check for privileged users' in course
12646: environment -- set via:  Course Settings -> Classlists and staff listing).
12647: 
12648: =item *
12649: 
12650: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
12651: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
12652: $possdomains and $possroles are optional array refs -- to domains to check and
12653: roles to check.  If $possdomains is not specified, a dump will be done of the
12654: users' roles.db to check for a dc or su role in any domain. This can be
12655: time consuming if &privileged is called repeatedly (e.g., when displaying a
12656: classlist), so in such cases, supplying a $possdomains array is preferred, as
12657: this then allows &privileged_by_domain() to be used, which caches the identity
12658: of privileged users, eliminating the need for repeated calls to &dump().
12659: 
12660: =item *
12661: 
12662: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
12663: where the outer hash keys are domains specified in the $possdomains array ref,
12664: next inner hash keys are privileged roles specified in the $roles array ref,
12665: and the innermost hash contains key = value pairs for username:domain = end:start
12666: for active or future "privileged" users with that role in that domain. To avoid
12667: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
12668: innerhash are cached using priv_$role and $dom as the identifiers.
12669: 
12670: =back
12671: 
12672: =head2 User Modification
12673: 
12674: =over 4
12675: 
12676: =item *
12677: 
12678: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
12679: user for the level given by URL.  Optional start and end dates (leave empty
12680: string or zero for "no date")
12681: 
12682: =item *
12683: 
12684: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
12685: change a users, password, possible return values are: ok,
12686: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
12687: refused
12688: 
12689: =item *
12690: 
12691: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
12692: 
12693: =item *
12694: 
12695: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
12696:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
12697: 
12698: will update user information (firstname,middlename,lastname,generation,
12699: permanentemail), and if forceid is true, student/employee ID also.
12700: A user's institutional affiliation(s) can also be updated.
12701: User information fields will not be overwritten with empty entries 
12702: unless the field is included in the $candelete array reference.
12703: This array is included when a single user is modified via "Manage Users",
12704: or when Autoupdate.pl is run by cron in a domain.
12705: 
12706: =item *
12707: 
12708: modifystudent
12709: 
12710: modify a student's enrollment and identification information.
12711: The course id is resolved based on the current user's environment.  
12712: This means the invoking user must be a course coordinator or otherwise
12713: associated with a course.
12714: 
12715: This call is essentially a wrapper for lonnet::modifyuser and
12716: lonnet::modify_student_enrollment
12717: 
12718: Inputs: 
12719: 
12720: =over 4
12721: 
12722: =item B<$udom> Student's loncapa domain
12723: 
12724: =item B<$uname> Student's loncapa login name
12725: 
12726: =item B<$uid> Student/Employee ID
12727: 
12728: =item B<$umode> Student's authentication mode
12729: 
12730: =item B<$upass> Student's password
12731: 
12732: =item B<$first> Student's first name
12733: 
12734: =item B<$middle> Student's middle name
12735: 
12736: =item B<$last> Student's last name
12737: 
12738: =item B<$gene> Student's generation
12739: 
12740: =item B<$usec> Student's section in course
12741: 
12742: =item B<$end> Unix time of the roles expiration
12743: 
12744: =item B<$start> Unix time of the roles start date
12745: 
12746: =item B<$forceid> If defined, allow $uid to be changed
12747: 
12748: =item B<$desiredhome> server to use as home server for student
12749: 
12750: =item B<$email> Student's permanent e-mail address
12751: 
12752: =item B<$type> Type of enrollment (auto or manual)
12753: 
12754: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
12755: 
12756: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
12757: 
12758: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
12759: 
12760: =item B<$context> role change context (shown in User Management Logs display in a course)
12761: 
12762: =item B<$inststatus> institutional status of user - : separated string of escaped status types
12763: 
12764: =item B<$credits> Number of credits student will earn from this class - only needs to be supplied if value needs to be different from default credits for class.
12765: 
12766: =back
12767: 
12768: =item *
12769: 
12770: modify_student_enrollment
12771: 
12772: Change a student's enrollment status in a class.  The environment variable
12773: 'role.request.course' must be defined for this function to proceed.
12774: 
12775: Inputs:
12776: 
12777: =over 4
12778: 
12779: =item $udom, student's domain
12780: 
12781: =item $uname, student's name
12782: 
12783: =item $uid, student's user id
12784: 
12785: =item $first, student's first name
12786: 
12787: =item $middle
12788: 
12789: =item $last
12790: 
12791: =item $gene
12792: 
12793: =item $usec
12794: 
12795: =item $end
12796: 
12797: =item $start
12798: 
12799: =item $type
12800: 
12801: =item $locktype
12802: 
12803: =item $cid
12804: 
12805: =item $selfenroll
12806: 
12807: =item $context
12808: 
12809: =item $credits, number of credits student will earn from this class
12810: 
12811: =back
12812: 
12813: 
12814: =item *
12815: 
12816: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
12817: custom role; give a custom role to a user for the level given by URL.  Specify
12818: name and domain of role author, and role name
12819: 
12820: =item *
12821: 
12822: revokerole($udom,$uname,$url,$role) : revoke a role for url
12823: 
12824: =item *
12825: 
12826: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
12827: 
12828: =back
12829: 
12830: =head2 Course Infomation
12831: 
12832: =over 4
12833: 
12834: =item *
12835: 
12836: coursedescription($courseid,$options) : returns a hash of information about the
12837: specified course id, including all environment settings for the
12838: course, the description of the course will be in the hash under the
12839: key 'description'
12840: 
12841: $options is an optional parameter that if supplied is a hash reference that controls
12842: what how this function works.  It has the following key/values:
12843: 
12844: =over 4
12845: 
12846: =item freshen_cache
12847: 
12848: If defined, and the environment cache for the course is valid, it is 
12849: returned in the returned hash.
12850: 
12851: =item one_time
12852: 
12853: If defined, the last cache time is set to _now_
12854: 
12855: =item user
12856: 
12857: If defined, the supplied username is used instead of the current user.
12858: 
12859: 
12860: =back
12861: 
12862: =item *
12863: 
12864: resdata($name,$domain,$type,@which) : request for current parameter
12865: setting for a specific $type, where $type is either 'course' or 'user',
12866: @what should be a list of parameters to ask about. This routine caches
12867: answers for 10 minutes.
12868: 
12869: =item *
12870: 
12871: get_courseresdata($courseid, $domain) : dump the entire course resource
12872: data base, returning a hash that is keyed by the resource name and has
12873: values that are the resource value.  I believe that the timestamps and
12874: versions are also returned.
12875: 
12876: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
12877: supplemental content area. This routine caches the number of files for 
12878: 10 minutes.
12879: 
12880: =back
12881: 
12882: =head2 Course Modification
12883: 
12884: =over 4
12885: 
12886: =item *
12887: 
12888: writecoursepref($courseid,%prefs) : write preferences (environment
12889: database) for a course
12890: 
12891: =item *
12892: 
12893: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
12894: 
12895: =item *
12896: 
12897: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
12898: 
12899: =item *
12900: 
12901: is_course($courseid), is_course($cdom, $cnum)
12902: 
12903: Accepts either a combined $courseid (in the form of domain_courseid) or the
12904: two component version $cdom, $cnum. It checks if the specified course exists.
12905: 
12906: Returns:
12907:     undef if the course doesn't exist, otherwise
12908:     in scalar context the combined courseid.
12909:     in list context the two components of the course identifier, domain and 
12910:     courseid.    
12911: 
12912: =back
12913: 
12914: =head2 Resource Subroutines
12915: 
12916: =over 4
12917: 
12918: =item *
12919: 
12920: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
12921: 
12922: =item *
12923: 
12924: repcopy($filename) : subscribes to the requested file, and attempts to
12925: replicate from the owning library server, Might return
12926: 'unavailable', 'not_found', 'forbidden', 'ok', or
12927: 'bad_request', also attempts to grab the metadata for the
12928: resource. Expects the local filesystem pathname
12929: (/home/httpd/html/res/....)
12930: 
12931: =back
12932: 
12933: =head2 Resource Information
12934: 
12935: =over 4
12936: 
12937: =item *
12938: 
12939: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
12940: and returns the value of a variety of different possible values,
12941: $varname should be a request string, and the other parameters can be
12942: used to specify who and what one is asking about. Ordinarily, $cid 
12943: does not need to be specified, as it is retrived from 
12944: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
12945: within lonuserstate::loadmap() when initializing a course, before
12946: $env{'request.course.id'} has been set, so it needs to be provided
12947: in that one case.
12948: 
12949: Possible values for $varname are environment.lastname (or other item
12950: from the envirnment hash), user.name (or someother aspect about the
12951: user), resource.0.maxtries (or some other part and parameter of a
12952: resource)
12953: 
12954: =item *
12955: 
12956: directcondval($number) : get current value of a condition; reads from a state
12957: string
12958: 
12959: =item *
12960: 
12961: condval($condidx) : value of condition index based on state
12962: 
12963: =item *
12964: 
12965: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
12966: resource's metadata, $what should be either a specific key, or either
12967: 'keys' (to get a list of possible keys) or 'packages' to get a list of
12968: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
12969: 
12970: this function automatically caches all requests
12971: 
12972: =item *
12973: 
12974: metadata_query($query,$custom,$customshow) : make a metadata query against the
12975: network of library servers; returns file handle of where SQL and regex results
12976: will be stored for query
12977: 
12978: =item *
12979: 
12980: symbread($filename) : return symbolic list entry (filename argument optional);
12981: returns the data handle
12982: 
12983: =item *
12984: 
12985: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
12986: and is a possible symb for the URL in $thisfn, and if is an encrypted
12987: resource that the user accessed using /enc/ returns a 1 on success, 0
12988: on failure, user must be in a course, as it assumes the existence of
12989: the course initial hash, and uses $env('request.course.id'}.  The third
12990: arg is an optional reference to a scalar.  If this arg is passed in the 
12991: call to symbverify, it will be set to 1 if the symb has been set to be 
12992: encrypted; otherwise it will be null.  
12993: 
12994: =item *
12995: 
12996: symbclean($symb) : removes versions numbers from a symb, returns the
12997: cleaned symb
12998: 
12999: =item *
13000: 
13001: is_on_map($uri) : checks if the $uri is somewhere on the current
13002: course map, user must be in a course for it to work.
13003: 
13004: =item *
13005: 
13006: numval($salt) : return random seed value (addend for rndseed)
13007: 
13008: =item *
13009: 
13010: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
13011: a random seed, all arguments are optional, if they aren't sent it uses the
13012: environment to derive them. Note: if symb isn't sent and it can't get one
13013: from &symbread it will use the current time as its return value
13014: 
13015: =item *
13016: 
13017: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
13018: unfakeable, receipt
13019: 
13020: =item *
13021: 
13022: receipt() : API to ireceipt working off of env values; given out to users
13023: 
13024: =item *
13025: 
13026: countacc($url) : count the number of accesses to a given URL
13027: 
13028: =item *
13029: 
13030: 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
13031: 
13032: =item *
13033: 
13034: 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)
13035: 
13036: =item *
13037: 
13038: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
13039: 
13040: =item *
13041: 
13042: devalidate($symb) : devalidate temporary spreadsheet calculations,
13043: forcing spreadsheet to reevaluate the resource scores next time.
13044: 
13045: =item * 
13046: 
13047: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
13048: when viewing in course context.
13049: 
13050:  input: six args -- filename (decluttered), course number, course domain,
13051:                     url, symb (if registered) and group (if this is a 
13052:                     group item -- e.g., bulletin board, group page etc.).
13053: 
13054:  output: array of five scalars --
13055:          $cfile -- url for file editing if editable on current server
13056:          $home -- homeserver of resource (i.e., for author if published,
13057:                                           or course if uploaded.).
13058:          $switchserver --  1 if server switch will be needed.
13059:          $forceedit -- 1 if icon/link should be to go to edit mode 
13060:          $forceview -- 1 if icon/link should be to go to view mode
13061: 
13062: =item *
13063: 
13064: is_course_upload($file,$cnum,$cdom)
13065: 
13066: Used in course context to determine if current file was uploaded to 
13067: the course (i.e., would be found in /userfiles/docs on the course's 
13068: homeserver.
13069: 
13070:   input: 3 args -- filename (decluttered), course number and course domain.
13071:   output: boolean -- 1 if file was uploaded.
13072: 
13073: =back
13074: 
13075: =head2 Storing/Retreiving Data
13076: 
13077: =over 4
13078: 
13079: =item *
13080: 
13081: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
13082: for this url; hashref needs to be given and should be a \%hashname; the
13083: remaining args aren't required and if they aren't passed or are '' they will
13084: be derived from the env
13085: 
13086: =item *
13087: 
13088: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
13089: uses critical subroutine
13090: 
13091: =item *
13092: 
13093: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
13094: all args are optional
13095: 
13096: =item *
13097: 
13098: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
13099: dumps the complete (or key matching regexp) namespace into a hash
13100: ($udom, $uname, $regexp, $range are optional) for a namespace that is
13101: normally &store()ed into
13102: 
13103: $range should be either an integer '100' (give me the first 100
13104:                                            matching records)
13105:               or be  two integers sperated by a - with no spaces
13106:                  '30-50' (give me the 30th through the 50th matching
13107:                           records)
13108: 
13109: 
13110: =item *
13111: 
13112: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
13113: replaces a &store() version of data with a replacement set of data
13114: for a particular resource in a namespace passed in the $storehash hash 
13115: reference
13116: 
13117: =item *
13118: 
13119: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
13120: works very similar to store/cstore, but all data is stored in a
13121: temporary location and can be reset using tmpreset, $storehash should
13122: be a hash reference, returns nothing on success
13123: 
13124: =item *
13125: 
13126: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
13127: similar to restore, but all data is stored in a temporary location and
13128: can be reset using tmpreset. Returns a hash of values on success,
13129: error string otherwise.
13130: 
13131: =item *
13132: 
13133: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
13134: deltes all keys for $symb form the temporary storage hash.
13135: 
13136: =item *
13137: 
13138: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13139: reference filled in from namesp ($udom and $uname are optional)
13140: 
13141: =item *
13142: 
13143: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
13144: namesp ($udom and $uname are optional)
13145: 
13146: =item *
13147: 
13148: dump($namespace,$udom,$uname,$regexp,$range) : 
13149: dumps the complete (or key matching regexp) namespace into a hash
13150: ($udom, $uname, $regexp, $range are optional)
13151: 
13152: $range should be either an integer '100' (give me the first 100
13153:                                            matching records)
13154:               or be  two integers sperated by a - with no spaces
13155:                  '30-50' (give me the 30th through the 50th matching
13156:                           records)
13157: =item *
13158: 
13159: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
13160: $store can be a scalar, an array reference, or if the amount to be 
13161: incremented is > 1, a hash reference.
13162: 
13163: ($udom and $uname are optional)
13164: 
13165: =item *
13166: 
13167: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
13168: ($udom and $uname are optional)
13169: 
13170: =item *
13171: 
13172: cput($namespace,$storehash,$udom,$uname) : critical put
13173: ($udom and $uname are optional)
13174: 
13175: =item *
13176: 
13177: newput($namespace,$storehash,$udom,$uname) :
13178: 
13179: Attempts to store the items in the $storehash, but only if they don't
13180: currently exist, if this succeeds you can be certain that you have 
13181: successfully created a new key value pair in the $namespace db.
13182: 
13183: 
13184: Args:
13185:  $namespace: name of database to store values to
13186:  $storehash: hashref to store to the db
13187:  $udom: (optional) domain of user containing the db
13188:  $uname: (optional) name of user caontaining the db
13189: 
13190: Returns:
13191:  'ok' -> succeeded in storing all keys of $storehash
13192:  'key_exists: <key>' -> failed to anything out of $storehash, as at
13193:                         least <key> already existed in the db (other
13194:                         requested keys may also already exist)
13195:  'error: <msg>' -> unable to tie the DB or other error occurred
13196:  'con_lost' -> unable to contact request server
13197:  'refused' -> action was not allowed by remote machine
13198: 
13199: 
13200: =item *
13201: 
13202: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13203: reference filled in from namesp (encrypts the return communication)
13204: ($udom and $uname are optional)
13205: 
13206: =item *
13207: 
13208: log($udom,$name,$home,$message) : write to permanent log for user; use
13209: critical subroutine
13210: 
13211: =item *
13212: 
13213: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
13214: array reference filled in from namespace found in domain level on either
13215: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
13216: 
13217: =item *
13218: 
13219: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
13220: domain level either on specified domain server ($uhome) or primary domain 
13221: server ($udom and $uhome are optional)
13222: 
13223: =item * 
13224: 
13225: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
13226: for: authentication, language, quotas, timezone, date locale, and portal URL in
13227: the target domain.
13228: 
13229: May also include additional key => value pairs for the following groups:
13230: 
13231: =over
13232: 
13233: =item
13234: disk quotas (MB allocated by default to portfolios and authoring spaces).
13235: 
13236: =over
13237: 
13238: =item defaultquota, authorquota
13239: 
13240: =back
13241: 
13242: =item
13243: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
13244: portfolio for users).
13245: 
13246: =over
13247: 
13248: =item
13249: aboutme, blog, webdav, portfolio
13250: 
13251: =back
13252: 
13253: =item
13254: requestcourses: ability to request courses, and how requests are processed.
13255: 
13256: =over
13257: 
13258: =item
13259: official, unofficial, community
13260: 
13261: =back
13262: 
13263: =item
13264: inststatus: types of institutional affiliation, and order in which they are displayed.
13265: 
13266: =over
13267: 
13268: =item
13269: inststatustypes, inststatusorder
13270: 
13271: =back
13272: 
13273: =item
13274: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
13275: for course's uploaded content.
13276: 
13277: =over
13278: 
13279: =item
13280: canuse_pdfforms, officialcredits, unofficialcredits, officialquota, unofficialquota, communityquota
13281: 
13282: =back
13283: 
13284: =item
13285: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
13286: on your servers.
13287: 
13288: =over
13289: 
13290: =item 
13291: remotesessions, hostedsessions
13292: 
13293: =back
13294: 
13295: =back
13296: 
13297: In cases where a domain coordinator has never used the "Set Domain Configuration"
13298: utility to create a configuration.db file on a domain's primary library server 
13299: only the following domain defaults: auth_def, auth_arg_def, lang_def
13300: -- corresponding values are authentication type (internal, krb4, krb5,
13301: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
13302: will be available. Values are retrieved from cache (if current), unless the
13303: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
13304: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
13305: 
13306: Typical usage:
13307: 
13308: %domdefaults = &get_domain_defaults($target_domain);
13309: 
13310: =back
13311: 
13312: =head2 Network Status Functions
13313: 
13314: =over 4
13315: 
13316: =item *
13317: 
13318: dirlist() : return directory list based on URI (first arg).
13319: 
13320: Inputs: 1 required, 5 optional.
13321: 
13322: =over
13323: 
13324: =item 
13325: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
13326: 
13327: =item
13328: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
13329: 
13330: =item
13331: $username -  username of user/course to be listed. Extracted from $uri if absent. 
13332: 
13333: =item
13334: $getpropath - boolean: 1 if prepend path using &propath(). 
13335: 
13336: =item
13337: $getuserdir - boolean: 1 if prepend path for "userfiles".
13338: 
13339: =item 
13340: $alternateRoot - path to prepend in place of path from $uri.
13341: 
13342: =back
13343: 
13344: Returns: Array of up to two items.
13345: 
13346: =over
13347: 
13348: a reference to an array of files/subdirectories
13349: 
13350: =over
13351: 
13352: Each element in the array of files/subdirectories is a & separated list of
13353: item name and the result of running stat on the item.  If dirlist was requested
13354: for a file instead of a directory, the item name will be ''. For a directory 
13355: listing, if the item is a metadata file, the element will end &N&M 
13356: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
13357: default copyright set (1).  
13358: 
13359: =back
13360: 
13361: a scalar containing error condition (if encountered).
13362: 
13363: =over
13364: 
13365: =item 
13366: no_host (no homeserver identified for $username:$domain).
13367: 
13368: =item 
13369: no_such_host (server contacted for listing not identified as valid host).
13370: 
13371: =item 
13372: con_lost (connection to remote server failed).
13373: 
13374: =item 
13375: refused (invalid $username:$domain received on lond side).
13376: 
13377: =item 
13378: no_such_dir (directory at specified path on lond side does not exist). 
13379: 
13380: =item 
13381: empty (directory at specified path on lond side is empty).
13382: 
13383: =over
13384: 
13385: This is currently not encountered because the &ls3, &ls2, 
13386: &ls (_handler) routines on the lond side do not filter out
13387: . and .. from a directory listing. 
13388: 
13389: =back
13390: 
13391: =back
13392: 
13393: =back
13394: 
13395: =item *
13396: 
13397: spareserver() : find server with least workload from spare.tab
13398: 
13399: 
13400: =item *
13401: 
13402: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
13403: if there is no corresponding loncapa host.
13404: 
13405: =back
13406: 
13407: 
13408: =head2 Apache Request
13409: 
13410: =over 4
13411: 
13412: =item *
13413: 
13414: ssi($url,%hash) : server side include, does a complete request cycle on url to
13415: localhost, posts hash
13416: 
13417: =back
13418: 
13419: =head2 Data to String to Data
13420: 
13421: =over 4
13422: 
13423: =item *
13424: 
13425: hash2str(%hash) : convert a hash into a string complete with escaping and '='
13426: and '&' separators, supports elements that are arrayrefs and hashrefs
13427: 
13428: =item *
13429: 
13430: hashref2str($hashref) : convert a hashref into a string complete with
13431: escaping and '=' and '&' separators, supports elements that are
13432: arrayrefs and hashrefs
13433: 
13434: =item *
13435: 
13436: arrayref2str($arrayref) : convert an arrayref into a string complete
13437: with escaping and '&' separators, supports elements that are arrayrefs
13438: and hashrefs
13439: 
13440: =item *
13441: 
13442: str2hash($string) : convert string to hash using unescaping and
13443: splitting on '=' and '&', supports elements that are arrayrefs and
13444: hashrefs
13445: 
13446: =item *
13447: 
13448: str2array($string) : convert string to hash using unescaping and
13449: splitting on '&', supports elements that are arrayrefs and hashrefs
13450: 
13451: =back
13452: 
13453: =head2 Logging Routines
13454: 
13455: 
13456: These routines allow one to make log messages in the lonnet.log and
13457: lonnet.perm logfiles.
13458: 
13459: =over 4
13460: 
13461: =item *
13462: 
13463: logtouch() : make sure the logfile, lonnet.log, exists
13464: 
13465: =item *
13466: 
13467: logthis() : append message to the normal lonnet.log file, it gets
13468: preiodically rolled over and deleted.
13469: 
13470: =item *
13471: 
13472: logperm() : append a permanent message to lonnet.perm.log, this log
13473: file never gets deleted by any automated portion of the system, only
13474: messages of critical importance should go in here.
13475: 
13476: 
13477: =back
13478: 
13479: =head2 General File Helper Routines
13480: 
13481: =over 4
13482: 
13483: =item *
13484: 
13485: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
13486: (a) files in /uploaded
13487:   (i) If a local copy of the file exists - 
13488:       compares modification date of local copy with last-modified date for 
13489:       definitive version stored on home server for course. If local copy is 
13490:       stale, requests a new version from the home server and stores it. 
13491:       If the original has been removed from the home server, then local copy 
13492:       is unlinked.
13493:   (ii) If local copy does not exist -
13494:       requests the file from the home server and stores it. 
13495:   
13496:   If $caller is 'uploadrep':  
13497:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
13498:     for request for files originally uploaded via DOCS. 
13499:      - returns 'ok' if fresh local copy now available, -1 otherwise.
13500:   
13501:   Otherwise:
13502:      This indicates a call from the content generation phase of the request.
13503:      -  returns the entire contents of the file or -1.
13504:      
13505: (b) files in /res
13506:    - returns the entire contents of a file or -1; 
13507:    it properly subscribes to and replicates the file if neccessary.
13508: 
13509: 
13510: =item *
13511: 
13512: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
13513:                   reference
13514: 
13515: returns either a stat() list of data about the file or an empty list
13516: if the file doesn't exist or couldn't find out about it (connection
13517: problems or user unknown)
13518: 
13519: =item *
13520: 
13521: filelocation($dir,$file) : returns file system location of a file
13522: based on URI; meant to be "fairly clean" absolute reference, $dir is a
13523: directory that relative $file lookups are to looked in ($dir of /a/dir
13524: and a file of ../bob will become /a/bob)
13525: 
13526: =item *
13527: 
13528: hreflocation($dir,$file) : returns file system location or a URL; same as
13529: filelocation except for hrefs
13530: 
13531: =item *
13532: 
13533: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
13534: 
13535: =back
13536: 
13537: =head2 Usererfile file routines (/uploaded*)
13538: 
13539: =over 4
13540: 
13541: =item *
13542: 
13543: userfileupload(): main rotine for putting a file in a user or course's
13544:                   filespace, arguments are,
13545: 
13546:  formname - required - this is the name of the element in $env where the
13547:            filename, and the contents of the file to create/modifed exist
13548:            the filename is in $env{'form.'.$formname.'.filename'} and the
13549:            contents of the file is located in $env{'form.'.$formname}
13550:  context - if coursedoc, store the file in the course of the active role
13551:              of the current user; 
13552:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
13553:            if 'canceloverwrite': delete file in tmp/overwrites directory
13554:  subdir - required - subdirectory to put the file in under ../userfiles/
13555:          if undefined, it will be placed in "unknown"
13556: 
13557:  (This routine calls clean_filename() to remove any dangerous
13558:  characters from the filename, and then calls finuserfileupload() to
13559:  complete the transaction)
13560: 
13561:  returns either the url of the uploaded file (/uploaded/....) if successful
13562:  and /adm/notfound.html if unsuccessful
13563: 
13564: =item *
13565: 
13566: clean_filename(): routine for cleaing a filename up for storage in
13567:                  userfile space, argument is:
13568: 
13569:  filename - proposed filename
13570: 
13571: returns: the new clean filename
13572: 
13573: =item *
13574: 
13575: finishuserfileupload(): routine that creates and sends the file to
13576: userspace, probably shouldn't be called directly
13577: 
13578:   docuname: username or courseid of destination for the file
13579:   docudom: domain of user/course of destination for the file
13580:   formname: same as for userfileupload()
13581:   fname: filename (including subdirectories) for the file
13582:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
13583:   allfiles: reference to hash used to store objects found by parser
13584:   codebase: reference to hash used for codebases of java objects found by parser
13585:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
13586:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
13587:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
13588:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
13589:   context: if 'overwrite', will move the uploaded file from its temporary location to
13590:             userfiles to facilitate overwriting a previously uploaded file with same name.
13591:   mimetype: reference to scalar to accommodate mime type determined
13592:             from File::MMagic if $parser = parse.
13593: 
13594:  returns either the url of the uploaded file (/uploaded/....) if successful
13595:  and /adm/notfound.html if unsuccessful (or an error message if context 
13596:  was 'overwrite').
13597:  
13598: 
13599: =item *
13600: 
13601: renameuserfile(): renames an existing userfile to a new name
13602: 
13603:   Args:
13604:    docuname: username or courseid of destination for the file
13605:    docudom: domain of user/course of destination for the file
13606:    old: current file name (including any subdirs under userfiles)
13607:    new: desired file name (including any subdirs under userfiles)
13608: 
13609: =item *
13610: 
13611: mkdiruserfile(): creates a directory is a userfiles dir
13612: 
13613:   Args:
13614:    docuname: username or courseid of destination for the file
13615:    docudom: domain of user/course of destination for the file
13616:    dir: dir to create (including any subdirs under userfiles)
13617: 
13618: =item *
13619: 
13620: removeuserfile(): removes a file that exists in userfiles
13621: 
13622:   Args:
13623:    docuname: username or courseid of destination for the file
13624:    docudom: domain of user/course of destination for the file
13625:    fname: filname to delete (including any subdirs under userfiles)
13626: 
13627: =item *
13628: 
13629: removeuploadedurl(): convience function for removeuserfile()
13630: 
13631:   Args:
13632:    url:  a full /uploaded/... url to delete
13633: 
13634: =item * 
13635: 
13636: get_portfile_permissions():
13637:   Args:
13638:     domain: domain of user or course contain the portfolio files
13639:     user: name of user or num of course contain the portfolio files
13640:   Returns:
13641:     hashref of a dump of the proper file_permissions.db
13642:    
13643: 
13644: =item * 
13645: 
13646: get_access_controls():
13647: 
13648: Args:
13649:   current_permissions: the hash ref returned from get_portfile_permissions()
13650:   group: (optional) the group you want the files associated with
13651:   file: (optional) the file you want access info on
13652: 
13653: Returns:
13654:     a hash (keys are file names) of hashes containing
13655:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
13656:         values are XML containing access control settings (see below) 
13657: 
13658: Internal notes:
13659: 
13660:  access controls are stored in file_permissions.db as key=value pairs.
13661:     key -> path to file/file_name\0uniqueID:scope_end_start
13662:         where scope -> public,guest,course,group,domains or users.
13663:               end -> UNIX time for end of access (0 -> no end date)
13664:               start -> UNIX time for start of access
13665: 
13666:     value -> XML description of access control
13667:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
13668:             <start></start>
13669:             <end></end>
13670: 
13671:             <password></password>  for scope type = guest
13672: 
13673:             <domain></domain>     for scope type = course or group
13674:             <number></number>
13675:             <roles id="">
13676:              <role></role>
13677:              <access></access>
13678:              <section></section>
13679:              <group></group>
13680:             </roles>
13681: 
13682:             <dom></dom>         for scope type = domains
13683: 
13684:             <users>             for scope type = users
13685:              <user>
13686:               <uname></uname>
13687:               <udom></udom>
13688:              </user>
13689:             </users>
13690:            </scope> 
13691:               
13692:  Access data is also aggregated for each file in an additional key=value pair:
13693:  key -> path to file/file_name\0accesscontrol 
13694:  value -> reference to hash
13695:           hash contains key = value pairs
13696:           where key = uniqueID:scope_end_start
13697:                 value = UNIX time record was last updated
13698: 
13699:           Used to improve speed of look-ups of access controls for each file.  
13700:  
13701:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
13702: 
13703: =item *
13704: 
13705: modify_access_controls():
13706: 
13707: Modifies access controls for a portfolio file
13708: Args
13709: 1. file name
13710: 2. reference to hash of required changes,
13711: 3. domain
13712: 4. username
13713:   where domain,username are the domain of the portfolio owner 
13714:   (either a user or a course) 
13715: 
13716: Returns:
13717: 1. result of additions or updates ('ok' or 'error', with error message). 
13718: 2. result of deletions ('ok' or 'error', with error message).
13719: 3. reference to hash of any new or updated access controls.
13720: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
13721:    key = integer (inbound ID)
13722:    value = uniqueID
13723: 
13724: =item *
13725: 
13726: get_timebased_id():
13727: 
13728: Attempts to get a unique timestamp-based suffix for use with items added to a 
13729: course via the Course Editor (e.g., folders, composite pages, 
13730: group bulletin boards).
13731: 
13732: Args: (first three required; six others optional)
13733: 
13734: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
13735:    docssequence, or name of group
13736: 
13737: 2. keyid (alphanumeric): name of temporary locking key in hash,
13738:    e.g., num, boardids
13739: 
13740: 3. namespace: name of gdbm file used to store suffixes already assigned;  
13741:    file will be named nohist_namespace.db
13742: 
13743: 4. cdom: domain of course; default is current course domain from %env
13744: 
13745: 5. cnum: course number; default is current course number from %env
13746: 
13747: 6. idtype: set to concat if an additional digit is to be appended to the 
13748:    unix timestamp to form the suffix, if the plain timestamp is already
13749:    in use.  Default is to not do this, but simply increment the unix 
13750:    timestamp by 1 until a unique key is obtained.
13751: 
13752: 7. who: holder of locking key; defaults to user:domain for user.
13753: 
13754: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
13755:    retrying); default is 3.
13756: 
13757: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
13758: 
13759: Returns:
13760: 
13761: 1. suffix obtained (numeric)
13762: 
13763: 2. result of deleting locking key (ok if deleted, or lock never obtained)
13764: 
13765: 3. error: contains (localized) error message if an error occurred.
13766: 
13767: 
13768: =back
13769: 
13770: =head2 HTTP Helper Routines
13771: 
13772: =over 4
13773: 
13774: =item *
13775: 
13776: escape() : unpack non-word characters into CGI-compatible hex codes
13777: 
13778: =item *
13779: 
13780: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
13781: 
13782: =back
13783: 
13784: =head1 PRIVATE SUBROUTINES
13785: 
13786: =head2 Underlying communication routines (Shouldn't call)
13787: 
13788: =over 4
13789: 
13790: =item *
13791: 
13792: subreply() : tries to pass a message to lonc, returns con_lost if incapable
13793: 
13794: =item *
13795: 
13796: reply() : uses subreply to send a message to remote machine, logs all failures
13797: 
13798: =item *
13799: 
13800: critical() : passes a critical message to another server; if cannot
13801: get through then place message in connection buffer directory and
13802: returns con_delayed, if incapable of saving message, returns
13803: con_failed
13804: 
13805: =item *
13806: 
13807: reconlonc() : tries to reconnect lonc client processes.
13808: 
13809: =back
13810: 
13811: =head2 Resource Access Logging
13812: 
13813: =over 4
13814: 
13815: =item *
13816: 
13817: flushcourselogs() : flush (save) buffer logs and access logs
13818: 
13819: =item *
13820: 
13821: courselog($what) : save message for course in hash
13822: 
13823: =item *
13824: 
13825: courseacclog($what) : save message for course using &courselog().  Perform
13826: special processing for specific resource types (problems, exams, quizzes, etc).
13827: 
13828: =item *
13829: 
13830: goodbye() : flush course logs and log shutting down; it is called in srm.conf
13831: as a PerlChildExitHandler
13832: 
13833: =back
13834: 
13835: =head2 Other
13836: 
13837: =over 4
13838: 
13839: =item *
13840: 
13841: symblist($mapname,%newhash) : update symbolic storage links
13842: 
13843: =back
13844: 
13845: =cut
13846: 

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