File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1225: download - view: text, annotated - select for diffs
Mon May 27 18:35:05 2013 UTC (11 years, 1 month ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Update POD

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1225 2013/05/27 18:35:05 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:         my ($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: # ------------------------------dump from db file owned by domainconfig user
 1582: sub dump_dom {
 1583:     my ($namespace, $udom, $regexp) = @_;
 1584: 
 1585:     $udom ||= $env{'user.domain'};
 1586: 
 1587:     return () unless $udom;
 1588: 
 1589:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
 1590: }
 1591: 
 1592: # ------------------------------------------ get items from domain db files   
 1593: 
 1594: sub get_dom {
 1595:     my ($namespace,$storearr,$udom,$uhome)=@_;
 1596:     my $items='';
 1597:     foreach my $item (@$storearr) {
 1598:         $items.=&escape($item).'&';
 1599:     }
 1600:     $items=~s/\&$//;
 1601:     if (!$udom) {
 1602:         $udom=$env{'user.domain'};
 1603:         if (defined(&domain($udom,'primary'))) {
 1604:             $uhome=&domain($udom,'primary');
 1605:         } else {
 1606:             undef($uhome);
 1607:         }
 1608:     } else {
 1609:         if (!$uhome) {
 1610:             if (defined(&domain($udom,'primary'))) {
 1611:                 $uhome=&domain($udom,'primary');
 1612:             }
 1613:         }
 1614:     }
 1615:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1616:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 1617:         my %returnhash;
 1618:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 1619:             return %returnhash;
 1620:         }
 1621:         my @pairs=split(/\&/,$rep);
 1622:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 1623:             return @pairs;
 1624:         }
 1625:         my $i=0;
 1626:         foreach my $item (@$storearr) {
 1627:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 1628:             $i++;
 1629:         }
 1630:         return %returnhash;
 1631:     } else {
 1632:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 1633:     }
 1634: }
 1635: 
 1636: # -------------------------------------------- put items in domain db files 
 1637: 
 1638: sub put_dom {
 1639:     my ($namespace,$storehash,$udom,$uhome)=@_;
 1640:     if (!$udom) {
 1641:         $udom=$env{'user.domain'};
 1642:         if (defined(&domain($udom,'primary'))) {
 1643:             $uhome=&domain($udom,'primary');
 1644:         } else {
 1645:             undef($uhome);
 1646:         }
 1647:     } else {
 1648:         if (!$uhome) {
 1649:             if (defined(&domain($udom,'primary'))) {
 1650:                 $uhome=&domain($udom,'primary');
 1651:             }
 1652:         }
 1653:     } 
 1654:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1655:         my $items='';
 1656:         foreach my $item (keys(%$storehash)) {
 1657:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 1658:         }
 1659:         $items=~s/\&$//;
 1660:         return &reply("putdom:$udom:$namespace:$items",$uhome);
 1661:     } else {
 1662:         &logthis("put_dom failed - no homeserver and/or domain");
 1663:     }
 1664: }
 1665: 
 1666: # --------------------- newput for items in db file owned by domainconfig user
 1667: sub newput_dom {
 1668:     my ($namespace,$storehash,$udom) = @_;
 1669:     my $result;
 1670:     if (!$udom) {
 1671:         $udom=$env{'user.domain'};
 1672:     }
 1673:     if ($udom) {
 1674:         my $uname = &get_domainconfiguser($udom);
 1675:         $result = &newput($namespace,$storehash,$udom,$uname);
 1676:     }
 1677:     return $result;
 1678: }
 1679: 
 1680: # --------------------- delete for items in db file owned by domainconfig user
 1681: sub del_dom {
 1682:     my ($namespace,$storearr,$udom)=@_;
 1683:     if (ref($storearr) eq 'ARRAY') {
 1684:         if (!$udom) {
 1685:             $udom=$env{'user.domain'};
 1686:         }
 1687:         if ($udom) {
 1688:             my $uname = &get_domainconfiguser($udom); 
 1689:             return &del($namespace,$storearr,$udom,$uname);
 1690:         }
 1691:     }
 1692: }
 1693: 
 1694: # ----------------------------------construct domainconfig user for a domain 
 1695: sub get_domainconfiguser {
 1696:     my ($udom) = @_;
 1697:     return $udom.'-domainconfig';
 1698: }
 1699: 
 1700: sub retrieve_inst_usertypes {
 1701:     my ($udom) = @_;
 1702:     my (%returnhash,@order);
 1703:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 1704:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 1705:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 1706:         %returnhash = %{$domdefs{'inststatustypes'}};
 1707:         @order = @{$domdefs{'inststatusorder'}};
 1708:     } else {
 1709:         if (defined(&domain($udom,'primary'))) {
 1710:             my $uhome=&domain($udom,'primary');
 1711:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 1712:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 1713:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
 1714:                 return (\%returnhash,\@order);
 1715:             }
 1716:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 1717:             my @pairs=split(/\&/,$hashitems);
 1718:             foreach my $item (@pairs) {
 1719:                 my ($key,$value)=split(/=/,$item,2);
 1720:                 $key = &unescape($key);
 1721:                 next if ($key =~ /^error: 2 /);
 1722:                 $returnhash{$key}=&thaw_unescape($value);
 1723:             }
 1724:             my @esc_order = split(/\&/,$orderitems);
 1725:             foreach my $item (@esc_order) {
 1726:                 push(@order,&unescape($item));
 1727:             }
 1728:         } else {
 1729:             &logthis("get_dom failed - no primary domain server for $udom");
 1730:         }
 1731:     }
 1732:     return (\%returnhash,\@order);
 1733: }
 1734: 
 1735: sub is_domainimage {
 1736:     my ($url) = @_;
 1737:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
 1738:         if (&domain($1) ne '') {
 1739:             return '1';
 1740:         }
 1741:     }
 1742:     return;
 1743: }
 1744: 
 1745: sub inst_directory_query {
 1746:     my ($srch) = @_;
 1747:     my $udom = $srch->{'srchdomain'};
 1748:     my %results;
 1749:     my $homeserver = &domain($udom,'primary');
 1750:     my $outcome;
 1751:     if ($homeserver ne '') {
 1752: 	my $queryid=&reply("querysend:instdirsearch:".
 1753: 			   &escape($srch->{'srchby'}).':'.
 1754: 			   &escape($srch->{'srchterm'}).':'.
 1755: 			   &escape($srch->{'srchtype'}),$homeserver);
 1756: 	my $host=&hostname($homeserver);
 1757: 	if ($queryid !~/^\Q$host\E\_/) {
 1758: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1759: 	    return;
 1760: 	}
 1761: 	my $response = &get_query_reply($queryid);
 1762: 	my $maxtries = 5;
 1763: 	my $tries = 1;
 1764: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1765: 	    $response = &get_query_reply($queryid);
 1766: 	    $tries ++;
 1767: 	}
 1768: 
 1769:         if (!&error($response) && $response ne 'refused') {
 1770:             if ($response eq 'unavailable') {
 1771:                 $outcome = $response;
 1772:             } else {
 1773:                 $outcome = 'ok';
 1774:                 my @matches = split(/\n/,$response);
 1775:                 foreach my $match (@matches) {
 1776:                     my ($key,$value) = split(/=/,$match);
 1777:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 1778:                 }
 1779:             }
 1780:         }
 1781:     }
 1782:     return ($outcome,%results);
 1783: }
 1784: 
 1785: sub usersearch {
 1786:     my ($srch) = @_;
 1787:     my $dom = $srch->{'srchdomain'};
 1788:     my %results;
 1789:     my %libserv = &all_library();
 1790:     my $query = 'usersearch';
 1791:     foreach my $tryserver (keys(%libserv)) {
 1792:         if (&host_domain($tryserver) eq $dom) {
 1793:             my $host=&hostname($tryserver);
 1794:             my $queryid=
 1795:                 &reply("querysend:".&escape($query).':'.
 1796:                        &escape($srch->{'srchby'}).':'.
 1797:                        &escape($srch->{'srchtype'}).':'.
 1798:                        &escape($srch->{'srchterm'}),$tryserver);
 1799:             if ($queryid !~/^\Q$host\E\_/) {
 1800:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 1801:                 next;
 1802:             }
 1803:             my $reply = &get_query_reply($queryid);
 1804:             my $maxtries = 1;
 1805:             my $tries = 1;
 1806:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 1807:                 $reply = &get_query_reply($queryid);
 1808:                 $tries ++;
 1809:             }
 1810:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 1811:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 1812:             } else {
 1813:                 my @matches;
 1814:                 if ($reply =~ /\n/) {
 1815:                     @matches = split(/\n/,$reply);
 1816:                 } else {
 1817:                     @matches = split(/\&/,$reply);
 1818:                 }
 1819:                 foreach my $match (@matches) {
 1820:                     my ($uname,$udom,%userhash);
 1821:                     foreach my $entry (split(/:/,$match)) {
 1822:                         my ($key,$value) =
 1823:                             map {&unescape($_);} split(/=/,$entry);
 1824:                         $userhash{$key} = $value;
 1825:                         if ($key eq 'username') {
 1826:                             $uname = $value;
 1827:                         } elsif ($key eq 'domain') {
 1828:                             $udom = $value;
 1829:                         }
 1830:                     }
 1831:                     $results{$uname.':'.$udom} = \%userhash;
 1832:                 }
 1833:             }
 1834:         }
 1835:     }
 1836:     return %results;
 1837: }
 1838: 
 1839: sub get_instuser {
 1840:     my ($udom,$uname,$id) = @_;
 1841:     my $homeserver = &domain($udom,'primary');
 1842:     my ($outcome,%results);
 1843:     if ($homeserver ne '') {
 1844:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 1845:                            &escape($id).':'.&escape($udom),$homeserver);
 1846:         my $host=&hostname($homeserver);
 1847:         if ($queryid !~/^\Q$host\E\_/) {
 1848:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1849:             return;
 1850:         }
 1851:         my $response = &get_query_reply($queryid);
 1852:         my $maxtries = 5;
 1853:         my $tries = 1;
 1854:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1855:             $response = &get_query_reply($queryid);
 1856:             $tries ++;
 1857:         }
 1858:         if (!&error($response) && $response ne 'refused') {
 1859:             if ($response eq 'unavailable') {
 1860:                 $outcome = $response;
 1861:             } else {
 1862:                 $outcome = 'ok';
 1863:                 my @matches = split(/\n/,$response);
 1864:                 foreach my $match (@matches) {
 1865:                     my ($key,$value) = split(/=/,$match);
 1866:                     $results{&unescape($key)} = &thaw_unescape($value);
 1867:                 }
 1868:             }
 1869:         }
 1870:     }
 1871:     my %userinfo;
 1872:     if (ref($results{$uname}) eq 'HASH') {
 1873:         %userinfo = %{$results{$uname}};
 1874:     } 
 1875:     return ($outcome,%userinfo);
 1876: }
 1877: 
 1878: sub inst_rulecheck {
 1879:     my ($udom,$uname,$id,$item,$rules) = @_;
 1880:     my %returnhash;
 1881:     if ($udom ne '') {
 1882:         if (ref($rules) eq 'ARRAY') {
 1883:             @{$rules} = map {&escape($_);} (@{$rules});
 1884:             my $rulestr = join(':',@{$rules});
 1885:             my $homeserver=&domain($udom,'primary');
 1886:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1887:                 my $response;
 1888:                 if ($item eq 'username') {                
 1889:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 1890:                                               ':'.&escape($uname).':'.$rulestr,
 1891:                                               $homeserver));
 1892:                 } elsif ($item eq 'id') {
 1893:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 1894:                                               ':'.&escape($id).':'.$rulestr,
 1895:                                               $homeserver));
 1896:                 } elsif ($item eq 'selfcreate') {
 1897:                     $response=&unescape(&reply('instselfcreatecheck:'.
 1898:                                                &escape($udom).':'.&escape($uname).
 1899:                                               ':'.$rulestr,$homeserver));
 1900:                 }
 1901:                 if ($response ne 'refused') {
 1902:                     my @pairs=split(/\&/,$response);
 1903:                     foreach my $item (@pairs) {
 1904:                         my ($key,$value)=split(/=/,$item,2);
 1905:                         $key = &unescape($key);
 1906:                         next if ($key =~ /^error: 2 /);
 1907:                         $returnhash{$key}=&thaw_unescape($value);
 1908:                     }
 1909:                 }
 1910:             }
 1911:         }
 1912:     }
 1913:     return %returnhash;
 1914: }
 1915: 
 1916: sub inst_userrules {
 1917:     my ($udom,$check) = @_;
 1918:     my (%ruleshash,@ruleorder);
 1919:     if ($udom ne '') {
 1920:         my $homeserver=&domain($udom,'primary');
 1921:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1922:             my $response;
 1923:             if ($check eq 'id') {
 1924:                 $response=&reply('instidrules:'.&escape($udom),
 1925:                                  $homeserver);
 1926:             } elsif ($check eq 'email') {
 1927:                 $response=&reply('instemailrules:'.&escape($udom),
 1928:                                  $homeserver);
 1929:             } else {
 1930:                 $response=&reply('instuserrules:'.&escape($udom),
 1931:                                  $homeserver);
 1932:             }
 1933:             if (($response ne 'refused') && ($response ne 'error') && 
 1934:                 ($response ne 'unknown_cmd') && 
 1935:                 ($response ne 'no_such_host')) {
 1936:                 my ($hashitems,$orderitems) = split(/:/,$response);
 1937:                 my @pairs=split(/\&/,$hashitems);
 1938:                 foreach my $item (@pairs) {
 1939:                     my ($key,$value)=split(/=/,$item,2);
 1940:                     $key = &unescape($key);
 1941:                     next if ($key =~ /^error: 2 /);
 1942:                     $ruleshash{$key}=&thaw_unescape($value);
 1943:                 }
 1944:                 my @esc_order = split(/\&/,$orderitems);
 1945:                 foreach my $item (@esc_order) {
 1946:                     push(@ruleorder,&unescape($item));
 1947:                 }
 1948:             }
 1949:         }
 1950:     }
 1951:     return (\%ruleshash,\@ruleorder);
 1952: }
 1953: 
 1954: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 1955: 
 1956: sub get_domain_defaults {
 1957:     my ($domain) = @_;
 1958:     my $cachetime = 60*60*24;
 1959:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 1960:     if (defined($cached)) {
 1961:         if (ref($result) eq 'HASH') {
 1962:             return %{$result};
 1963:         }
 1964:     }
 1965:     my %domdefaults;
 1966:     my %domconfig =
 1967:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 1968:                                   'requestcourses','inststatus',
 1969:                                   'coursedefaults','usersessions',
 1970:                                   'requestauthor'],$domain);
 1971:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 1972:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 1973:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 1974:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 1975:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 1976:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 1977:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
 1978:     } else {
 1979:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 1980:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 1981:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 1982:     }
 1983:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 1984:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 1985:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 1986:         } else {
 1987:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 1988:         } 
 1989:         my @usertools = ('aboutme','blog','webdav','portfolio');
 1990:         foreach my $item (@usertools) {
 1991:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 1992:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 1993:             }
 1994:         }
 1995:     }
 1996:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 1997:         foreach my $item ('official','unofficial','community') {
 1998:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 1999:         }
 2000:     }
 2001:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
 2002:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
 2003:     }
 2004:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 2005:         foreach my $item ('inststatustypes','inststatusorder') {
 2006:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 2007:         }
 2008:     }
 2009:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 2010:         foreach my $item ('canuse_pdfforms') {
 2011:             $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
 2012:         }
 2013:         if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
 2014:             $domdefaults{'officialcredits'} = $domconfig{'coursedefaults'}{'coursecredits'}{'official'};
 2015:             $domdefaults{'unofficialcredits'} = $domconfig{'coursedefaults'}{'coursecredits'}{'unofficial'};
 2016:         }
 2017:     }
 2018:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 2019:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 2020:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 2021:         }
 2022:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 2023:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 2024:         }
 2025:     }
 2026:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
 2027:     return %domdefaults;
 2028: }
 2029: 
 2030: # --------------------------------------------------- Assign a key to a student
 2031: 
 2032: sub assign_access_key {
 2033: #
 2034: # a valid key looks like uname:udom#comments
 2035: # comments are being appended
 2036: #
 2037:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 2038:     $kdom=
 2039:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 2040:     $knum=
 2041:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 2042:     $cdom=
 2043:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2044:     $cnum=
 2045:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2046:     $udom=$env{'user.name'} unless (defined($udom));
 2047:     $uname=$env{'user.domain'} unless (defined($uname));
 2048:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 2049:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 2050:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 2051:                                                   # assigned to this person
 2052:                                                   # - this should not happen,
 2053:                                                   # unless something went wrong
 2054:                                                   # the first time around
 2055: # ready to assign
 2056:         $logentry=$1.'; '.$logentry;
 2057:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 2058:                                                  $kdom,$knum) eq 'ok') {
 2059: # key now belongs to user
 2060: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 2061:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 2062:                 &appenv({'environment.'.$envkey => $ckey});
 2063:                 return 'ok';
 2064:             } else {
 2065:                 return 
 2066:   'error: Count not permanently assign key, will need to be re-entered later.';
 2067: 	    }
 2068:         } else {
 2069:             return 'error: Could not assign key, try again later.';
 2070:         }
 2071:     } elsif (!$existing{$ckey}) {
 2072: # the key does not exist
 2073: 	return 'error: The key does not exist';
 2074:     } else {
 2075: # the key is somebody else's
 2076: 	return 'error: The key is already in use';
 2077:     }
 2078: }
 2079: 
 2080: # ------------------------------------------ put an additional comment on a key
 2081: 
 2082: sub comment_access_key {
 2083: #
 2084: # a valid key looks like uname:udom#comments
 2085: # comments are being appended
 2086: #
 2087:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 2088:     $cdom=
 2089:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2090:     $cnum=
 2091:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2092:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2093:     if ($existing{$ckey}) {
 2094:         $existing{$ckey}.='; '.$logentry;
 2095: # ready to assign
 2096:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 2097:                                                  $cdom,$cnum) eq 'ok') {
 2098: 	    return 'ok';
 2099:         } else {
 2100: 	    return 'error: Count not store comment.';
 2101:         }
 2102:     } else {
 2103: # the key does not exist
 2104: 	return 'error: The key does not exist';
 2105:     }
 2106: }
 2107: 
 2108: # ------------------------------------------------------ Generate a set of keys
 2109: 
 2110: sub generate_access_keys {
 2111:     my ($number,$cdom,$cnum,$logentry)=@_;
 2112:     $cdom=
 2113:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2114:     $cnum=
 2115:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2116:     unless (&allowed('mky',$cdom)) { return 0; }
 2117:     unless (($cdom) && ($cnum)) { return 0; }
 2118:     if ($number>10000) { return 0; }
 2119:     sleep(2); # make sure don't get same seed twice
 2120:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 2121:     my $total=0;
 2122:     for (my $i=1;$i<=$number;$i++) {
 2123:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 2124:                   sprintf("%lx",int(100000*rand)).'-'.
 2125:                   sprintf("%lx",int(100000*rand));
 2126:        $newkey=~s/1/g/g; # folks mix up 1 and l
 2127:        $newkey=~s/0/h/g; # and also 0 and O
 2128:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 2129:        if ($existing{$newkey}) {
 2130:            $i--;
 2131:        } else {
 2132: 	  if (&put('accesskeys',
 2133:               { $newkey => '# generated '.localtime().
 2134:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 2135:                            '; '.$logentry },
 2136: 		   $cdom,$cnum) eq 'ok') {
 2137:               $total++;
 2138: 	  }
 2139:        }
 2140:     }
 2141:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 2142:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 2143:     return $total;
 2144: }
 2145: 
 2146: # ------------------------------------------------------- Validate an accesskey
 2147: 
 2148: sub validate_access_key {
 2149:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 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:     $udom=$env{'user.domain'} unless (defined($udom));
 2155:     $uname=$env{'user.name'} unless (defined($uname));
 2156:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2157:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 2158: }
 2159: 
 2160: # ------------------------------------- Find the section of student in a course
 2161: sub devalidate_getsection_cache {
 2162:     my ($udom,$unam,$courseid)=@_;
 2163:     my $hashid="$udom:$unam:$courseid";
 2164:     &devalidate_cache_new('getsection',$hashid);
 2165: }
 2166: 
 2167: sub courseid_to_courseurl {
 2168:     my ($courseid) = @_;
 2169:     #already url style courseid
 2170:     return $courseid if ($courseid =~ m{^/});
 2171: 
 2172:     if (exists($env{'course.'.$courseid.'.num'})) {
 2173: 	my $cnum = $env{'course.'.$courseid.'.num'};
 2174: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 2175: 	return "/$cdom/$cnum";
 2176:     }
 2177: 
 2178:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 2179:     if (exists($courseinfo{'num'})) {
 2180: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 2181:     }
 2182: 
 2183:     return undef;
 2184: }
 2185: 
 2186: sub getsection {
 2187:     my ($udom,$unam,$courseid)=@_;
 2188:     my $cachetime=1800;
 2189: 
 2190:     my $hashid="$udom:$unam:$courseid";
 2191:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 2192:     if (defined($cached)) { return $result; }
 2193: 
 2194:     my %Pending; 
 2195:     my %Expired;
 2196:     #
 2197:     # Each role can either have not started yet (pending), be active, 
 2198:     #    or have expired.
 2199:     #
 2200:     # If there is an active role, we are done.
 2201:     #
 2202:     # If there is more than one role which has not started yet, 
 2203:     #     choose the one which will start sooner
 2204:     # If there is one role which has not started yet, return it.
 2205:     #
 2206:     # If there is more than one expired role, choose the one which ended last.
 2207:     # If there is a role which has expired, return it.
 2208:     #
 2209:     $courseid = &courseid_to_courseurl($courseid);
 2210:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 2211:     foreach my $key (keys(%roleshash)) {
 2212:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 2213:         my $section=$1;
 2214:         if ($key eq $courseid.'_st') { $section=''; }
 2215:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 2216:         my $now=time;
 2217:         if (defined($end) && $end && ($now > $end)) {
 2218:             $Expired{$end}=$section;
 2219:             next;
 2220:         }
 2221:         if (defined($start) && $start && ($now < $start)) {
 2222:             $Pending{$start}=$section;
 2223:             next;
 2224:         }
 2225:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 2226:     }
 2227:     #
 2228:     # Presumedly there will be few matching roles from the above
 2229:     # loop and the sorting time will be negligible.
 2230:     if (scalar(keys(%Pending))) {
 2231:         my ($time) = sort {$a <=> $b} keys(%Pending);
 2232:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 2233:     } 
 2234:     if (scalar(keys(%Expired))) {
 2235:         my @sorted = sort {$a <=> $b} keys(%Expired);
 2236:         my $time = pop(@sorted);
 2237:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 2238:     }
 2239:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 2240: }
 2241: 
 2242: sub save_cache {
 2243:     &purge_remembered();
 2244:     #&Apache::loncommon::validate_page();
 2245:     undef(%env);
 2246:     undef($env_loaded);
 2247: }
 2248: 
 2249: my $to_remember=-1;
 2250: my %remembered;
 2251: my %accessed;
 2252: my $kicks=0;
 2253: my $hits=0;
 2254: sub make_key {
 2255:     my ($name,$id) = @_;
 2256:     if (length($id) > 65 
 2257: 	&& length(&escape($id)) > 200) {
 2258: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 2259:     }
 2260:     return &escape($name.':'.$id);
 2261: }
 2262: 
 2263: sub devalidate_cache_new {
 2264:     my ($name,$id,$debug) = @_;
 2265:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 2266:     $id=&make_key($name,$id);
 2267:     $memcache->delete($id);
 2268:     delete($remembered{$id});
 2269:     delete($accessed{$id});
 2270: }
 2271: 
 2272: sub is_cached_new {
 2273:     my ($name,$id,$debug) = @_;
 2274:     $id=&make_key($name,$id);
 2275:     if (exists($remembered{$id})) {
 2276: 	if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
 2277: 	$accessed{$id}=[&gettimeofday()];
 2278: 	$hits++;
 2279: 	return ($remembered{$id},1);
 2280:     }
 2281:     my $value = $memcache->get($id);
 2282:     if (!(defined($value))) {
 2283: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 2284: 	return (undef,undef);
 2285:     }
 2286:     if ($value eq '__undef__') {
 2287: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 2288: 	$value=undef;
 2289:     }
 2290:     &make_room($id,$value,$debug);
 2291:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 2292:     return ($value,1);
 2293: }
 2294: 
 2295: sub do_cache_new {
 2296:     my ($name,$id,$value,$time,$debug) = @_;
 2297:     $id=&make_key($name,$id);
 2298:     my $setvalue=$value;
 2299:     if (!defined($setvalue)) {
 2300: 	$setvalue='__undef__';
 2301:     }
 2302:     if (!defined($time) ) {
 2303: 	$time=600;
 2304:     }
 2305:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 2306:     my $result = $memcache->set($id,$setvalue,$time);
 2307:     if (! $result) {
 2308: 	&logthis("caching of id -> $id  failed");
 2309: 	$memcache->disconnect_all();
 2310:     }
 2311:     # need to make a copy of $value
 2312:     &make_room($id,$value,$debug);
 2313:     return $value;
 2314: }
 2315: 
 2316: sub make_room {
 2317:     my ($id,$value,$debug)=@_;
 2318: 
 2319:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
 2320:                                     : $value;
 2321:     if ($to_remember<0) { return; }
 2322:     $accessed{$id}=[&gettimeofday()];
 2323:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 2324:     my $to_kick;
 2325:     my $max_time=0;
 2326:     foreach my $other (keys(%accessed)) {
 2327: 	if (&tv_interval($accessed{$other}) > $max_time) {
 2328: 	    $to_kick=$other;
 2329: 	    $max_time=&tv_interval($accessed{$other});
 2330: 	}
 2331:     }
 2332:     delete($remembered{$to_kick});
 2333:     delete($accessed{$to_kick});
 2334:     $kicks++;
 2335:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 2336:     return;
 2337: }
 2338: 
 2339: sub purge_remembered {
 2340:     #&logthis("Tossing ".scalar(keys(%remembered)));
 2341:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 2342:     undef(%remembered);
 2343:     undef(%accessed);
 2344: }
 2345: # ------------------------------------- Read an entry from a user's environment
 2346: 
 2347: sub userenvironment {
 2348:     my ($udom,$unam,@what)=@_;
 2349:     my $items;
 2350:     foreach my $item (@what) {
 2351:         $items.=&escape($item).'&';
 2352:     }
 2353:     $items=~s/\&$//;
 2354:     my %returnhash=();
 2355:     my $uhome = &homeserver($unam,$udom);
 2356:     unless ($uhome eq 'no_host') {
 2357:         my @answer=split(/\&/, 
 2358:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 2359:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 2360:             return %returnhash;
 2361:         }
 2362:         my $i;
 2363:         for ($i=0;$i<=$#what;$i++) {
 2364: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 2365:         }
 2366:     }
 2367:     return %returnhash;
 2368: }
 2369: 
 2370: # ---------------------------------------------------------- Get a studentphoto
 2371: sub studentphoto {
 2372:     my ($udom,$unam,$ext) = @_;
 2373:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2374:     if (defined($env{'request.course.id'})) {
 2375:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 2376:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 2377:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 2378:             } else {
 2379:                 my ($result,$perm_reqd)=
 2380: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2381:                 if ($result eq 'ok') {
 2382:                     if (!($perm_reqd eq 'yes')) {
 2383:                         return(&retrievestudentphoto($udom,$unam,$ext));
 2384:                     }
 2385:                 }
 2386:             }
 2387:         }
 2388:     } else {
 2389:         my ($result,$perm_reqd) = 
 2390: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2391:         if ($result eq 'ok') {
 2392:             if (!($perm_reqd eq 'yes')) {
 2393:                 return(&retrievestudentphoto($udom,$unam,$ext));
 2394:             }
 2395:         }
 2396:     }
 2397:     return '/adm/lonKaputt/lonlogo_broken.gif';
 2398: }
 2399: 
 2400: sub retrievestudentphoto {
 2401:     my ($udom,$unam,$ext,$type) = @_;
 2402:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2403:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 2404:     if ($ret eq 'ok') {
 2405:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 2406:         if ($type eq 'thumbnail') {
 2407:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 2408:         }
 2409:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 2410:         return $tokenurl;
 2411:     } else {
 2412:         if ($type eq 'thumbnail') {
 2413:             return '/adm/lonKaputt/genericstudent_tn.gif';
 2414:         } else { 
 2415:             return '/adm/lonKaputt/lonlogo_broken.gif';
 2416:         }
 2417:     }
 2418: }
 2419: 
 2420: # -------------------------------------------------------------------- New chat
 2421: 
 2422: sub chatsend {
 2423:     my ($newentry,$anon,$group)=@_;
 2424:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 2425:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2426:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 2427:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 2428: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 2429: 		   &escape($newentry)).':'.$group,$chome);
 2430: }
 2431: 
 2432: # ------------------------------------------ Find current version of a resource
 2433: 
 2434: sub getversion {
 2435:     my $fname=&clutter(shift);
 2436:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
 2437:     return &currentversion(&filelocation('',$fname));
 2438: }
 2439: 
 2440: sub currentversion {
 2441:     my $fname=shift;
 2442:     my $author=$fname;
 2443:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2444:     my ($udom,$uname)=split(/\//,$author);
 2445:     my $home=&homeserver($uname,$udom);
 2446:     if ($home eq 'no_host') { 
 2447:         return -1; 
 2448:     }
 2449:     my $answer=&reply("currentversion:$fname",$home);
 2450:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 2451: 	return -1;
 2452:     }
 2453:     return $answer;
 2454: }
 2455: 
 2456: #
 2457: # Return special version number of resource if set by override, empty otherwise
 2458: #
 2459: sub usedversion {
 2460:     my $fname=shift;
 2461:     unless ($fname) { $fname=$env{'request.uri'}; }
 2462:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 2463:     if ($urlversion) { return $urlversion; }
 2464:     return '';
 2465: }
 2466: 
 2467: # ----------------------------- Subscribe to a resource, return URL if possible
 2468: 
 2469: sub subscribe {
 2470:     my $fname=shift;
 2471:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 2472:     $fname=~s/[\n\r]//g;
 2473:     my $author=$fname;
 2474:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2475:     my ($udom,$uname)=split(/\//,$author);
 2476:     my $home=homeserver($uname,$udom);
 2477:     if ($home eq 'no_host') {
 2478:         return 'not_found';
 2479:     }
 2480:     my $answer=reply("sub:$fname",$home);
 2481:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 2482: 	$answer.=' by '.$home;
 2483:     }
 2484:     return $answer;
 2485: }
 2486:     
 2487: # -------------------------------------------------------------- Replicate file
 2488: 
 2489: sub repcopy {
 2490:     my $filename=shift;
 2491:     $filename=~s/\/+/\//g;
 2492:     my $londocroot = $perlvar{'lonDocRoot'};
 2493:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 2494:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
 2495:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 2496: 	$filename=~m{^/*(uploaded|editupload)/}) {
 2497: 	return &repcopy_userfile($filename);
 2498:     }
 2499:     $filename=~s/[\n\r]//g;
 2500:     my $transname="$filename.in.transfer";
 2501: # FIXME: this should flock
 2502:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 2503:     my $remoteurl=subscribe($filename);
 2504:     if ($remoteurl =~ /^con_lost by/) {
 2505: 	   &logthis("Subscribe returned $remoteurl: $filename");
 2506:            return 'unavailable';
 2507:     } elsif ($remoteurl eq 'not_found') {
 2508: 	   #&logthis("Subscribe returned not_found: $filename");
 2509: 	   return 'not_found';
 2510:     } elsif ($remoteurl =~ /^rejected by/) {
 2511: 	   &logthis("Subscribe returned $remoteurl: $filename");
 2512:            return 'forbidden';
 2513:     } elsif ($remoteurl eq 'directory') {
 2514:            return 'ok';
 2515:     } else {
 2516:         my $author=$filename;
 2517:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2518:         my ($udom,$uname)=split(/\//,$author);
 2519:         my $home=homeserver($uname,$udom);
 2520:         unless ($home eq $perlvar{'lonHostID'}) {
 2521:            my @parts=split(/\//,$filename);
 2522:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 2523:            if ($path ne "$londocroot/res") {
 2524:                &logthis("Malconfiguration for replication: $filename");
 2525: 	       return 'bad_request';
 2526:            }
 2527:            my $count;
 2528:            for ($count=5;$count<$#parts;$count++) {
 2529:                $path.="/$parts[$count]";
 2530:                if ((-e $path)!=1) {
 2531: 		   mkdir($path,0777);
 2532:                }
 2533:            }
 2534:            my $ua=new LWP::UserAgent;
 2535:            my $request=new HTTP::Request('GET',"$remoteurl");
 2536:            my $response=$ua->request($request,$transname);
 2537:            if ($response->is_error()) {
 2538: 	       unlink($transname);
 2539:                my $message=$response->status_line;
 2540:                &logthis("<font color=\"blue\">WARNING:"
 2541:                        ." LWP get: $message: $filename</font>");
 2542:                return 'unavailable';
 2543:            } else {
 2544: 	       if ($remoteurl!~/\.meta$/) {
 2545:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 2546:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 2547:                   if ($mresponse->is_error()) {
 2548: 		      unlink($filename.'.meta');
 2549:                       &logthis(
 2550:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 2551:                   }
 2552: 	       }
 2553:                rename($transname,$filename);
 2554:                return 'ok';
 2555:            }
 2556:        }
 2557:     }
 2558: }
 2559: 
 2560: # ------------------------------------------------ Get server side include body
 2561: sub ssi_body {
 2562:     my ($filelink,%form)=@_;
 2563:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 2564:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 2565:     }
 2566:     my $output='';
 2567:     my $response;
 2568:     if ($filelink=~/^https?\:/) {
 2569:        ($output,$response)=&externalssi($filelink);
 2570:     } else {
 2571:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 2572:        $filelink .= 'inhibitmenu=yes';
 2573:        ($output,$response)=&ssi($filelink,%form);
 2574:     }
 2575:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 2576:     $output=~s/^.*?\<body[^\>]*\>//si;
 2577:     $output=~s/\<\/body\s*\>.*?$//si;
 2578:     if (wantarray) {
 2579:         return ($output, $response);
 2580:     } else {
 2581:         return $output;
 2582:     }
 2583: }
 2584: 
 2585: # --------------------------------------------------------- Server Side Include
 2586: 
 2587: sub absolute_url {
 2588:     my ($host_name) = @_;
 2589:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 2590:     if ($host_name eq '') {
 2591: 	$host_name = $ENV{'SERVER_NAME'};
 2592:     }
 2593:     return $protocol.$host_name;
 2594: }
 2595: 
 2596: #
 2597: #   Server side include.
 2598: # Parameters:
 2599: #  fn     Possibly encrypted resource name/id.
 2600: #  form   Hash that describes how the rendering should be done
 2601: #         and other things.
 2602: # Returns:
 2603: #   Scalar context: The content of the response.
 2604: #   Array context:  2 element list of the content and the full response object.
 2605: #     
 2606: sub ssi {
 2607: 
 2608:     my ($fn,%form)=@_;
 2609:     my $ua=new LWP::UserAgent;
 2610:     my $request;
 2611: 
 2612:     $form{'no_update_last_known'}=1;
 2613:     &Apache::lonenc::check_encrypt(\$fn);
 2614:     if (%form) {
 2615:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 2616:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
 2617:     } else {
 2618:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 2619:     }
 2620: 
 2621:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 2622:     my $response= $ua->request($request);
 2623:     my $content = $response->content;
 2624: 
 2625: 
 2626:     if (wantarray) {
 2627: 	return ($content, $response);
 2628:     } else {
 2629: 	return $content;
 2630:     }
 2631: }
 2632: 
 2633: sub externalssi {
 2634:     my ($url)=@_;
 2635:     my $ua=new LWP::UserAgent;
 2636:     my $request=new HTTP::Request('GET',$url);
 2637:     my $response=$ua->request($request);
 2638:     if (wantarray) {
 2639:         return ($response->content, $response);
 2640:     } else {
 2641:         return $response->content;
 2642:     }
 2643: }
 2644: 
 2645: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 2646: 
 2647: sub allowuploaded {
 2648:     my ($srcurl,$url)=@_;
 2649:     $url=&clutter(&declutter($url));
 2650:     my $dir=$url;
 2651:     $dir=~s/\/[^\/]+$//;
 2652:     my %httpref=();
 2653:     my $httpurl=&hreflocation('',$url);
 2654:     $httpref{'httpref.'.$httpurl}=$srcurl;
 2655:     &Apache::lonnet::appenv(\%httpref);
 2656: }
 2657: 
 2658: #
 2659: # Determine if the current user should be able to edit a particular resource,
 2660: # when viewing in course context.
 2661: # (a) When viewing resource used to determine if "Edit" item is included in 
 2662: #     Functions.
 2663: # (b) When displaying folder contents in course editor, used to determine if
 2664: #     "Edit" link will be displayed alongside resource.
 2665: #
 2666: #  input: six args -- filename (decluttered), course number, course domain,
 2667: #                   url, symb (if registered) and group (if this is a group
 2668: #                   item -- e.g., bulletin board, group page etc.).
 2669: #  output: array of five scalars -- 
 2670: #          $cfile -- url for file editing if editable on current server
 2671: #          $home -- homeserver of resource (i.e., for author if published,
 2672: #                                           or course if uploaded.).
 2673: #          $switchserver --  1 if server switch will be needed.
 2674: #          $forceedit -- 1 if icon/link should be to go to edit mode 
 2675: #          $forceview -- 1 if icon/link should be to go to view mode
 2676: #
 2677: 
 2678: sub can_edit_resource {
 2679:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
 2680:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
 2681: #
 2682: # For aboutme pages user can only edit his/her own.
 2683: #
 2684:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
 2685:         my ($sdom,$sname) = ($1,$2);
 2686:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
 2687:             $home = $env{'user.home'};
 2688:             $cfile = $resurl;
 2689:             if ($env{'form.forceedit'}) {
 2690:                 $forceview = 1;
 2691:             } else {
 2692:                 $forceedit = 1;
 2693:             }
 2694:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
 2695:         } else {
 2696:             return;
 2697:         }
 2698:     }
 2699: 
 2700:     if ($env{'request.course.id'}) {
 2701:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
 2702:         if ($group ne '') {
 2703: # if this is a group homepage or group bulletin board, check group privs
 2704:             my $allowed = 0;
 2705:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
 2706:                 if ((&allowed('mdg',$env{'request.course.id'}.
 2707:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 2708:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 2709:                     $allowed = 1;
 2710:                 }
 2711:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
 2712:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 2713:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 2714:                     $allowed = 1;
 2715:                 }
 2716:             }
 2717:             if ($allowed) {
 2718:                 $home=&homeserver($cnum,$cdom);
 2719:                 if ($env{'form.forceedit'}) {
 2720:                     $forceview = 1;
 2721:                 } else {
 2722:                     $forceedit = 1;
 2723:                 }
 2724:                 $cfile = $resurl;
 2725:             } else {
 2726:                 return;
 2727:             }
 2728:         } else {
 2729:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
 2730:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
 2731:                     return;
 2732:                 }
 2733:             } elsif (!$crsedit) {
 2734: #
 2735: # No edit allowed where CC has switched to student role.
 2736: #
 2737:                 return;
 2738:             }
 2739:         }
 2740:     }
 2741: 
 2742:     if ($file ne '') {
 2743:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
 2744:             if (&is_course_upload($file,$cnum,$cdom)) {
 2745:                 $uploaded = 1;
 2746:                 $incourse = 1;
 2747:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
 2748:                     $cfile = &hreflocation('',$file);
 2749:                     if ($env{'form.forceedit'}) {
 2750:                         $forceview = 1;
 2751:                     } else {
 2752:                         $forceedit = 1;
 2753:                     }
 2754:                 }
 2755:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
 2756:                 $incourse = 1;
 2757:                 if ($env{'form.forceedit'}) {
 2758:                     $forceview = 1;
 2759:                 } else {
 2760:                     $forceedit = 1;
 2761:                 }
 2762:                 $cfile = $resurl;
 2763:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
 2764:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
 2765:                     $incourse = 1;
 2766:                     if ($env{'form.forceedit'}) {
 2767:                         $forceview = 1;
 2768:                     } else {
 2769:                         $forceedit = 1;
 2770:                     }
 2771:                     $cfile = $resurl;
 2772:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
 2773:                     $incourse = 1;
 2774:                     $cfile = $resurl.'/smpedit';
 2775:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
 2776:                     $incourse = 1;
 2777:                     if ($env{'form.forceedit'}) {
 2778:                         $forceview = 1;
 2779:                     } else {
 2780:                         $forceedit = 1;
 2781:                     }
 2782:                     $cfile = $resurl;
 2783:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 2784:                     $incourse = 1;
 2785:                     if ($env{'form.forceedit'}) {
 2786:                         $forceview = 1;
 2787:                     } else {
 2788:                         $forceedit = 1;
 2789:                     }
 2790:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 2791:                 }
 2792:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
 2793:                 my $template = '/res/lib/templates/simpleproblem.problem';
 2794:                 if (&is_on_map($template)) { 
 2795:                     $incourse = 1;
 2796:                     $forceview = 1;
 2797:                     $cfile = $template;
 2798:                 }
 2799:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 2800:                     $incourse = 1;
 2801:                     if ($env{'form.forceedit'}) {
 2802:                         $forceview = 1;
 2803:                     } else {
 2804:                         $forceedit = 1;
 2805:                     }
 2806:                     $cfile = $resurl;
 2807:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
 2808:                 $incourse = 1;
 2809:                 $forceview = 1;
 2810:                 if ($symb) {
 2811:                     my ($map,$id,$res)=&decode_symb($symb);
 2812:                     $env{'request.symb'} = $symb;
 2813:                     $cfile = &clutter($res);
 2814:                 } else {
 2815:                     $cfile = $env{'form.suppurl'};
 2816:                     $cfile =~ s{^http://}{};
 2817:                     $cfile = '/adm/wrapper/ext/'.$cfile;
 2818:                 }
 2819:             }
 2820:         }
 2821:         if ($uploaded || $incourse) {
 2822:             $home=&homeserver($cnum,$cdom);
 2823:         } elsif ($file !~ m{/$}) {
 2824:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
 2825:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
 2826:             # Check that the user has permission to edit this resource
 2827:             my $setpriv = 1;
 2828:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
 2829:             if (defined($cfudom)) {
 2830:                 $home=&homeserver($cfuname,$cfudom);
 2831:                 $cfile=$file;
 2832:             }
 2833:         }
 2834:         if (($cfile ne '') && (!$incourse || $uploaded) && 
 2835:             (($home ne '') && ($home ne 'no_host'))) {
 2836:             my @ids=&current_machine_ids();
 2837:             unless (grep(/^\Q$home\E$/,@ids)) {
 2838:                 $switchserver=1;
 2839:             }
 2840:         }
 2841:     }
 2842:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
 2843: }
 2844: 
 2845: sub is_course_upload {
 2846:     my ($file,$cnum,$cdom) = @_;
 2847:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
 2848:     $uploadpath =~ s{^\/}{};
 2849:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
 2850:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
 2851:         return 1;
 2852:     }
 2853:     return;
 2854: }
 2855: 
 2856: sub in_course {
 2857:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
 2858:     if ($hideprivileged) {
 2859:         my $skipuser;
 2860:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
 2861:         my @possdoms = ($cdom);  
 2862:         if ($coursehash{'checkforpriv'}) { 
 2863:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
 2864:         }
 2865:         if (&privileged($uname,$udom,\@possdoms)) {
 2866:             $skipuser = 1;
 2867:             if ($coursehash{'nothideprivileged'}) {
 2868:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2869:                     my $user;
 2870:                     if ($item =~ /:/) {
 2871:                         $user = $item;
 2872:                     } else {
 2873:                         $user = join(':',split(/[\@]/,$item));
 2874:                     }
 2875:                     if ($user eq $uname.':'.$udom) {
 2876:                         undef($skipuser);
 2877:                         last;
 2878:                     }
 2879:                 }
 2880:             }
 2881:             if ($skipuser) {
 2882:                 return 0;
 2883:             }
 2884:         }
 2885:     }
 2886:     $type ||= 'any';
 2887:     if (!defined($cdom) || !defined($cnum)) {
 2888:         my $cid  = $env{'request.course.id'};
 2889:         $cdom = $env{'course.'.$cid.'.domain'};
 2890:         $cnum = $env{'course.'.$cid.'.num'};
 2891:     }
 2892:     my $typesref;
 2893:     if (($type eq 'any') || ($type eq 'all')) {
 2894:         $typesref = ['active','previous','future'];
 2895:     } elsif ($type eq 'previous' || $type eq 'future') {
 2896:         $typesref = [$type];
 2897:     }
 2898:     my %roles = &get_my_roles($uname,$udom,'userroles',
 2899:                               $typesref,undef,[$cdom]);
 2900:     my ($tmp) = keys(%roles);
 2901:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
 2902:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
 2903:     if (@course_roles > 0) {
 2904:         return 1;
 2905:     }
 2906:     return 0;
 2907: }
 2908: 
 2909: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 2910: # input: action, courseID, current domain, intended
 2911: #        path to file, source of file, instruction to parse file for objects,
 2912: #        ref to hash for embedded objects,
 2913: #        ref to hash for codebase of java objects.
 2914: #        reference to scalar to accommodate mime type determined
 2915: #          from File::MMagic if $parser = parse.
 2916: #
 2917: # output: url to file (if action was uploaddoc), 
 2918: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 2919: #
 2920: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 2921: # course.
 2922: #
 2923: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2924: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 2925: #          course's home server.
 2926: #
 2927: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 2928: #          be copied from $source (current location) to 
 2929: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2930: #         and will then be copied to
 2931: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 2932: #         course's home server.
 2933: #
 2934: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2935: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 2936: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2937: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 2938: #         in course's home server.
 2939: #
 2940: 
 2941: sub process_coursefile {
 2942:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 2943:         $mimetype)=@_;
 2944:     my $fetchresult;
 2945:     my $home=&homeserver($docuname,$docudom);
 2946:     if ($action eq 'propagate') {
 2947:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2948: 			     $home);
 2949:     } else {
 2950:         my $fpath = '';
 2951:         my $fname = $file;
 2952:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 2953:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 2954:         my $filepath = &build_filepath($fpath);
 2955:         if ($action eq 'copy') {
 2956:             if ($source eq '') {
 2957:                 $fetchresult = 'no source file';
 2958:                 return $fetchresult;
 2959:             } else {
 2960:                 my $destination = $filepath.'/'.$fname;
 2961:                 rename($source,$destination);
 2962:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2963:                                  $home);
 2964:             }
 2965:         } elsif ($action eq 'uploaddoc') {
 2966:             open(my $fh,'>'.$filepath.'/'.$fname);
 2967:             print $fh $env{'form.'.$source};
 2968:             close($fh);
 2969:             if ($parser eq 'parse') {
 2970:                 my $mm = new File::MMagic;
 2971:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 2972:                 if ($type eq 'text/html') {
 2973:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 2974:                     unless ($parse_result eq 'ok') {
 2975:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 2976:                     }
 2977:                 }
 2978:                 if (ref($mimetype)) {
 2979:                     $$mimetype = $type;
 2980:                 } 
 2981:             }
 2982:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2983:                                  $home);
 2984:             if ($fetchresult eq 'ok') {
 2985:                 return '/uploaded/'.$fpath.'/'.$fname;
 2986:             } else {
 2987:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2988:                         ' to host '.$home.': '.$fetchresult);
 2989:                 return '/adm/notfound.html';
 2990:             }
 2991:         }
 2992:     }
 2993:     unless ( $fetchresult eq 'ok') {
 2994:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2995:              ' to host '.$home.': '.$fetchresult);
 2996:     }
 2997:     return $fetchresult;
 2998: }
 2999: 
 3000: sub build_filepath {
 3001:     my ($fpath) = @_;
 3002:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 3003:     unless ($fpath eq '') {
 3004:         my @parts=split('/',$fpath);
 3005:         foreach my $part (@parts) {
 3006:             $filepath.= '/'.$part;
 3007:             if ((-e $filepath)!=1) {
 3008:                 mkdir($filepath,0777);
 3009:             }
 3010:         }
 3011:     }
 3012:     return $filepath;
 3013: }
 3014: 
 3015: sub store_edited_file {
 3016:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 3017:     my $file = $primary_url;
 3018:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 3019:     my $fpath = '';
 3020:     my $fname = $file;
 3021:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3022:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3023:     my $filepath = &build_filepath($fpath);
 3024:     open(my $fh,'>'.$filepath.'/'.$fname);
 3025:     print $fh $content;
 3026:     close($fh);
 3027:     my $home=&homeserver($docuname,$docudom);
 3028:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3029: 			  $home);
 3030:     if ($$fetchresult eq 'ok') {
 3031:         return '/uploaded/'.$fpath.'/'.$fname;
 3032:     } else {
 3033:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3034: 		 ' to host '.$home.': '.$$fetchresult);
 3035:         return '/adm/notfound.html';
 3036:     }
 3037: }
 3038: 
 3039: sub clean_filename {
 3040:     my ($fname,$args)=@_;
 3041: # Replace Windows backslashes by forward slashes
 3042:     $fname=~s/\\/\//g;
 3043:     if (!$args->{'keep_path'}) {
 3044:         # Get rid of everything but the actual filename
 3045: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 3046:     }
 3047: # Replace spaces by underscores
 3048:     $fname=~s/\s+/\_/g;
 3049: # Replace all other weird characters by nothing
 3050:     $fname=~s{[^/\w\.\-]}{}g;
 3051: # Replace all .\d. sequences with _\d. so they no longer look like version
 3052: # numbers
 3053:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 3054:     return $fname;
 3055: }
 3056: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 3057: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 3058: # image with the same aspect ratio as the original, but with dimensions which do 
 3059: # not exceed $resizewidth and $resizeheight.
 3060:  
 3061: sub resizeImage {
 3062:     my ($img_path,$resizewidth,$resizeheight) = @_;
 3063:     my $ima = Image::Magick->new;
 3064:     my $resized;
 3065:     if (-e $img_path) {
 3066:         $ima->Read($img_path);
 3067:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 3068:             my $width = $ima->Get('width');
 3069:             my $height = $ima->Get('height');
 3070:             if ($width > $resizewidth) {
 3071: 	        my $factor = $width/$resizewidth;
 3072:                 my $newheight = $height/$factor;
 3073:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 3074:                 $resized = 1;
 3075:             }
 3076:         }
 3077:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 3078:             my $width = $ima->Get('width');
 3079:             my $height = $ima->Get('height');
 3080:             if ($height > $resizeheight) {
 3081:                 my $factor = $height/$resizeheight;
 3082:                 my $newwidth = $width/$factor;
 3083:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 3084:                 $resized = 1;
 3085:             }
 3086:         }
 3087:         if ($resized) {
 3088:             $ima->Write($img_path);
 3089:         }
 3090:     }
 3091:     return;
 3092: }
 3093: 
 3094: # --------------- Take an uploaded file and put it into the userfiles directory
 3095: # input: $formname - the contents of the file are in $env{"form.$formname"}
 3096: #                    the desired filename is in $env{"form.$formname.filename"}
 3097: #        $context - possible values: coursedoc, existingfile, overwrite, 
 3098: #                                    canceloverwrite, or ''. 
 3099: #                   if 'coursedoc': upload to the current course
 3100: #                   if 'existingfile': write file to tmp/overwrites directory 
 3101: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 3102: #                   $context is passed as argument to &finishuserfileupload
 3103: #        $subdir - directory in userfile to store the file into
 3104: #        $parser - instruction to parse file for objects ($parser = parse)    
 3105: #        $allfiles - reference to hash for embedded objects
 3106: #        $codebase - reference to hash for codebase of java objects
 3107: #        $desuname - username for permanent storage of uploaded file
 3108: #        $dsetudom - domain for permanaent storage of uploaded file
 3109: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 3110: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 3111: #        $resizewidth - width (pixels) to which to resize uploaded image
 3112: #        $resizeheight - height (pixels) to which to resize uploaded image
 3113: #        $mimetype - reference to scalar to accommodate mime type determined
 3114: #                    from File::MMagic.
 3115: # 
 3116: # output: url of file in userspace, or error: <message> 
 3117: #             or /adm/notfound.html if failure to upload occurse
 3118: 
 3119: sub userfileupload {
 3120:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 3121:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 3122:     if (!defined($subdir)) { $subdir='unknown'; }
 3123:     my $fname=$env{'form.'.$formname.'.filename'};
 3124:     $fname=&clean_filename($fname);
 3125:     # See if there is anything left
 3126:     unless ($fname) { return 'error: no uploaded file'; }
 3127:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 3128:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 3129:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 3130:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3131:         my $now = time;
 3132:         my $filepath;
 3133:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 3134:              $filepath = 'tmp/helprequests/'.$now;
 3135:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 3136:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 3137:                          '_'.$env{'user.domain'}.'/pending';
 3138:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3139:             my ($docuname,$docudom);
 3140:             if ($destudom) {
 3141:                 $docudom = $destudom;
 3142:             } else {
 3143:                 $docudom = $env{'user.domain'};
 3144:             }
 3145:             if ($destuname) {
 3146:                 $docuname = $destuname;
 3147:             } else {
 3148:                 $docuname = $env{'user.name'};
 3149:             }
 3150:             if (exists($env{'form.group'})) {
 3151:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3152:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3153:             }
 3154:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 3155:             if ($context eq 'canceloverwrite') {
 3156:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 3157:                 if (-e  $tempfile) {
 3158:                     my @info = stat($tempfile);
 3159:                     if ($info[9] eq $env{'form.timestamp'}) {
 3160:                         unlink($tempfile);
 3161:                     }
 3162:                 }
 3163:                 return;
 3164:             }
 3165:         }
 3166:         # Create the directory if not present
 3167:         my @parts=split(/\//,$filepath);
 3168:         my $fullpath = $perlvar{'lonDaemons'};
 3169:         for (my $i=0;$i<@parts;$i++) {
 3170:             $fullpath .= '/'.$parts[$i];
 3171:             if ((-e $fullpath)!=1) {
 3172:                 mkdir($fullpath,0777);
 3173:             }
 3174:         }
 3175:         open(my $fh,'>'.$fullpath.'/'.$fname);
 3176:         print $fh $env{'form.'.$formname};
 3177:         close($fh);
 3178:         if ($context eq 'existingfile') {
 3179:             my @info = stat($fullpath.'/'.$fname);
 3180:             return ($fullpath.'/'.$fname,$info[9]);
 3181:         } else {
 3182:             return $fullpath.'/'.$fname;
 3183:         }
 3184:     }
 3185:     if ($subdir eq 'scantron') {
 3186:         $fname = 'scantron_orig_'.$fname;
 3187:     } else {
 3188:         $fname="$subdir/$fname";
 3189:     }
 3190:     if ($context eq 'coursedoc') {
 3191: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3192: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3193:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 3194:             return &finishuserfileupload($docuname,$docudom,
 3195: 					 $formname,$fname,$parser,$allfiles,
 3196: 					 $codebase,$thumbwidth,$thumbheight,
 3197:                                          $resizewidth,$resizeheight,$context,$mimetype);
 3198:         } else {
 3199:             if ($env{'form.folder'}) {
 3200:                 $fname=$env{'form.folder'}.'/'.$fname;
 3201:             }
 3202:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 3203: 				       $fname,$formname,$parser,
 3204: 				       $allfiles,$codebase,$mimetype);
 3205:         }
 3206:     } elsif (defined($destuname)) {
 3207:         my $docuname=$destuname;
 3208:         my $docudom=$destudom;
 3209: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3210: 				     $parser,$allfiles,$codebase,
 3211:                                      $thumbwidth,$thumbheight,
 3212:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3213:     } else {
 3214:         my $docuname=$env{'user.name'};
 3215:         my $docudom=$env{'user.domain'};
 3216:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
 3217:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3218:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3219:         }
 3220: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3221: 				     $parser,$allfiles,$codebase,
 3222:                                      $thumbwidth,$thumbheight,
 3223:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3224:     }
 3225: }
 3226: 
 3227: sub finishuserfileupload {
 3228:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 3229:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 3230:     my $path=$docudom.'/'.$docuname.'/';
 3231:     my $filepath=$perlvar{'lonDocRoot'};
 3232:   
 3233:     my ($fnamepath,$file,$fetchthumb);
 3234:     $file=$fname;
 3235:     if ($fname=~m|/|) {
 3236:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 3237: 	$path.=$fnamepath.'/';
 3238:     }
 3239:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 3240:     my $count;
 3241:     for ($count=4;$count<=$#parts;$count++) {
 3242:         $filepath.="/$parts[$count]";
 3243:         if ((-e $filepath)!=1) {
 3244: 	    mkdir($filepath,0777);
 3245:         }
 3246:     }
 3247: 
 3248: # Save the file
 3249:     {
 3250: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 3251: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 3252: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 3253: 	    return '/adm/notfound.html';
 3254: 	}
 3255:         if ($context eq 'overwrite') {
 3256:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 3257:             my $target = $filepath.'/'.$file;
 3258:             if (-e $source) {
 3259:                 my @info = stat($source);
 3260:                 if ($info[9] eq $env{'form.timestamp'}) {   
 3261:                     unless (&File::Copy::move($source,$target)) {
 3262:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 3263:                         return "Moving from $source failed";
 3264:                     }
 3265:                 } else {
 3266:                     return "Temporary file: $source had unexpected date/time for last modification";
 3267:                 }
 3268:             } else {
 3269:                 return "Temporary file: $source missing";
 3270:             }
 3271:         } elsif (!print FH ($env{'form.'.$formname})) {
 3272: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 3273: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 3274: 	    return '/adm/notfound.html';
 3275: 	}
 3276: 	close(FH);
 3277:         if ($resizewidth && $resizeheight) {
 3278:             my $mm = new File::MMagic;
 3279:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 3280:             if ($mime_type =~ m{^image/}) {
 3281: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 3282:             }  
 3283: 	}
 3284:     }
 3285:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 3286:         if (ref($mimetype)) {
 3287:             if ($$mimetype eq '') {
 3288:                 my $mm = new File::MMagic;
 3289:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 3290:                 $$mimetype = $type;
 3291:             }
 3292:         }
 3293:     }
 3294:     if ($parser eq 'parse') {
 3295:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 3296:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 3297:                                                        $allfiles,$codebase);
 3298:             unless ($parse_result eq 'ok') {
 3299:                 &logthis('Failed to parse '.$filepath.$file.
 3300: 	   	         ' for embedded media: '.$parse_result); 
 3301:             }
 3302:         }
 3303:     }
 3304:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 3305:         my $input = $filepath.'/'.$file;
 3306:         my $output = $filepath.'/'.'tn-'.$file;
 3307:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 3308:         system("convert -sample $thumbsize $input $output");
 3309:         if (-e $filepath.'/'.'tn-'.$file) {
 3310:             $fetchthumb  = 1; 
 3311:         }
 3312:     }
 3313:  
 3314: # Notify homeserver to grep it
 3315: #
 3316:     my $docuhome=&homeserver($docuname,$docudom);	
 3317:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 3318:     if ($fetchresult eq 'ok') {
 3319:         if ($fetchthumb) {
 3320:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 3321:             if ($thumbresult ne 'ok') {
 3322:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 3323:                          $docuhome.': '.$thumbresult);
 3324:             }
 3325:         }
 3326: #
 3327: # Return the URL to it
 3328:         return '/uploaded/'.$path.$file;
 3329:     } else {
 3330:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 3331: 		 ': '.$fetchresult);
 3332:         return '/adm/notfound.html';
 3333:     }
 3334: }
 3335: 
 3336: sub extract_embedded_items {
 3337:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 3338:     my @state = ();
 3339:     my (%lastids,%related,%shockwave,%flashvars);
 3340:     my %javafiles = (
 3341:                       codebase => '',
 3342:                       code => '',
 3343:                       archive => ''
 3344:                     );
 3345:     my %mediafiles = (
 3346:                       src => '',
 3347:                       movie => '',
 3348:                      );
 3349:     my $p;
 3350:     if ($content) {
 3351:         $p = HTML::LCParser->new($content);
 3352:     } else {
 3353:         $p = HTML::LCParser->new($fullpath);
 3354:     }
 3355:     while (my $t=$p->get_token()) {
 3356: 	if ($t->[0] eq 'S') {
 3357: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 3358: 	    push(@state, $tagname);
 3359:             if (lc($tagname) eq 'allow') {
 3360:                 &add_filetype($allfiles,$attr->{'src'},'src');
 3361:             }
 3362: 	    if (lc($tagname) eq 'img') {
 3363: 		&add_filetype($allfiles,$attr->{'src'},'src');
 3364: 	    }
 3365: 	    if (lc($tagname) eq 'a') {
 3366:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
 3367:                     &add_filetype($allfiles,$attr->{'href'},'href');
 3368:                 }
 3369: 	    }
 3370:             if (lc($tagname) eq 'script') {
 3371:                 my $src;
 3372:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 3373:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 3374:                 } else {
 3375:                     if ($attr->{'src'} ne '') {
 3376:                         $src = $attr->{'src'};
 3377:                         &add_filetype($allfiles,$src,'src');
 3378:                     }
 3379:                 }
 3380:                 my $text = $p->get_trimmed_text();
 3381:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 3382:                     my @swfargs = split(/,/,$1);
 3383:                     foreach my $item (@swfargs) {
 3384:                         $item =~ s/["']//g;
 3385:                         $item =~ s/^\s+//;
 3386:                         $item =~ s/\s+$//;
 3387:                     }
 3388:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 3389:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 3390:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 3391:                         } else {
 3392:                             $related{$swfargs[0]} = [$swfargs[2]];
 3393:                         }
 3394:                     }
 3395:                 }
 3396:             }
 3397:             if (lc($tagname) eq 'link') {
 3398:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 3399:                     &add_filetype($allfiles,$attr->{'href'},'href');
 3400:                 }
 3401:             }
 3402: 	    if (lc($tagname) eq 'object' ||
 3403: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 3404: 		foreach my $item (keys(%javafiles)) {
 3405: 		    $javafiles{$item} = '';
 3406: 		}
 3407:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 3408:                     $lastids{lc($tagname)} = $attr->{'id'};
 3409:                 }
 3410: 	    }
 3411: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 3412: 		my $name = lc($attr->{'name'});
 3413: 		foreach my $item (keys(%javafiles)) {
 3414: 		    if ($name eq $item) {
 3415: 			$javafiles{$item} = $attr->{'value'};
 3416: 			last;
 3417: 		    }
 3418: 		}
 3419:                 my $pathfrom;
 3420: 		foreach my $item (keys(%mediafiles)) {
 3421: 		    if ($name eq $item) {
 3422:                         $pathfrom = $attr->{'value'};
 3423:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 3424: 			&add_filetype($allfiles,$pathfrom,$name);
 3425: 			last;
 3426: 		    }
 3427: 		}
 3428:                 if ($name eq 'flashvars') {
 3429:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 3430:                 }
 3431:                 if ($pathfrom ne '') {
 3432:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 3433:                                          $pathfrom);
 3434:                 }
 3435: 	    }
 3436: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 3437: 		foreach my $item (keys(%javafiles)) {
 3438: 		    if ($attr->{$item}) {
 3439: 			$javafiles{$item} = $attr->{$item};
 3440: 			last;
 3441: 		    }
 3442: 		}
 3443: 		foreach my $item (keys(%mediafiles)) {
 3444: 		    if ($attr->{$item}) {
 3445: 			&add_filetype($allfiles,$attr->{$item},$item);
 3446: 			last;
 3447: 		    }
 3448: 		}
 3449:                 if (lc($tagname) eq 'embed') {
 3450:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 3451:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 3452:                                              $attr->{'src'});
 3453:                     }
 3454:                 }
 3455: 	    }
 3456:             if ($t->[4] =~ m{/>$}) {
 3457:                 pop(@state);  
 3458:             }
 3459: 	} elsif ($t->[0] eq 'E') {
 3460: 	    my ($tagname) = ($t->[1]);
 3461: 	    if ($javafiles{'codebase'} ne '') {
 3462: 		$javafiles{'codebase'} .= '/';
 3463: 	    }  
 3464: 	    if (lc($tagname) eq 'applet' ||
 3465: 		lc($tagname) eq 'object' ||
 3466: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 3467: 		) {
 3468: 		foreach my $item (keys(%javafiles)) {
 3469: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 3470: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 3471: 			&add_filetype($allfiles,$file,$item);
 3472: 		    }
 3473: 		}
 3474: 	    } 
 3475: 	    pop @state;
 3476: 	}
 3477:     }
 3478:     foreach my $id (sort(keys(%flashvars))) {
 3479:         if ($shockwave{$id} ne '') {
 3480:             my @pairs = split(/\&/,$flashvars{$id});
 3481:             foreach my $pair (@pairs) {
 3482:                 my ($key,$value) = split(/\=/,$pair);
 3483:                 if ($key eq 'thumb') {
 3484:                     &add_filetype($allfiles,$value,$key);
 3485:                 } elsif ($key eq 'content') {
 3486:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 3487:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 3488:                     if ($ext ne '') {
 3489:                         &add_filetype($allfiles,$path.$value,$ext);
 3490:                     }
 3491:                 }
 3492:             }
 3493:         }
 3494:     }
 3495:     return 'ok';
 3496: }
 3497: 
 3498: sub add_filetype {
 3499:     my ($allfiles,$file,$type)=@_;
 3500:     if (exists($allfiles->{$file})) {
 3501: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 3502: 	    push(@{$allfiles->{$file}}, &escape($type));
 3503: 	}
 3504:     } else {
 3505: 	@{$allfiles->{$file}} = (&escape($type));
 3506:     }
 3507: }
 3508: 
 3509: sub embedded_dependency {
 3510:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 3511:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 3512:         if (($identifier ne '') &&
 3513:             (ref($related->{$identifier}) eq 'ARRAY') &&
 3514:             ($pathfrom ne '')) {
 3515:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 3516:             foreach my $dep (@{$related->{$identifier}}) {
 3517:                 &add_filetype($allfiles,$path.$dep,'object');
 3518:             }
 3519:         }
 3520:     }
 3521:     return;
 3522: }
 3523: 
 3524: sub removeuploadedurl {
 3525:     my ($url)=@_;	
 3526:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 3527:     return &removeuserfile($uname,$udom,$fname);
 3528: }
 3529: 
 3530: sub removeuserfile {
 3531:     my ($docuname,$docudom,$fname)=@_;
 3532:     my $home=&homeserver($docuname,$docudom);    
 3533:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 3534:     if ($result eq 'ok') {	
 3535:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 3536:             my $metafile = $fname.'.meta';
 3537:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 3538: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 3539:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 3540:             my $sqlresult = 
 3541:                 &update_portfolio_table($docuname,$docudom,$file,
 3542:                                         'portfolio_metadata',$group,
 3543:                                         'delete');
 3544:         }
 3545:     }
 3546:     return $result;
 3547: }
 3548: 
 3549: sub mkdiruserfile {
 3550:     my ($docuname,$docudom,$dir)=@_;
 3551:     my $home=&homeserver($docuname,$docudom);
 3552:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 3553: }
 3554: 
 3555: sub renameuserfile {
 3556:     my ($docuname,$docudom,$old,$new)=@_;
 3557:     my $home=&homeserver($docuname,$docudom);
 3558:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 3559:                         &escape("$old").':'.&escape("$new"),$home);
 3560:     if ($result eq 'ok') {
 3561:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 3562:             my $oldmeta = $old.'.meta';
 3563:             my $newmeta = $new.'.meta';
 3564:             my $metaresult = 
 3565:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 3566: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 3567:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 3568:             my $sqlresult = 
 3569:                 &update_portfolio_table($docuname,$docudom,$file,
 3570:                                         'portfolio_metadata',$group,
 3571:                                         'delete');
 3572:         }
 3573:     }
 3574:     return $result;
 3575: }
 3576: 
 3577: # ------------------------------------------------------------------------- Log
 3578: 
 3579: sub log {
 3580:     my ($dom,$nam,$hom,$what)=@_;
 3581:     return critical("log:$dom:$nam:$what",$hom);
 3582: }
 3583: 
 3584: # ------------------------------------------------------------------ Course Log
 3585: #
 3586: # This routine flushes several buffers of non-mission-critical nature
 3587: #
 3588: 
 3589: sub flushcourselogs {
 3590:     &logthis('Flushing log buffers');
 3591: #
 3592: # course logs
 3593: # This is a log of all transactions in a course, which can be used
 3594: # for data mining purposes
 3595: #
 3596: # It also collects the courseid database, which lists last transaction
 3597: # times and course titles for all courseids
 3598: #
 3599:     my %courseidbuffer=();
 3600:     foreach my $crsid (keys(%courselogs)) {
 3601:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 3602: 		          &escape($courselogs{$crsid}),
 3603: 		          $coursehombuf{$crsid}) eq 'ok') {
 3604: 	    delete $courselogs{$crsid};
 3605:         } else {
 3606:             &logthis('Failed to flush log buffer for '.$crsid);
 3607:             if (length($courselogs{$crsid})>40000) {
 3608:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 3609:                         " exceeded maximum size, deleting.</font>");
 3610:                delete $courselogs{$crsid};
 3611:             }
 3612:         }
 3613:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 3614:             'description' => $coursedescrbuf{$crsid},
 3615:             'inst_code'    => $courseinstcodebuf{$crsid},
 3616:             'type'        => $coursetypebuf{$crsid},
 3617:             'owner'       => $courseownerbuf{$crsid},
 3618:         };
 3619:     }
 3620: #
 3621: # Write course id database (reverse lookup) to homeserver of courses 
 3622: # Is used in pickcourse
 3623: #
 3624:     foreach my $crs_home (keys(%courseidbuffer)) {
 3625:         my $response = &courseidput(&host_domain($crs_home),
 3626:                                     $courseidbuffer{$crs_home},
 3627:                                     $crs_home,'timeonly');
 3628:     }
 3629: #
 3630: # File accesses
 3631: # Writes to the dynamic metadata of resources to get hit counts, etc.
 3632: #
 3633:     foreach my $entry (keys(%accesshash)) {
 3634:         if ($entry =~ /___count$/) {
 3635:             my ($dom,$name);
 3636:             ($dom,$name,undef)=
 3637: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 3638:             if (! defined($dom) || $dom eq '' || 
 3639:                 ! defined($name) || $name eq '') {
 3640:                 my $cid = $env{'request.course.id'};
 3641:                 $dom  = $env{'request.'.$cid.'.domain'};
 3642:                 $name = $env{'request.'.$cid.'.num'};
 3643:             }
 3644:             my $value = $accesshash{$entry};
 3645:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 3646:             my %temphash=($url => $value);
 3647:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 3648:             if ($result eq 'ok') {
 3649:                 delete $accesshash{$entry};
 3650:             }
 3651:         } else {
 3652:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 3653:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 3654:             my %temphash=($entry => $accesshash{$entry});
 3655:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 3656:                 delete $accesshash{$entry};
 3657:             }
 3658:         }
 3659:     }
 3660: #
 3661: # Roles
 3662: # Reverse lookup of user roles for course faculty/staff and co-authorship
 3663: #
 3664:     foreach my $entry (keys(%userrolehash)) {
 3665:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 3666: 	    split(/\:/,$entry);
 3667:         if (&Apache::lonnet::put('nohist_userroles',
 3668:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 3669:                 $rudom,$runame) eq 'ok') {
 3670: 	    delete $userrolehash{$entry};
 3671:         }
 3672:     }
 3673: #
 3674: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 3675: #
 3676:     my %domrolebuffer = ();
 3677:     foreach my $entry (keys(%domainrolehash)) {
 3678:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 3679:         if ($domrolebuffer{$rudom}) {
 3680:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 3681:                       '='.&escape($domainrolehash{$entry});
 3682:         } else {
 3683:             $domrolebuffer{$rudom}.=&escape($entry).
 3684:                       '='.&escape($domainrolehash{$entry});
 3685:         }
 3686:         delete $domainrolehash{$entry};
 3687:     }
 3688:     foreach my $dom (keys(%domrolebuffer)) {
 3689: 	my %servers = &get_servers($dom,'library');
 3690: 	foreach my $tryserver (keys(%servers)) {
 3691: 	    unless (&reply('domroleput:'.$dom.':'.
 3692: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 3693: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 3694: 	    }
 3695:         }
 3696:     }
 3697:     $dumpcount++;
 3698: }
 3699: 
 3700: sub courselog {
 3701:     my $what=shift;
 3702:     $what=time.':'.$what;
 3703:     unless ($env{'request.course.id'}) { return ''; }
 3704:     $coursedombuf{$env{'request.course.id'}}=
 3705:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 3706:     $coursenumbuf{$env{'request.course.id'}}=
 3707:        $env{'course.'.$env{'request.course.id'}.'.num'};
 3708:     $coursehombuf{$env{'request.course.id'}}=
 3709:        $env{'course.'.$env{'request.course.id'}.'.home'};
 3710:     $coursedescrbuf{$env{'request.course.id'}}=
 3711:        $env{'course.'.$env{'request.course.id'}.'.description'};
 3712:     $courseinstcodebuf{$env{'request.course.id'}}=
 3713:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 3714:     $courseownerbuf{$env{'request.course.id'}}=
 3715:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 3716:     $coursetypebuf{$env{'request.course.id'}}=
 3717:        $env{'course.'.$env{'request.course.id'}.'.type'};
 3718:     if (defined $courselogs{$env{'request.course.id'}}) {
 3719: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 3720:     } else {
 3721: 	$courselogs{$env{'request.course.id'}}.=$what;
 3722:     }
 3723:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 3724: 	&flushcourselogs();
 3725:     }
 3726: }
 3727: 
 3728: sub courseacclog {
 3729:     my $fnsymb=shift;
 3730:     unless ($env{'request.course.id'}) { return ''; }
 3731:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 3732:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 3733:         $what.=':POST';
 3734:         # FIXME: Probably ought to escape things....
 3735: 	foreach my $key (keys(%env)) {
 3736:             if ($key=~/^form\.(.*)/) {
 3737:                 my $formitem = $1;
 3738:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 3739:                     $what.=':'.$formitem.'='.$env{$key};
 3740:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 3741:                     $what.=':'.$formitem.'='.$env{$key};
 3742:                 }
 3743:             }
 3744:         }
 3745:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 3746:         # FIXME: We should not be depending on a form parameter that someone
 3747:         # editing lonsearchcat.pm might change in the future.
 3748:         if ($env{'form.phase'} eq 'course_search') {
 3749:             $what.= ':POST';
 3750:             # FIXME: Probably ought to escape things....
 3751:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 3752:                                  'crsdiscuss') {
 3753:                 $what.=':'.$element.'='.$env{'form.'.$element};
 3754:             }
 3755:         }
 3756:     }
 3757:     &courselog($what);
 3758: }
 3759: 
 3760: sub countacc {
 3761:     my $url=&declutter(shift);
 3762:     return if (! defined($url) || $url eq '');
 3763:     unless ($env{'request.course.id'}) { return ''; }
 3764: #
 3765: # Mark that this url was used in this course
 3766: #
 3767:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 3768: #
 3769: # Increase the access count for this resource in this child process
 3770: #
 3771:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 3772:     $accesshash{$key}++;
 3773: }
 3774: 
 3775: sub linklog {
 3776:     my ($from,$to)=@_;
 3777:     $from=&declutter($from);
 3778:     $to=&declutter($to);
 3779:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 3780:     $accesshash{$to.'___'.$from.'___goto'}=1;
 3781: }
 3782: 
 3783: sub statslog {
 3784:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 3785:     if ($users<2) { return; }
 3786:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 3787:             'course'       => $env{'request.course.id'},
 3788:             'sections'     => '"all"',
 3789:             'num_students' => $users,
 3790:             'part'         => $part,
 3791:             'symb'         => $symb,
 3792:             'mean_tries'   => $av_attempts,
 3793:             'deg_of_diff'  => $degdiff});
 3794:     foreach my $key (keys(%dynstore)) {
 3795:         $accesshash{$key}=$dynstore{$key};
 3796:     }
 3797: }
 3798:   
 3799: sub userrolelog {
 3800:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 3801:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
 3802:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 3803:        $userrolehash
 3804:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 3805:                     =$tend.':'.$tstart;
 3806:     }
 3807:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
 3808:        $userrolehash
 3809:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 3810:                     =$tend.':'.$tstart;
 3811:     }
 3812:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
 3813:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 3814:        $domainrolehash
 3815:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 3816:                     = $tend.':'.$tstart;
 3817:     }
 3818: }
 3819: 
 3820: sub courserolelog {
 3821:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 3822:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 3823:         my $cdom = $1;
 3824:         my $cnum = $2;
 3825:         my $sec = $3;
 3826:         my $namespace = 'rolelog';
 3827:         my %storehash = (
 3828:                            role    => $trole,
 3829:                            start   => $tstart,
 3830:                            end     => $tend,
 3831:                            selfenroll => $selfenroll,
 3832:                            context    => $context,
 3833:                         );
 3834:         if ($trole eq 'gr') {
 3835:             $namespace = 'groupslog';
 3836:             $storehash{'group'} = $sec;
 3837:         } else {
 3838:             $storehash{'section'} = $sec;
 3839:         }
 3840:         &write_log('course',$namespace,\%storehash,$delflag,$username,
 3841:                    $domain,$cnum,$cdom);
 3842:         if (($trole ne 'st') || ($sec ne '')) {
 3843:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 3844:         }
 3845:     }
 3846:     return;
 3847: }
 3848: 
 3849: sub domainrolelog {
 3850:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 3851:     if ($area =~ m{^/($match_domain)/$}) {
 3852:         my $cdom = $1;
 3853:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
 3854:         my $namespace = 'rolelog';
 3855:         my %storehash = (
 3856:                            role    => $trole,
 3857:                            start   => $tstart,
 3858:                            end     => $tend,
 3859:                            context => $context,
 3860:                         );
 3861:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
 3862:                    $domain,$domconfiguser,$cdom);
 3863:     }
 3864:     return;
 3865: 
 3866: }
 3867: 
 3868: sub coauthorrolelog {
 3869:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 3870:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
 3871:         my $audom = $1;
 3872:         my $auname = $2;
 3873:         my $namespace = 'rolelog';
 3874:         my %storehash = (
 3875:                            role    => $trole,
 3876:                            start   => $tstart,
 3877:                            end     => $tend,
 3878:                            context => $context,
 3879:                         );
 3880:         &write_log('author',$namespace,\%storehash,$delflag,$username,
 3881:                    $domain,$auname,$audom);
 3882:     }
 3883:     return;
 3884: }
 3885: 
 3886: sub get_course_adv_roles {
 3887:     my ($cid,$codes) = @_;
 3888:     $cid=$env{'request.course.id'} unless (defined($cid));
 3889:     my %coursehash=&coursedescription($cid);
 3890:     my $crstype = &Apache::loncommon::course_type($cid);
 3891:     my %nothide=();
 3892:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3893:         if ($user !~ /:/) {
 3894: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 3895:         } else {
 3896:             $nothide{$user}=1;
 3897:         }
 3898:     }
 3899:     my @possdoms = ($coursehash{'domain'});
 3900:     if ($coursehash{'checkforpriv'}) {
 3901:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 3902:     }
 3903:     my %returnhash=();
 3904:     my %dumphash=
 3905:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 3906:     my $now=time;
 3907:     my %privileged;
 3908:     foreach my $entry (keys(%dumphash)) {
 3909: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 3910:         if (($tstart) && ($tstart<0)) { next; }
 3911:         if (($tend) && ($tend<$now)) { next; }
 3912:         if (($tstart) && ($now<$tstart)) { next; }
 3913:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 3914: 	if ($username eq '' || $domain eq '') { next; }
 3915:         if ((&privileged($username,$domain,\@possdoms)) &&
 3916:             (!$nothide{$username.':'.$domain})) { next; }
 3917: 	if ($role eq 'cr') { next; }
 3918:         if ($codes) {
 3919:             if ($section) { $role .= ':'.$section; }
 3920:             if ($returnhash{$role}) {
 3921:                 $returnhash{$role}.=','.$username.':'.$domain;
 3922:             } else {
 3923:                 $returnhash{$role}=$username.':'.$domain;
 3924:             }
 3925:         } else {
 3926:             my $key=&plaintext($role,$crstype);
 3927:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 3928:             if ($returnhash{$key}) {
 3929: 	        $returnhash{$key}.=','.$username.':'.$domain;
 3930:             } else {
 3931:                 $returnhash{$key}=$username.':'.$domain;
 3932:             }
 3933:         }
 3934:     }
 3935:     return %returnhash;
 3936: }
 3937: 
 3938: sub get_my_roles {
 3939:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 3940:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 3941:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 3942:     my (%dumphash,%nothide);
 3943:     if ($context eq 'userroles') {
 3944:         %dumphash = &dump('roles',$udom,$uname);
 3945:     } else {
 3946:         %dumphash = &dump('nohist_userroles',$udom,$uname);
 3947:         if ($hidepriv) {
 3948:             my %coursehash=&coursedescription($udom.'_'.$uname);
 3949:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3950:                 if ($user !~ /:/) {
 3951:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 3952:                 } else {
 3953:                     $nothide{$user} = 1;
 3954:                 }
 3955:             }
 3956:         }
 3957:     }
 3958:     my %returnhash=();
 3959:     my $now=time;
 3960:     my %privileged;
 3961:     foreach my $entry (keys(%dumphash)) {
 3962:         my ($role,$tend,$tstart);
 3963:         if ($context eq 'userroles') {
 3964:             next if ($entry =~ /^rolesdef/);
 3965: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 3966:         } else {
 3967:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 3968:         }
 3969:         if (($tstart) && ($tstart<0)) { next; }
 3970:         my $status = 'active';
 3971:         if (($tend) && ($tend<=$now)) {
 3972:             $status = 'previous';
 3973:         } 
 3974:         if (($tstart) && ($now<$tstart)) {
 3975:             $status = 'future';
 3976:         }
 3977:         if (ref($types) eq 'ARRAY') {
 3978:             if (!grep(/^\Q$status\E$/,@{$types})) {
 3979:                 next;
 3980:             } 
 3981:         } else {
 3982:             if ($status ne 'active') {
 3983:                 next;
 3984:             }
 3985:         }
 3986:         my ($rolecode,$username,$domain,$section,$area);
 3987:         if ($context eq 'userroles') {
 3988:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
 3989:             (undef,$domain,$username,$section) = split(/\//,$area);
 3990:         } else {
 3991:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 3992:         }
 3993:         if (ref($roledoms) eq 'ARRAY') {
 3994:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 3995:                 next;
 3996:             }
 3997:         }
 3998:         if (ref($roles) eq 'ARRAY') {
 3999:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 4000:                 if ($role =~ /^cr\//) {
 4001:                     if (!grep(/^cr$/,@{$roles})) {
 4002:                         next;
 4003:                     }
 4004:                 } elsif ($role =~ /^gr\//) {
 4005:                     if (!grep(/^gr$/,@{$roles})) {
 4006:                         next;
 4007:                     }
 4008:                 } else {
 4009:                     next;
 4010:                 }
 4011:             }
 4012:         }
 4013:         if ($hidepriv) {
 4014:             my @privroles = ('dc','su');
 4015:             if ($context eq 'userroles') {
 4016:                 next if (grep(/^\Q$role\E$/,@privroles));
 4017:             } else {
 4018:                 my $possdoms = [$domain];
 4019:                 if (ref($roledoms) eq 'ARRAY') {
 4020:                    push(@{$possdoms},@{$roledoms}); 
 4021:                 }
 4022:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
 4023:                     if (!$nothide{$username.':'.$domain}) {
 4024:                         next;
 4025:                     }
 4026:                 }
 4027:             }
 4028:         }
 4029:         if ($withsec) {
 4030:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 4031:                 $tstart.':'.$tend;
 4032:         } else {
 4033:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 4034:         }
 4035:     }
 4036:     return %returnhash;
 4037: }
 4038: 
 4039: # ----------------------------------------------------- Frontpage Announcements
 4040: #
 4041: #
 4042: 
 4043: sub postannounce {
 4044:     my ($server,$text)=@_;
 4045:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 4046:     unless ($text=~/\w/) { $text=''; }
 4047:     return &reply('setannounce:'.&escape($text),$server);
 4048: }
 4049: 
 4050: sub getannounce {
 4051: 
 4052:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 4053: 	my $announcement='';
 4054: 	while (my $line = <$fh>) { $announcement .= $line; }
 4055: 	close($fh);
 4056: 	if ($announcement=~/\w/) { 
 4057: 	    return 
 4058:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 4059:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 4060: 	} else {
 4061: 	    return '';
 4062: 	}
 4063:     } else {
 4064: 	return '';
 4065:     }
 4066: }
 4067: 
 4068: # ---------------------------------------------------------- Course ID routines
 4069: # Deal with domain's nohist_courseid.db files
 4070: #
 4071: 
 4072: sub courseidput {
 4073:     my ($domain,$storehash,$coursehome,$caller) = @_;
 4074:     return unless (ref($storehash) eq 'HASH');
 4075:     my $outcome;
 4076:     if ($caller eq 'timeonly') {
 4077:         my $cids = '';
 4078:         foreach my $item (keys(%$storehash)) {
 4079:             $cids.=&escape($item).'&';
 4080:         }
 4081:         $cids=~s/\&$//;
 4082:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 4083:                           $coursehome);       
 4084:     } else {
 4085:         my $items = '';
 4086:         foreach my $item (keys(%$storehash)) {
 4087:             $items.= &escape($item).'='.
 4088:                      &freeze_escape($$storehash{$item}).'&';
 4089:         }
 4090:         $items=~s/\&$//;
 4091:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 4092:                           $coursehome);
 4093:     }
 4094:     if ($outcome eq 'unknown_cmd') {
 4095:         my $what;
 4096:         foreach my $cid (keys(%$storehash)) {
 4097:             $what .= &escape($cid).'=';
 4098:             foreach my $item ('description','inst_code','owner','type') {
 4099:                 $what .= &escape($storehash->{$cid}{$item}).':';
 4100:             }
 4101:             $what =~ s/\:$/&/;
 4102:         }
 4103:         $what =~ s/\&$//;  
 4104:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 4105:     } else {
 4106:         return $outcome;
 4107:     }
 4108: }
 4109: 
 4110: sub courseiddump {
 4111:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 4112:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 4113:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 4114:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
 4115:     my $as_hash = 1;
 4116:     my %returnhash;
 4117:     if (!$domfilter) { $domfilter=''; }
 4118:     my %libserv = &all_library();
 4119:     foreach my $tryserver (keys(%libserv)) {
 4120:         if ( (  $hostidflag == 1 
 4121: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 4122: 	     || (!defined($hostidflag)) ) {
 4123: 
 4124: 	    if (($domfilter eq '') ||
 4125: 		(&host_domain($tryserver) eq $domfilter)) {
 4126:                 my $rep;
 4127:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
 4128:                     $rep = LONCAPA::Lond::dump_course_id_handler(
 4129:                         join(":", (&host_domain($tryserver), $sincefilter, 
 4130:                                 &escape($descfilter), &escape($instcodefilter), 
 4131:                                 &escape($ownerfilter), &escape($coursefilter),
 4132:                                 &escape($typefilter), &escape($regexp_ok), 
 4133:                                 $as_hash, &escape($selfenrollonly), 
 4134:                                 &escape($catfilter), $showhidden, $caller, 
 4135:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
 4136:                                 &escape($createdbefore), &escape($createdafter), 
 4137:                                 &escape($creationcontext), $domcloner)));
 4138:                 } else {
 4139:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
 4140:                              $sincefilter.':'.&escape($descfilter).':'.
 4141:                              &escape($instcodefilter).':'.&escape($ownerfilter).
 4142:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
 4143:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
 4144:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
 4145:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
 4146:                              &escape($cc_clone).':'.$cloneonly.':'.
 4147:                              &escape($createdbefore).':'.&escape($createdafter).':'.
 4148:                              &escape($creationcontext).':'.$domcloner,
 4149:                              $tryserver);
 4150:                 }
 4151:                      
 4152:                 my @pairs=split(/\&/,$rep);
 4153:                 foreach my $item (@pairs) {
 4154:                     my ($key,$value)=split(/\=/,$item,2);
 4155:                     $key = &unescape($key);
 4156:                     next if ($key =~ /^error: 2 /);
 4157:                     my $result = &thaw_unescape($value);
 4158:                     if (ref($result) eq 'HASH') {
 4159:                         $returnhash{$key}=$result;
 4160:                     } else {
 4161:                         my @responses = split(/:/,$value);
 4162:                         my @items = ('description','inst_code','owner','type');
 4163:                         for (my $i=0; $i<@responses; $i++) {
 4164:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 4165:                         }
 4166:                     }
 4167:                 }
 4168:             }
 4169:         }
 4170:     }
 4171:     return %returnhash;
 4172: }
 4173: 
 4174: sub courselastaccess {
 4175:     my ($cdom,$cnum,$hostidref) = @_;
 4176:     my %returnhash;
 4177:     if ($cdom && $cnum) {
 4178:         my $chome = &homeserver($cnum,$cdom);
 4179:         if ($chome ne 'no_host') {
 4180:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 4181:             &extract_lastaccess(\%returnhash,$rep);
 4182:         }
 4183:     } else {
 4184:         if (!$cdom) { $cdom=''; }
 4185:         my %libserv = &all_library();
 4186:         foreach my $tryserver (keys(%libserv)) {
 4187:             if (ref($hostidref) eq 'ARRAY') {
 4188:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 4189:             } 
 4190:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 4191:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 4192:                 &extract_lastaccess(\%returnhash,$rep);
 4193:             }
 4194:         }
 4195:     }
 4196:     return %returnhash;
 4197: }
 4198: 
 4199: sub extract_lastaccess {
 4200:     my ($returnhash,$rep) = @_;
 4201:     if (ref($returnhash) eq 'HASH') {
 4202:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 4203:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 4204:                  $rep eq '') {
 4205:             my @pairs=split(/\&/,$rep);
 4206:             foreach my $item (@pairs) {
 4207:                 my ($key,$value)=split(/\=/,$item,2);
 4208:                 $key = &unescape($key);
 4209:                 next if ($key =~ /^error: 2 /);
 4210:                 $returnhash->{$key} = &thaw_unescape($value);
 4211:             }
 4212:         }
 4213:     }
 4214:     return;
 4215: }
 4216: 
 4217: # ---------------------------------------------------------- DC e-mail
 4218: 
 4219: sub dcmailput {
 4220:     my ($domain,$msgid,$message,$server)=@_;
 4221:     my $status = &Apache::lonnet::critical(
 4222:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 4223:        &escape($message),$server);
 4224:     return $status;
 4225: }
 4226: 
 4227: sub dcmaildump {
 4228:     my ($dom,$startdate,$enddate,$senders) = @_;
 4229:     my %returnhash=();
 4230: 
 4231:     if (defined(&domain($dom,'primary'))) {
 4232:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 4233:                                                          &escape($enddate).':';
 4234: 	my @esc_senders=map { &escape($_)} @$senders;
 4235: 	$cmd.=&escape(join('&',@esc_senders));
 4236: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 4237:             my ($key,$value) = split(/\=/,$line,2);
 4238:             if (($key) && ($value)) {
 4239:                 $returnhash{&unescape($key)} = &unescape($value);
 4240:             }
 4241:         }
 4242:     }
 4243:     return %returnhash;
 4244: }
 4245: # ---------------------------------------------------------- Domain roles
 4246: 
 4247: sub get_domain_roles {
 4248:     my ($dom,$roles,$startdate,$enddate)=@_;
 4249:     if ((!defined($startdate)) || ($startdate eq '')) {
 4250:         $startdate = '.';
 4251:     }
 4252:     if ((!defined($enddate)) || ($enddate eq '')) {
 4253:         $enddate = '.';
 4254:     }
 4255:     my $rolelist;
 4256:     if (ref($roles) eq 'ARRAY') {
 4257:         $rolelist = join('&',@{$roles});
 4258:     }
 4259:     my %personnel = ();
 4260: 
 4261:     my %servers = &get_servers($dom,'library');
 4262:     foreach my $tryserver (keys(%servers)) {
 4263: 	%{$personnel{$tryserver}}=();
 4264: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 4265: 					    &escape($startdate).':'.
 4266: 					    &escape($enddate).':'.
 4267: 					    &escape($rolelist), $tryserver))) {
 4268: 	    my ($key,$value) = split(/\=/,$line,2);
 4269: 	    if (($key) && ($value)) {
 4270: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 4271: 	    }
 4272: 	}
 4273:     }
 4274:     return %personnel;
 4275: }
 4276: 
 4277: # ----------------------------------------------------------- Interval timing 
 4278: 
 4279: {
 4280: # Caches needed for speedup of navmaps
 4281: # We don't want to cache this for very long at all (5 seconds at most)
 4282: # 
 4283: # The user for whom we cache
 4284: my $cachedkey='';
 4285: # The cached times for this user
 4286: my %cachedtimes=();
 4287: # When this was last done
 4288: my $cachedtime=();
 4289: 
 4290: sub load_all_first_access {
 4291:     my ($uname,$udom)=@_;
 4292:     if (($cachedkey eq $uname.':'.$udom) &&
 4293:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
 4294:         return;
 4295:     }
 4296:     $cachedtime=time;
 4297:     $cachedkey=$uname.':'.$udom;
 4298:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 4299: }
 4300: 
 4301: sub get_first_access {
 4302:     my ($type,$argsymb,$argmap)=@_;
 4303:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 4304:     if ($argsymb) { $symb=$argsymb; }
 4305:     my ($map,$id,$res)=&decode_symb($symb);
 4306:     if ($argmap) { $map = $argmap; }
 4307:     if ($type eq 'course') {
 4308: 	$res='course';
 4309:     } elsif ($type eq 'map') {
 4310: 	$res=&symbread($map);
 4311:     } else {
 4312: 	$res=$symb;
 4313:     }
 4314:     &load_all_first_access($uname,$udom);
 4315:     return $cachedtimes{"$courseid\0$res"};
 4316: }
 4317: 
 4318: sub set_first_access {
 4319:     my ($type,$interval)=@_;
 4320:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 4321:     my ($map,$id,$res)=&decode_symb($symb);
 4322:     if ($type eq 'course') {
 4323: 	$res='course';
 4324:     } elsif ($type eq 'map') {
 4325: 	$res=&symbread($map);
 4326:     } else {
 4327: 	$res=$symb;
 4328:     }
 4329:     $cachedkey='';
 4330:     my $firstaccess=&get_first_access($type,$symb,$map);
 4331:     if (!$firstaccess) {
 4332:         my $start = time;
 4333: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 4334:                           $udom,$uname);
 4335:         if ($putres eq 'ok') {
 4336:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 4337:                  $udom,$uname); 
 4338:             &appenv(
 4339:                      {
 4340:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 4341:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 4342:                      }
 4343:                   );
 4344:         }
 4345:         return $putres;
 4346:     }
 4347:     return 'already_set';
 4348: }
 4349: }
 4350: # --------------------------------------------- Set Expire Date for Spreadsheet
 4351: 
 4352: sub expirespread {
 4353:     my ($uname,$udom,$stype,$usymb)=@_;
 4354:     my $cid=$env{'request.course.id'}; 
 4355:     if ($cid) {
 4356:        my $now=time;
 4357:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 4358:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 4359:                             $env{'course.'.$cid.'.num'}.
 4360: 	        	    ':nohist_expirationdates:'.
 4361:                             &escape($key).'='.$now,
 4362:                             $env{'course.'.$cid.'.home'})
 4363:     }
 4364:     return 'ok';
 4365: }
 4366: 
 4367: # ----------------------------------------------------- Devalidate Spreadsheets
 4368: 
 4369: sub devalidate {
 4370:     my ($symb,$uname,$udom)=@_;
 4371:     my $cid=$env{'request.course.id'}; 
 4372:     if ($cid) {
 4373:         # delete the stored spreadsheets for
 4374:         # - the student level sheet of this user in course's homespace
 4375:         # - the assessment level sheet for this resource 
 4376:         #   for this user in user's homespace
 4377: 	# - current conditional state info
 4378: 	my $key=$uname.':'.$udom.':';
 4379:         my $status=
 4380: 	    &del('nohist_calculatedsheets',
 4381: 		 [$key.'studentcalc:'],
 4382: 		 $env{'course.'.$cid.'.domain'},
 4383: 		 $env{'course.'.$cid.'.num'})
 4384: 		.' '.
 4385: 	    &del('nohist_calculatedsheets_'.$cid,
 4386: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 4387:         unless ($status eq 'ok ok') {
 4388:            &logthis('Could not devalidate spreadsheet '.
 4389:                     $uname.' at '.$udom.' for '.
 4390: 		    $symb.': '.$status);
 4391:         }
 4392: 	&delenv('user.state.'.$cid);
 4393:     }
 4394: }
 4395: 
 4396: sub get_scalar {
 4397:     my ($string,$end) = @_;
 4398:     my $value;
 4399:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 4400: 	$value = $1;
 4401:     } elsif ($$string =~ s/^([^&]*?)&//) {
 4402: 	$value = $1;
 4403:     }
 4404:     return &unescape($value);
 4405: }
 4406: 
 4407: sub array2str {
 4408:   my (@array) = @_;
 4409:   my $result=&arrayref2str(\@array);
 4410:   $result=~s/^__ARRAY_REF__//;
 4411:   $result=~s/__END_ARRAY_REF__$//;
 4412:   return $result;
 4413: }
 4414: 
 4415: sub arrayref2str {
 4416:   my ($arrayref) = @_;
 4417:   my $result='__ARRAY_REF__';
 4418:   foreach my $elem (@$arrayref) {
 4419:     if(ref($elem) eq 'ARRAY') {
 4420:       $result.=&arrayref2str($elem).'&';
 4421:     } elsif(ref($elem) eq 'HASH') {
 4422:       $result.=&hashref2str($elem).'&';
 4423:     } elsif(ref($elem)) {
 4424:       #print("Got a ref of ".(ref($elem))." skipping.");
 4425:     } else {
 4426:       $result.=&escape($elem).'&';
 4427:     }
 4428:   }
 4429:   $result=~s/\&$//;
 4430:   $result .= '__END_ARRAY_REF__';
 4431:   return $result;
 4432: }
 4433: 
 4434: sub hash2str {
 4435:   my (%hash) = @_;
 4436:   my $result=&hashref2str(\%hash);
 4437:   $result=~s/^__HASH_REF__//;
 4438:   $result=~s/__END_HASH_REF__$//;
 4439:   return $result;
 4440: }
 4441: 
 4442: sub hashref2str {
 4443:   my ($hashref)=@_;
 4444:   my $result='__HASH_REF__';
 4445:   foreach my $key (sort(keys(%$hashref))) {
 4446:     if (ref($key) eq 'ARRAY') {
 4447:       $result.=&arrayref2str($key).'=';
 4448:     } elsif (ref($key) eq 'HASH') {
 4449:       $result.=&hashref2str($key).'=';
 4450:     } elsif (ref($key)) {
 4451:       $result.='=';
 4452:       #print("Got a ref of ".(ref($key))." skipping.");
 4453:     } else {
 4454: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 4455:     }
 4456: 
 4457:     if(ref($hashref->{$key}) eq 'ARRAY') {
 4458:       $result.=&arrayref2str($hashref->{$key}).'&';
 4459:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 4460:       $result.=&hashref2str($hashref->{$key}).'&';
 4461:     } elsif(ref($hashref->{$key})) {
 4462:        $result.='&';
 4463:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 4464:     } else {
 4465:       $result.=&escape($hashref->{$key}).'&';
 4466:     }
 4467:   }
 4468:   $result=~s/\&$//;
 4469:   $result .= '__END_HASH_REF__';
 4470:   return $result;
 4471: }
 4472: 
 4473: sub str2hash {
 4474:     my ($string)=@_;
 4475:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 4476:     return %$hash;
 4477: }
 4478: 
 4479: sub str2hashref {
 4480:   my ($string) = @_;
 4481: 
 4482:   my %hash;
 4483: 
 4484:   if($string !~ /^__HASH_REF__/) {
 4485:       if (! ($string eq '' || !defined($string))) {
 4486: 	  $hash{'error'}='Not hash reference';
 4487:       }
 4488:       return (\%hash, $string);
 4489:   }
 4490: 
 4491:   $string =~ s/^__HASH_REF__//;
 4492: 
 4493:   while($string !~ /^__END_HASH_REF__/) {
 4494:       #key
 4495:       my $key='';
 4496:       if($string =~ /^__HASH_REF__/) {
 4497:           ($key, $string)=&str2hashref($string);
 4498:           if(defined($key->{'error'})) {
 4499:               $hash{'error'}='Bad data';
 4500:               return (\%hash, $string);
 4501:           }
 4502:       } elsif($string =~ /^__ARRAY_REF__/) {
 4503:           ($key, $string)=&str2arrayref($string);
 4504:           if($key->[0] eq 'Array reference error') {
 4505:               $hash{'error'}='Bad data';
 4506:               return (\%hash, $string);
 4507:           }
 4508:       } else {
 4509:           $string =~ s/^(.*?)=//;
 4510: 	  $key=&unescape($1);
 4511:       }
 4512:       $string =~ s/^=//;
 4513: 
 4514:       #value
 4515:       my $value='';
 4516:       if($string =~ /^__HASH_REF__/) {
 4517:           ($value, $string)=&str2hashref($string);
 4518:           if(defined($value->{'error'})) {
 4519:               $hash{'error'}='Bad data';
 4520:               return (\%hash, $string);
 4521:           }
 4522:       } elsif($string =~ /^__ARRAY_REF__/) {
 4523:           ($value, $string)=&str2arrayref($string);
 4524:           if($value->[0] eq 'Array reference error') {
 4525:               $hash{'error'}='Bad data';
 4526:               return (\%hash, $string);
 4527:           }
 4528:       } else {
 4529: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 4530:       }
 4531:       $string =~ s/^&//;
 4532: 
 4533:       $hash{$key}=$value;
 4534:   }
 4535: 
 4536:   $string =~ s/^__END_HASH_REF__//;
 4537: 
 4538:   return (\%hash, $string);
 4539: }
 4540: 
 4541: sub str2array {
 4542:     my ($string)=@_;
 4543:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 4544:     return @$array;
 4545: }
 4546: 
 4547: sub str2arrayref {
 4548:   my ($string) = @_;
 4549:   my @array;
 4550: 
 4551:   if($string !~ /^__ARRAY_REF__/) {
 4552:       if (! ($string eq '' || !defined($string))) {
 4553: 	  $array[0]='Array reference error';
 4554:       }
 4555:       return (\@array, $string);
 4556:   }
 4557: 
 4558:   $string =~ s/^__ARRAY_REF__//;
 4559: 
 4560:   while($string !~ /^__END_ARRAY_REF__/) {
 4561:       my $value='';
 4562:       if($string =~ /^__HASH_REF__/) {
 4563:           ($value, $string)=&str2hashref($string);
 4564:           if(defined($value->{'error'})) {
 4565:               $array[0] ='Array reference error';
 4566:               return (\@array, $string);
 4567:           }
 4568:       } elsif($string =~ /^__ARRAY_REF__/) {
 4569:           ($value, $string)=&str2arrayref($string);
 4570:           if($value->[0] eq 'Array reference error') {
 4571:               $array[0] ='Array reference error';
 4572:               return (\@array, $string);
 4573:           }
 4574:       } else {
 4575: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 4576:       }
 4577:       $string =~ s/^&//;
 4578: 
 4579:       push(@array, $value);
 4580:   }
 4581: 
 4582:   $string =~ s/^__END_ARRAY_REF__//;
 4583: 
 4584:   return (\@array, $string);
 4585: }
 4586: 
 4587: # -------------------------------------------------------------------Temp Store
 4588: 
 4589: sub tmpreset {
 4590:   my ($symb,$namespace,$domain,$stuname) = @_;
 4591:   if (!$symb) {
 4592:     $symb=&symbread();
 4593:     if (!$symb) { $symb= $env{'request.url'}; }
 4594:   }
 4595:   $symb=escape($symb);
 4596: 
 4597:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4598:   $namespace=~s/\//\_/g;
 4599:   $namespace=~s/\W//g;
 4600: 
 4601:   if (!$domain) { $domain=$env{'user.domain'}; }
 4602:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4603:   if ($domain eq 'public' && $stuname eq 'public') {
 4604:       $stuname=$ENV{'REMOTE_ADDR'};
 4605:   }
 4606:   my $path=LONCAPA::tempdir();
 4607:   my %hash;
 4608:   if (tie(%hash,'GDBM_File',
 4609: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4610: 	  &GDBM_WRCREAT(),0640)) {
 4611:     foreach my $key (keys(%hash)) {
 4612:       if ($key=~ /:$symb/) {
 4613: 	delete($hash{$key});
 4614:       }
 4615:     }
 4616:   }
 4617: }
 4618: 
 4619: sub tmpstore {
 4620:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4621: 
 4622:   if (!$symb) {
 4623:     $symb=&symbread();
 4624:     if (!$symb) { $symb= $env{'request.url'}; }
 4625:   }
 4626:   $symb=escape($symb);
 4627: 
 4628:   if (!$namespace) {
 4629:     # I don't think we would ever want to store this for a course.
 4630:     # it seems this will only be used if we don't have a course.
 4631:     #$namespace=$env{'request.course.id'};
 4632:     #if (!$namespace) {
 4633:       $namespace=$env{'request.state'};
 4634:     #}
 4635:   }
 4636:   $namespace=~s/\//\_/g;
 4637:   $namespace=~s/\W//g;
 4638:   if (!$domain) { $domain=$env{'user.domain'}; }
 4639:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4640:   if ($domain eq 'public' && $stuname eq 'public') {
 4641:       $stuname=$ENV{'REMOTE_ADDR'};
 4642:   }
 4643:   my $now=time;
 4644:   my %hash;
 4645:   my $path=LONCAPA::tempdir();
 4646:   if (tie(%hash,'GDBM_File',
 4647: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4648: 	  &GDBM_WRCREAT(),0640)) {
 4649:     $hash{"version:$symb"}++;
 4650:     my $version=$hash{"version:$symb"};
 4651:     my $allkeys=''; 
 4652:     foreach my $key (keys(%$storehash)) {
 4653:       $allkeys.=$key.':';
 4654:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 4655:     }
 4656:     $hash{"$version:$symb:timestamp"}=$now;
 4657:     $allkeys.='timestamp';
 4658:     $hash{"$version:keys:$symb"}=$allkeys;
 4659:     if (untie(%hash)) {
 4660:       return 'ok';
 4661:     } else {
 4662:       return "error:$!";
 4663:     }
 4664:   } else {
 4665:     return "error:$!";
 4666:   }
 4667: }
 4668: 
 4669: # -----------------------------------------------------------------Temp Restore
 4670: 
 4671: sub tmprestore {
 4672:   my ($symb,$namespace,$domain,$stuname) = @_;
 4673: 
 4674:   if (!$symb) {
 4675:     $symb=&symbread();
 4676:     if (!$symb) { $symb= $env{'request.url'}; }
 4677:   }
 4678:   $symb=escape($symb);
 4679: 
 4680:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4681: 
 4682:   if (!$domain) { $domain=$env{'user.domain'}; }
 4683:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4684:   if ($domain eq 'public' && $stuname eq 'public') {
 4685:       $stuname=$ENV{'REMOTE_ADDR'};
 4686:   }
 4687:   my %returnhash;
 4688:   $namespace=~s/\//\_/g;
 4689:   $namespace=~s/\W//g;
 4690:   my %hash;
 4691:   my $path=LONCAPA::tempdir();
 4692:   if (tie(%hash,'GDBM_File',
 4693: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4694: 	  &GDBM_READER(),0640)) {
 4695:     my $version=$hash{"version:$symb"};
 4696:     $returnhash{'version'}=$version;
 4697:     my $scope;
 4698:     for ($scope=1;$scope<=$version;$scope++) {
 4699:       my $vkeys=$hash{"$scope:keys:$symb"};
 4700:       my @keys=split(/:/,$vkeys);
 4701:       my $key;
 4702:       $returnhash{"$scope:keys"}=$vkeys;
 4703:       foreach $key (@keys) {
 4704: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4705: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4706:       }
 4707:     }
 4708:     if (!(untie(%hash))) {
 4709:       return "error:$!";
 4710:     }
 4711:   } else {
 4712:     return "error:$!";
 4713:   }
 4714:   return %returnhash;
 4715: }
 4716: 
 4717: # ----------------------------------------------------------------------- Store
 4718: 
 4719: sub store {
 4720:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4721:     my $home='';
 4722: 
 4723:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4724: 
 4725:     $symb=&symbclean($symb);
 4726:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 4727: 
 4728:     if (!$domain) { $domain=$env{'user.domain'}; }
 4729:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4730: 
 4731:     &devalidate($symb,$stuname,$domain);
 4732: 
 4733:     $symb=escape($symb);
 4734:     if (!$namespace) { 
 4735:        unless ($namespace=$env{'request.course.id'}) { 
 4736:           return ''; 
 4737:        } 
 4738:     }
 4739:     if (!$home) { $home=$env{'user.home'}; }
 4740: 
 4741:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 4742:     $$storehash{'host'}=$perlvar{'lonHostID'};
 4743: 
 4744:     my $namevalue='';
 4745:     foreach my $key (keys(%$storehash)) {
 4746:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4747:     }
 4748:     $namevalue=~s/\&$//;
 4749:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 4750:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 4751: }
 4752: 
 4753: # -------------------------------------------------------------- Critical Store
 4754: 
 4755: sub cstore {
 4756:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4757:     my $home='';
 4758: 
 4759:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4760: 
 4761:     $symb=&symbclean($symb);
 4762:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 4763: 
 4764:     if (!$domain) { $domain=$env{'user.domain'}; }
 4765:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4766: 
 4767:     &devalidate($symb,$stuname,$domain);
 4768: 
 4769:     $symb=escape($symb);
 4770:     if (!$namespace) { 
 4771:        unless ($namespace=$env{'request.course.id'}) { 
 4772:           return ''; 
 4773:        } 
 4774:     }
 4775:     if (!$home) { $home=$env{'user.home'}; }
 4776: 
 4777:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 4778:     $$storehash{'host'}=$perlvar{'lonHostID'};
 4779: 
 4780:     my $namevalue='';
 4781:     foreach my $key (keys(%$storehash)) {
 4782:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4783:     }
 4784:     $namevalue=~s/\&$//;
 4785:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 4786:     return critical
 4787:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 4788: }
 4789: 
 4790: # --------------------------------------------------------------------- Restore
 4791: 
 4792: sub restore {
 4793:     my ($symb,$namespace,$domain,$stuname) = @_;
 4794:     my $home='';
 4795: 
 4796:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4797: 
 4798:     if (!$symb) {
 4799:         return if ($namespace eq 'courserequests');
 4800:         unless ($symb=escape(&symbread())) { return ''; }
 4801:     } else {
 4802:         unless ($namespace eq 'courserequests') {
 4803:             $symb=&escape(&symbclean($symb));
 4804:         }
 4805:     }
 4806:     if (!$namespace) { 
 4807:        unless ($namespace=$env{'request.course.id'}) { 
 4808:           return ''; 
 4809:        } 
 4810:     }
 4811:     if (!$domain) { $domain=$env{'user.domain'}; }
 4812:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4813:     if (!$home) { $home=$env{'user.home'}; }
 4814:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 4815: 
 4816:     my %returnhash=();
 4817:     foreach my $line (split(/\&/,$answer)) {
 4818: 	my ($name,$value)=split(/\=/,$line);
 4819:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 4820:     }
 4821:     my $version;
 4822:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 4823:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 4824:           $returnhash{$item}=$returnhash{$version.':'.$item};
 4825:        }
 4826:     }
 4827:     return %returnhash;
 4828: }
 4829: 
 4830: # ---------------------------------------------------------- Course Description
 4831: #
 4832: #  
 4833: 
 4834: sub coursedescription {
 4835:     my ($courseid,$args)=@_;
 4836:     $courseid=~s/^\///;
 4837:     $courseid=~s/\_/\//g;
 4838:     my ($cdomain,$cnum)=split(/\//,$courseid);
 4839:     my $chome=&homeserver($cnum,$cdomain);
 4840:     my $normalid=$cdomain.'_'.$cnum;
 4841:     # need to always cache even if we get errors otherwise we keep 
 4842:     # trying and trying and trying to get the course description.
 4843:     my %envhash=();
 4844:     my %returnhash=();
 4845:     
 4846:     my $expiretime=600;
 4847:     if ($env{'request.course.id'} eq $normalid) {
 4848: 	$expiretime=120;
 4849:     }
 4850: 
 4851:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 4852:     if (!$args->{'freshen_cache'}
 4853: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 4854: 	foreach my $key (keys(%env)) {
 4855: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 4856: 	    my ($setting) = $1;
 4857: 	    $returnhash{$setting} = $env{$key};
 4858: 	}
 4859: 	return %returnhash;
 4860:     }
 4861: 
 4862:     # get the data again
 4863: 
 4864:     if (!$args->{'one_time'}) {
 4865: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 4866:     }
 4867: 
 4868:     if ($chome ne 'no_host') {
 4869:        %returnhash=&dump('environment',$cdomain,$cnum);
 4870:        if (!exists($returnhash{'con_lost'})) {
 4871: 	   my $username = $env{'user.name'}; # Defult username
 4872: 	   if(defined $args->{'user'}) {
 4873: 	       $username = $args->{'user'};
 4874: 	   }
 4875:            $returnhash{'home'}= $chome;
 4876: 	   $returnhash{'domain'} = $cdomain;
 4877: 	   $returnhash{'num'} = $cnum;
 4878:            if (!defined($returnhash{'type'})) {
 4879:                $returnhash{'type'} = 'Course';
 4880:            }
 4881:            while (my ($name,$value) = each %returnhash) {
 4882:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 4883:            }
 4884:            $returnhash{'url'}=&clutter($returnhash{'url'});
 4885:            $returnhash{'fn'}=LONCAPA::tempdir() .
 4886: 	       $username.'_'.$cdomain.'_'.$cnum;
 4887:            $envhash{'course.'.$normalid.'.home'}=$chome;
 4888:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 4889:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 4890:        }
 4891:     }
 4892:     if (!$args->{'one_time'}) {
 4893: 	&appenv(\%envhash);
 4894:     }
 4895:     return %returnhash;
 4896: }
 4897: 
 4898: sub update_released_required {
 4899:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 4900:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 4901:         $cid = $env{'request.course.id'};
 4902:         $cdom = $env{'course.'.$cid.'.domain'};
 4903:         $cnum = $env{'course.'.$cid.'.num'};
 4904:         $chome = $env{'course.'.$cid.'.home'};
 4905:     }
 4906:     if ($needsrelease) {
 4907:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 4908:         my $needsupdate;
 4909:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 4910:             $needsupdate = 1;
 4911:         } else {
 4912:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 4913:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 4914:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 4915:                 $needsupdate = 1;
 4916:             }
 4917:         }
 4918:         if ($needsupdate) {
 4919:             my %needshash = (
 4920:                              'internal.releaserequired' => $needsrelease,
 4921:                             );
 4922:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 4923:             if ($putresult eq 'ok') {
 4924:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 4925:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 4926:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 4927:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 4928:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 4929:                 }
 4930:             }
 4931:         }
 4932:     }
 4933:     return;
 4934: }
 4935: 
 4936: # -------------------------------------------------See if a user is privileged
 4937: 
 4938: sub privileged {
 4939:     my ($username,$domain,$possdomains,$possroles)=@_;
 4940:     my $now = time;
 4941:     my $roles;
 4942:     if (ref($possroles) eq 'ARRAY') {
 4943:         $roles = $possroles; 
 4944:     } else {
 4945:         $roles = ['dc','su'];
 4946:     }
 4947:     if (ref($possdomains) eq 'ARRAY') {
 4948:         my %privileged = &privileged_by_domain($possdomains,$roles);
 4949:         foreach my $dom (@{$possdomains}) {
 4950:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
 4951:                 (ref($privileged{$dom}) eq 'HASH')) {
 4952:                 foreach my $role (@{$roles}) {
 4953:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 4954:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
 4955:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
 4956:                             return 1 unless (($end && $end < $now) ||
 4957:                                              ($start && $start > $now));
 4958:                         }
 4959:                     }
 4960:                 }
 4961:             }
 4962:         }
 4963:     } else {
 4964:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
 4965:         my $now = time;
 4966: 
 4967:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
 4968:             my ($trole, $tend, $tstart) = split(/_/, $role);
 4969:             if (grep(/^\Q$trole\E$/,@{$roles})) {
 4970:                 return 1 unless ($tend && $tend < $now) 
 4971:                         or ($tstart && $tstart > $now);
 4972:             }
 4973:         }
 4974:     }
 4975:     return 0;
 4976: }
 4977: 
 4978: sub privileged_by_domain {
 4979:     my ($domains,$roles) = @_;
 4980:     my %privileged = ();
 4981:     my $cachetime = 60*60*24;
 4982:     my $now = time;
 4983:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
 4984:         return %privileged;
 4985:     }
 4986:     foreach my $dom (@{$domains}) {
 4987:         next if (ref($privileged{$dom}) eq 'HASH');
 4988:         my $needroles;
 4989:         foreach my $role (@{$roles}) {
 4990:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
 4991:             if (defined($cached)) {
 4992:                 if (ref($result) eq 'HASH') {
 4993:                     $privileged{$dom}{$role} = $result;
 4994:                 }
 4995:             } else {
 4996:                 $needroles = 1;
 4997:             }
 4998:         }
 4999:         if ($needroles) {
 5000:             my %dompersonnel = &get_domain_roles($dom,$roles);
 5001:             $privileged{$dom} = {};
 5002:             foreach my $server (keys(%dompersonnel)) {
 5003:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 5004:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
 5005:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
 5006:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
 5007:                         next if ($end && $end < $now);
 5008:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
 5009:                             $dompersonnel{$server}{$item};
 5010:                     }
 5011:                 }
 5012:             }
 5013:             if (ref($privileged{$dom}) eq 'HASH') {
 5014:                 foreach my $role (@{$roles}) {
 5015:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 5016:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
 5017:                     } else {
 5018:                         my %hash = ();
 5019:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
 5020:                     }
 5021:                 }
 5022:             }
 5023:         }
 5024:     }
 5025:     return %privileged;
 5026: }
 5027: 
 5028: # -------------------------------------------------------- Get user privileges
 5029: 
 5030: sub rolesinit {
 5031:     my ($domain, $username) = @_;
 5032:     my %userroles = ('user.login.time' => time);
 5033:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 5034: 
 5035:     # firstaccess and timerinterval are related to timed maps/resources. 
 5036:     # also, blocking can be triggered by an activating timer
 5037:     # it's saved in the user's %env.
 5038:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 5039:     my %timerinterval = &dump('timerinterval', $domain, $username);
 5040:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 5041:         %timerintchk, %timerintenv);
 5042: 
 5043:     foreach my $key (keys(%firstaccess)) {
 5044:         my ($cid, $rest) = split(/\0/, $key);
 5045:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 5046:     }
 5047: 
 5048:     foreach my $key (keys(%timerinterval)) {
 5049:         my ($cid,$rest) = split(/\0/,$key);
 5050:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 5051:     }
 5052: 
 5053:     my %allroles=();
 5054:     my %allgroups=();
 5055: 
 5056:     for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
 5057:         my $role = $rolesdump{$area};
 5058:         $area =~ s/\_\w\w$//;
 5059: 
 5060:         my ($trole, $tend, $tstart, $group_privs);
 5061: 
 5062:         if ($role =~ /^cr/) {
 5063:         # Custom role, defined by a user 
 5064:         # e.g., user.role.cr/msu/smith/mynewrole
 5065:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 5066:                 $trole = $1;
 5067:                 ($tend, $tstart) = split('_', $2);
 5068:             } else {
 5069:                 $trole = $role;
 5070:             }
 5071:         } elsif ($role =~ m|^gr/|) {
 5072:         # Role of member in a group, defined within a course/community
 5073:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 5074:             ($trole, $tend, $tstart) = split(/_/, $role);
 5075:             next if $tstart eq '-1';
 5076:             ($trole, $group_privs) = split(/\//, $trole);
 5077:             $group_privs = &unescape($group_privs);
 5078:         } else {
 5079:         # Just a normal role, defined in roles.tab
 5080:             ($trole, $tend, $tstart) = split(/_/,$role);
 5081:         }
 5082: 
 5083:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 5084:                  $username);
 5085:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 5086: 
 5087:         # role expired or not available yet?
 5088:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 5089:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 5090: 
 5091:         next if $area eq '' or $trole eq '';
 5092: 
 5093:         my $spec = "$trole.$area";
 5094:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 5095: 
 5096:         if ($trole =~ /^cr\//) {
 5097:         # Custom role, defined by a user
 5098:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 5099:         } elsif ($trole eq 'gr') {
 5100:         # Role of a member in a group, defined within a course/community
 5101:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 5102:             next;
 5103:         } else {
 5104:         # Normal role, defined in roles.tab
 5105:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 5106:         }
 5107: 
 5108:         my $cid = $tdomain.'_'.$trest;
 5109:         unless ($firstaccchk{$cid}) {
 5110:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 5111:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 5112:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 5113:                         $coursetimerstarts{$cid}{$item}; 
 5114:                 }
 5115:             }
 5116:             $firstaccchk{$cid} = 1;
 5117:         }
 5118:         unless ($timerintchk{$cid}) {
 5119:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 5120:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 5121:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 5122:                        $coursetimerintervals{$cid}{$item};
 5123:                 }
 5124:             }
 5125:             $timerintchk{$cid} = 1;
 5126:         }
 5127:     }
 5128: 
 5129:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
 5130:         \%allroles, \%allgroups);
 5131:     $env{'user.adv'} = $userroles{'user.adv'};
 5132: 
 5133:     return (\%userroles,\%firstaccenv,\%timerintenv);
 5134: }
 5135: 
 5136: sub set_arearole {
 5137:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
 5138:     unless ($nolog) {
 5139: # log the associated role with the area
 5140:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 5141:     }
 5142:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 5143: }
 5144: 
 5145: sub custom_roleprivs {
 5146:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 5147:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 5148:     my $homsvr=homeserver($rauthor,$rdomain);
 5149:     if (&hostname($homsvr) ne '') {
 5150:         my ($rdummy,$roledef)=
 5151:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 5152:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 5153:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 5154:             if (defined($syspriv)) {
 5155:                 if ($trest =~ /^$match_community$/) {
 5156:                     $syspriv =~ s/bre\&S//; 
 5157:                 }
 5158:                 $$allroles{'cm./'}.=':'.$syspriv;
 5159:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 5160:             }
 5161:             if ($tdomain ne '') {
 5162:                 if (defined($dompriv)) {
 5163:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 5164:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 5165:                 }
 5166:                 if (($trest ne '') && (defined($coursepriv))) {
 5167:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 5168:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 5169:                 }
 5170:             }
 5171:         }
 5172:     }
 5173: }
 5174: 
 5175: sub group_roleprivs {
 5176:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 5177:     my $access = 1;
 5178:     my $now = time;
 5179:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 5180:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 5181:     if ($access) {
 5182:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 5183:         $$allgroups{$course}{$group} .=':'.$group_privs;
 5184:     }
 5185: }
 5186: 
 5187: sub standard_roleprivs {
 5188:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 5189:     if (defined($pr{$trole.':s'})) {
 5190:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 5191:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 5192:     }
 5193:     if ($tdomain ne '') {
 5194:         if (defined($pr{$trole.':d'})) {
 5195:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 5196:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 5197:         }
 5198:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 5199:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 5200:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 5201:         }
 5202:     }
 5203: }
 5204: 
 5205: sub set_userprivs {
 5206:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 5207:     my $author=0;
 5208:     my $adv=0;
 5209:     my %grouproles = ();
 5210:     if (keys(%{$allgroups}) > 0) {
 5211:         my @groupkeys; 
 5212:         foreach my $role (keys(%{$allroles})) {
 5213:             push(@groupkeys,$role);
 5214:         }
 5215:         if (ref($groups_roles) eq 'HASH') {
 5216:             foreach my $key (keys(%{$groups_roles})) {
 5217:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 5218:                     push(@groupkeys,$key);
 5219:                 }
 5220:             }
 5221:         }
 5222:         if (@groupkeys > 0) {
 5223:             foreach my $role (@groupkeys) {
 5224:                 my ($trole,$area,$sec,$extendedarea);
 5225:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 5226:                     $trole = $1;
 5227:                     $area = $2;
 5228:                     $sec = $3;
 5229:                     $extendedarea = $area.$sec;
 5230:                     if (exists($$allgroups{$area})) {
 5231:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 5232:                             my $spec = $trole.'.'.$extendedarea;
 5233:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 5234:                                                 $$allgroups{$area}{$group};
 5235:                         }
 5236:                     }
 5237:                 }
 5238:             }
 5239:         }
 5240:     }
 5241:     foreach my $group (keys(%grouproles)) {
 5242:         $$allroles{$group} = $grouproles{$group};
 5243:     }
 5244:     foreach my $role (keys(%{$allroles})) {
 5245:         my %thesepriv;
 5246:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 5247:         foreach my $item (split(/:/,$$allroles{$role})) {
 5248:             if ($item ne '') {
 5249:                 my ($privilege,$restrictions)=split(/&/,$item);
 5250:                 if ($restrictions eq '') {
 5251:                     $thesepriv{$privilege}='F';
 5252:                 } elsif ($thesepriv{$privilege} ne 'F') {
 5253:                     $thesepriv{$privilege}.=$restrictions;
 5254:                 }
 5255:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 5256:             }
 5257:         }
 5258:         my $thesestr='';
 5259:         foreach my $priv (sort(keys(%thesepriv))) {
 5260: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 5261: 	}
 5262:         $userroles->{'user.priv.'.$role} = $thesestr;
 5263:     }
 5264:     return ($author,$adv);
 5265: }
 5266: 
 5267: sub role_status {
 5268:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 5269:     my @pwhere = ();
 5270:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 5271:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
 5272:         unless (!defined($$role) || $$role eq '') {
 5273:             $$where=join('.',@pwhere);
 5274:             $$trolecode=$$role.'.'.$$where;
 5275:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 5276:             $$tstatus='is';
 5277:             if ($$tstart && $$tstart>$update) {
 5278:                 $$tstatus='future';
 5279:                 if ($$tstart<$now) {
 5280:                     if ($$tstart && $$tstart>$refresh) {
 5281:                         if (($$where ne '') && ($$role ne '')) {
 5282:                             my (%allroles,%allgroups,$group_privs,
 5283:                                 %groups_roles,@rolecodes);
 5284:                             my %userroles = (
 5285:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 5286:                             );
 5287:                             @rolecodes = ('cm'); 
 5288:                             my $spec=$$role.'.'.$$where;
 5289:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 5290:                             if ($$role =~ /^cr\//) {
 5291:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 5292:                                 push(@rolecodes,'cr');
 5293:                             } elsif ($$role eq 'gr') {
 5294:                                 push(@rolecodes,$$role);
 5295:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 5296:                                                     $env{'user.name'});
 5297:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 5298:                                 (undef,my $group_privs) = split(/\//,$trole);
 5299:                                 $group_privs = &unescape($group_privs);
 5300:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 5301:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 5302:                                 &get_groups_roles($tdomain,$trest,
 5303:                                                   \%course_roles,\@rolecodes,
 5304:                                                   \%groups_roles);
 5305:                             } else {
 5306:                                 push(@rolecodes,$$role);
 5307:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 5308:                             }
 5309:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
 5310:                             &appenv(\%userroles,\@rolecodes);
 5311:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 5312:                         }
 5313:                     }
 5314:                     $$tstatus = 'is';
 5315:                 }
 5316:             }
 5317:             if ($$tend) {
 5318:                 if ($$tend<$update) {
 5319:                     $$tstatus='expired';
 5320:                 } elsif ($$tend<$now) {
 5321:                     $$tstatus='will_not';
 5322:                 }
 5323:             }
 5324:         }
 5325:     }
 5326: }
 5327: 
 5328: sub get_groups_roles {
 5329:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 5330:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 5331:                   (ref($rolecodes) eq 'ARRAY') && 
 5332:                   (ref($groups_roles) eq 'HASH')); 
 5333:     if (keys(%{$cdom_courseroles}) > 0) {
 5334:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 5335:         if ($cdom ne '' && $cnum ne '') {
 5336:             foreach my $key (keys(%{$cdom_courseroles})) {
 5337:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 5338:                     my $crsrole = $1;
 5339:                     my $crssec = $2;
 5340:                     if ($crsrole =~ /^cr/) {
 5341:                         unless (grep(/^cr$/,@{$rolecodes})) {
 5342:                             push(@{$rolecodes},'cr');
 5343:                         }
 5344:                     } else {
 5345:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 5346:                             push(@{$rolecodes},$crsrole);
 5347:                         }
 5348:                     }
 5349:                     my $rolekey = "$crsrole./$cdom/$cnum";
 5350:                     if ($crssec ne '') {
 5351:                         $rolekey .= "/$crssec";
 5352:                     }
 5353:                     $rolekey .= './';
 5354:                     $groups_roles->{$rolekey} = $rolecodes;
 5355:                 }
 5356:             }
 5357:         }
 5358:     }
 5359:     return;
 5360: }
 5361: 
 5362: sub delete_env_groupprivs {
 5363:     my ($where,$courseroles,$possroles) = @_;
 5364:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 5365:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 5366:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 5367:         %{$courseroles->{$udom}} =
 5368:             &get_my_roles('','','userroles',['active'],
 5369:                           $possroles,[$udom],1);
 5370:     }
 5371:     if (ref($courseroles->{$udom}) eq 'HASH') {
 5372:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 5373:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 5374:             my $area = '/'.$cdom.'/'.$cnum;
 5375:             my $privkey = "user.priv.$crsrole.$area";
 5376:             if ($crssec ne '') {
 5377:                 $privkey .= '/'.$crssec;
 5378:             }
 5379:             $privkey .= ".$area/$group";
 5380:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 5381:         }
 5382:     }
 5383:     return;
 5384: }
 5385: 
 5386: sub check_adhoc_privs {
 5387:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
 5388:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 5389:     my $setprivs;
 5390:     if ($env{$cckey}) {
 5391:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 5392:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 5393:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 5394:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 5395:             $setprivs = 1;
 5396:         }
 5397:     } else {
 5398:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 5399:         $setprivs = 1;
 5400:     }
 5401:     return $setprivs;
 5402: }
 5403: 
 5404: sub set_adhoc_privileges {
 5405: # role can be cc or ca
 5406:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
 5407:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 5408:     my $spec = $role.'.'.$area;
 5409:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 5410:                                   $env{'user.name'},1);
 5411:     my %ccrole = ();
 5412:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
 5413:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
 5414:     &appenv(\%userroles,[$role,'cm']);
 5415:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 5416:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
 5417:         &appenv( {'request.role'        => $spec,
 5418:                   'request.role.domain' => $dcdom,
 5419:                   'request.course.sec'  => ''
 5420:                  }
 5421:                );
 5422:         my $tadv=0;
 5423:         if (&allowed('adv') eq 'F') { $tadv=1; }
 5424:         &appenv({'request.role.adv'    => $tadv});
 5425:     }
 5426: }
 5427: 
 5428: # --------------------------------------------------------------- get interface
 5429: 
 5430: sub get {
 5431:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5432:    my $items='';
 5433:    foreach my $item (@$storearr) {
 5434:        $items.=&escape($item).'&';
 5435:    }
 5436:    $items=~s/\&$//;
 5437:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5438:    if (!$uname) { $uname=$env{'user.name'}; }
 5439:    my $uhome=&homeserver($uname,$udomain);
 5440: 
 5441:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 5442:    my @pairs=split(/\&/,$rep);
 5443:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 5444:      return @pairs;
 5445:    }
 5446:    my %returnhash=();
 5447:    my $i=0;
 5448:    foreach my $item (@$storearr) {
 5449:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 5450:       $i++;
 5451:    }
 5452:    return %returnhash;
 5453: }
 5454: 
 5455: # --------------------------------------------------------------- del interface
 5456: 
 5457: sub del {
 5458:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5459:    my $items='';
 5460:    foreach my $item (@$storearr) {
 5461:        $items.=&escape($item).'&';
 5462:    }
 5463: 
 5464:    $items=~s/\&$//;
 5465:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5466:    if (!$uname) { $uname=$env{'user.name'}; }
 5467:    my $uhome=&homeserver($uname,$udomain);
 5468:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 5469: }
 5470: 
 5471: # -------------------------------------------------------------- dump interface
 5472: 
 5473: sub unserialize {
 5474:     my ($rep, $escapedkeys) = @_;
 5475: 
 5476:     return {} if $rep =~ /^error/;
 5477: 
 5478:     my %returnhash=();
 5479: 	foreach my $item (split /\&/, $rep) {
 5480: 	    my ($key, $value) = split(/=/, $item, 2);
 5481: 	    $key = unescape($key) unless $escapedkeys;
 5482: 	    next if $key =~ /^error: 2 /;
 5483: 	    $returnhash{$key} = Apache::lonnet::thaw_unescape($value);
 5484: 	}
 5485:     #return %returnhash;
 5486:     return \%returnhash;
 5487: }        
 5488: 
 5489: # see Lond::dump_with_regexp
 5490: # if $escapedkeys hash keys won't get unescaped.
 5491: sub dump {
 5492:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
 5493:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5494:     if (!$uname) { $uname=$env{'user.name'}; }
 5495:     my $uhome=&homeserver($uname,$udomain);
 5496: 
 5497:     my $reply;
 5498:     if (grep { $_ eq $uhome } current_machine_ids()) {
 5499:         # user is hosted on this machine
 5500:         $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
 5501:                     $uname, $namespace, $regexp, $range)), $loncaparevs{$uhome});
 5502:         return %{unserialize($reply, $escapedkeys)};
 5503:     }
 5504:     if ($regexp) {
 5505: 	$regexp=&escape($regexp);
 5506:     } else {
 5507: 	$regexp='.';
 5508:     }
 5509:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 5510:     my @pairs=split(/\&/,$rep);
 5511:     my %returnhash=();
 5512:     if (!($rep =~ /^error/ )) {
 5513: 	foreach my $item (@pairs) {
 5514: 	    my ($key,$value)=split(/=/,$item,2);
 5515:         $key = unescape($key) unless $escapedkeys;
 5516:         #$key = &unescape($key);
 5517: 	    next if ($key =~ /^error: 2 /);
 5518: 	    $returnhash{$key}=&thaw_unescape($value);
 5519: 	}
 5520:     }
 5521:     return %returnhash;
 5522: }
 5523: 
 5524: 
 5525: # --------------------------------------------------------- dumpstore interface
 5526: 
 5527: sub dumpstore {
 5528:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 5529:    # same as dump but keys must be escaped. They may contain colon separated
 5530:    # lists of values that may themself contain colons (e.g. symbs).
 5531:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
 5532: }
 5533: 
 5534: # -------------------------------------------------------------- keys interface
 5535: 
 5536: sub getkeys {
 5537:    my ($namespace,$udomain,$uname)=@_;
 5538:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5539:    if (!$uname) { $uname=$env{'user.name'}; }
 5540:    my $uhome=&homeserver($uname,$udomain);
 5541:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 5542:    my @keyarray=();
 5543:    foreach my $key (split(/\&/,$rep)) {
 5544:       next if ($key =~ /^error: 2 /);
 5545:       push(@keyarray,&unescape($key));
 5546:    }
 5547:    return @keyarray;
 5548: }
 5549: 
 5550: # --------------------------------------------------------------- currentdump
 5551: sub currentdump {
 5552:    my ($courseid,$sdom,$sname)=@_;
 5553:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 5554:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 5555:    $sname    = $env{'user.name'}         if (! defined($sname));
 5556:    my $uhome = &homeserver($sname,$sdom);
 5557:    my $rep;
 5558: 
 5559:    if (grep { $_ eq $uhome } current_machine_ids()) {
 5560:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
 5561:                    $courseid)));
 5562:    } else {
 5563:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 5564:    }
 5565: 
 5566:    return if ($rep =~ /^(error:|no_such_host)/);
 5567:    #
 5568:    my %returnhash=();
 5569:    #
 5570:    if ($rep eq "unknown_cmd") { 
 5571:        # an old lond will not know currentdump
 5572:        # Do a dump and make it look like a currentdump
 5573:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 5574:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 5575:        my %hash = @tmp;
 5576:        @tmp=();
 5577:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 5578:    } else {
 5579:        my @pairs=split(/\&/,$rep);
 5580:        foreach my $pair (@pairs) {
 5581:            my ($key,$value)=split(/=/,$pair,2);
 5582:            my ($symb,$param) = split(/:/,$key);
 5583:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 5584:                                                         &thaw_unescape($value);
 5585:        }
 5586:    }
 5587:    return %returnhash;
 5588: }
 5589: 
 5590: sub convert_dump_to_currentdump{
 5591:     my %hash = %{shift()};
 5592:     my %returnhash;
 5593:     # Code ripped from lond, essentially.  The only difference
 5594:     # here is the unescaping done by lonnet::dump().  Conceivably
 5595:     # we might run in to problems with parameter names =~ /^v\./
 5596:     while (my ($key,$value) = each(%hash)) {
 5597:         my ($v,$symb,$param) = split(/:/,$key);
 5598: 	$symb  = &unescape($symb);
 5599: 	$param = &unescape($param);
 5600:         next if ($v eq 'version' || $symb eq 'keys');
 5601:         next if (exists($returnhash{$symb}) &&
 5602:                  exists($returnhash{$symb}->{$param}) &&
 5603:                  $returnhash{$symb}->{'v.'.$param} > $v);
 5604:         $returnhash{$symb}->{$param}=$value;
 5605:         $returnhash{$symb}->{'v.'.$param}=$v;
 5606:     }
 5607:     #
 5608:     # Remove all of the keys in the hashes which keep track of
 5609:     # the version of the parameter.
 5610:     while (my ($symb,$param_hash) = each(%returnhash)) {
 5611:         # use a foreach because we are going to delete from the hash.
 5612:         foreach my $key (keys(%$param_hash)) {
 5613:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 5614:         }
 5615:     }
 5616:     return \%returnhash;
 5617: }
 5618: 
 5619: # ------------------------------------------------------ critical inc interface
 5620: 
 5621: sub cinc {
 5622:     return &inc(@_,'critical');
 5623: }
 5624: 
 5625: # --------------------------------------------------------------- inc interface
 5626: 
 5627: sub inc {
 5628:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 5629:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5630:     if (!$uname) { $uname=$env{'user.name'}; }
 5631:     my $uhome=&homeserver($uname,$udomain);
 5632:     my $items='';
 5633:     if (! ref($store)) {
 5634:         # got a single value, so use that instead
 5635:         $items = &escape($store).'=&';
 5636:     } elsif (ref($store) eq 'SCALAR') {
 5637:         $items = &escape($$store).'=&';        
 5638:     } elsif (ref($store) eq 'ARRAY') {
 5639:         $items = join('=&',map {&escape($_);} @{$store});
 5640:     } elsif (ref($store) eq 'HASH') {
 5641:         while (my($key,$value) = each(%{$store})) {
 5642:             $items.= &escape($key).'='.&escape($value).'&';
 5643:         }
 5644:     }
 5645:     $items=~s/\&$//;
 5646:     if ($critical) {
 5647: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 5648:     } else {
 5649: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 5650:     }
 5651: }
 5652: 
 5653: # --------------------------------------------------------------- put interface
 5654: 
 5655: sub put {
 5656:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5657:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5658:    if (!$uname) { $uname=$env{'user.name'}; }
 5659:    my $uhome=&homeserver($uname,$udomain);
 5660:    my $items='';
 5661:    foreach my $item (keys(%$storehash)) {
 5662:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5663:    }
 5664:    $items=~s/\&$//;
 5665:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5666: }
 5667: 
 5668: # ------------------------------------------------------------ newput interface
 5669: 
 5670: sub newput {
 5671:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5672:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5673:    if (!$uname) { $uname=$env{'user.name'}; }
 5674:    my $uhome=&homeserver($uname,$udomain);
 5675:    my $items='';
 5676:    foreach my $key (keys(%$storehash)) {
 5677:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 5678:    }
 5679:    $items=~s/\&$//;
 5680:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 5681: }
 5682: 
 5683: # ---------------------------------------------------------  putstore interface
 5684: 
 5685: sub putstore {
 5686:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 5687:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5688:    if (!$uname) { $uname=$env{'user.name'}; }
 5689:    my $uhome=&homeserver($uname,$udomain);
 5690:    my $items='';
 5691:    foreach my $key (keys(%$storehash)) {
 5692:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 5693:    }
 5694:    $items=~s/\&$//;
 5695:    my $esc_symb=&escape($symb);
 5696:    my $esc_v=&escape($version);
 5697:    my $reply =
 5698:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 5699: 	      $uhome);
 5700:    if ($reply eq 'unknown_cmd') {
 5701:        # gfall back to way things use to be done
 5702:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 5703: 			    $uname);
 5704:    }
 5705:    return $reply;
 5706: }
 5707: 
 5708: sub old_putstore {
 5709:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 5710:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5711:     if (!$uname) { $uname=$env{'user.name'}; }
 5712:     my $uhome=&homeserver($uname,$udomain);
 5713:     my %newstorehash;
 5714:     foreach my $item (keys(%$storehash)) {
 5715: 	my $key = $version.':'.&escape($symb).':'.$item;
 5716: 	$newstorehash{$key} = $storehash->{$item};
 5717:     }
 5718:     my $items='';
 5719:     my %allitems = ();
 5720:     foreach my $item (keys(%newstorehash)) {
 5721: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 5722: 	    my $key = $1.':keys:'.$2;
 5723: 	    $allitems{$key} .= $3.':';
 5724: 	}
 5725: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 5726:     }
 5727:     foreach my $item (keys(%allitems)) {
 5728: 	$allitems{$item} =~ s/\:$//;
 5729: 	$items.= $item.'='.$allitems{$item}.'&';
 5730:     }
 5731:     $items=~s/\&$//;
 5732:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5733: }
 5734: 
 5735: # ------------------------------------------------------ critical put interface
 5736: 
 5737: sub cput {
 5738:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5739:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5740:    if (!$uname) { $uname=$env{'user.name'}; }
 5741:    my $uhome=&homeserver($uname,$udomain);
 5742:    my $items='';
 5743:    foreach my $item (keys(%$storehash)) {
 5744:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5745:    }
 5746:    $items=~s/\&$//;
 5747:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 5748: }
 5749: 
 5750: # -------------------------------------------------------------- eget interface
 5751: 
 5752: sub eget {
 5753:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5754:    my $items='';
 5755:    foreach my $item (@$storearr) {
 5756:        $items.=&escape($item).'&';
 5757:    }
 5758:    $items=~s/\&$//;
 5759:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5760:    if (!$uname) { $uname=$env{'user.name'}; }
 5761:    my $uhome=&homeserver($uname,$udomain);
 5762:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 5763:    my @pairs=split(/\&/,$rep);
 5764:    my %returnhash=();
 5765:    my $i=0;
 5766:    foreach my $item (@$storearr) {
 5767:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 5768:       $i++;
 5769:    }
 5770:    return %returnhash;
 5771: }
 5772: 
 5773: # ------------------------------------------------------------ tmpput interface
 5774: sub tmpput {
 5775:     my ($storehash,$server,$context)=@_;
 5776:     my $items='';
 5777:     foreach my $item (keys(%$storehash)) {
 5778: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5779:     }
 5780:     $items=~s/\&$//;
 5781:     if (defined($context)) {
 5782:         $items .= ':'.&escape($context);
 5783:     }
 5784:     return &reply("tmpput:$items",$server);
 5785: }
 5786: 
 5787: # ------------------------------------------------------------ tmpget interface
 5788: sub tmpget {
 5789:     my ($token,$server)=@_;
 5790:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 5791:     my $rep=&reply("tmpget:$token",$server);
 5792:     my %returnhash;
 5793:     foreach my $item (split(/\&/,$rep)) {
 5794: 	my ($key,$value)=split(/=/,$item);
 5795:         next if ($key =~ /^error: 2 /);
 5796: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 5797:     }
 5798:     return %returnhash;
 5799: }
 5800: 
 5801: # ------------------------------------------------------------ tmpdel interface
 5802: sub tmpdel {
 5803:     my ($token,$server)=@_;
 5804:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 5805:     return &reply("tmpdel:$token",$server);
 5806: }
 5807: 
 5808: # ------------------------------------------------------------ get_timebased_id 
 5809: 
 5810: sub get_timebased_id {
 5811:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
 5812:         $maxtries) = @_;
 5813:     my ($newid,$error,$dellock);
 5814:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
 5815:         return ('','ok','invalid call to get suffix');
 5816:     }
 5817: 
 5818: # set defaults for any optional args for which values were not supplied
 5819:     if ($who eq '') {
 5820:         $who = $env{'user.name'}.':'.$env{'user.domain'};
 5821:     }
 5822:     if (!$locktries) {
 5823:         $locktries = 3;
 5824:     }
 5825:     if (!$maxtries) {
 5826:         $maxtries = 10;
 5827:     }
 5828:     
 5829:     if (($cdom eq '') || ($cnum eq '')) {
 5830:         if ($env{'request.course.id'}) {
 5831:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5832:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5833:         }
 5834:         if (($cdom eq '') || ($cnum eq '')) {
 5835:             return ('','ok','call to get suffix not in course context');
 5836:         }
 5837:     }
 5838: 
 5839: # construct locking item
 5840:     my $lockhash = {
 5841:                       $prefix."\0".'locked_'.$keyid => $who,
 5842:                    };
 5843:     my $tries = 0;
 5844: 
 5845: # attempt to get lock on nohist_$namespace file
 5846:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 5847:     while (($gotlock ne 'ok') && $tries <$locktries) {
 5848:         $tries ++;
 5849:         sleep 1;
 5850:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 5851:     }
 5852: 
 5853: # attempt to get unique identifier, based on current timestamp
 5854:     if ($gotlock eq 'ok') {
 5855:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
 5856:         my $id = time;
 5857:         $newid = $id;
 5858:         my $idtries = 0;
 5859:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
 5860:             if ($idtype eq 'concat') {
 5861:                 $newid = $id.$idtries;
 5862:             } else {
 5863:                 $newid ++;
 5864:             }
 5865:             $idtries ++;
 5866:         }
 5867:         if (!exists($inuse{$prefix."\0".$newid})) {
 5868:             my %new_item =  (
 5869:                               $prefix."\0".$newid => $who,
 5870:                             );
 5871:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
 5872:                                                  $cdom,$cnum);
 5873:             if ($putresult ne 'ok') {
 5874:                 undef($newid);
 5875:                 $error = 'error saving new item: '.$putresult;
 5876:             }
 5877:         } else {
 5878:              $error = ('error: no unique suffix available for the new item ');
 5879:         }
 5880: #  remove lock
 5881:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
 5882:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
 5883:     } else {
 5884:         $error = "error: could not obtain lockfile\n";
 5885:         $dellock = 'ok';
 5886:     }
 5887:     return ($newid,$dellock,$error);
 5888: }
 5889: 
 5890: # -------------------------------------------------- portfolio access checking
 5891: 
 5892: sub portfolio_access {
 5893:     my ($requrl) = @_;
 5894:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 5895:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 5896:     if ($result) {
 5897:         my %setters;
 5898:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 5899:             my ($startblock,$endblock) =
 5900:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 5901:             if ($startblock && $endblock) {
 5902:                 return 'B';
 5903:             }
 5904:         } else {
 5905:             my ($startblock,$endblock) =
 5906:                 &Apache::loncommon::blockcheck(\%setters,'port');
 5907:             if ($startblock && $endblock) {
 5908:                 return 'B';
 5909:             }
 5910:         }
 5911:     }
 5912:     if ($result eq 'ok') {
 5913:        return 'F';
 5914:     } elsif ($result =~ /^[^:]+:guest_/) {
 5915:        return 'A';
 5916:     }
 5917:     return '';
 5918: }
 5919: 
 5920: sub get_portfolio_access {
 5921:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 5922: 
 5923:     if (!ref($access_hash)) {
 5924: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 5925: 	my %access_controls = &get_access_controls($current_perms,$group,
 5926: 						   $file_name);
 5927: 	$access_hash = $access_controls{$file_name};
 5928:     }
 5929: 
 5930:     my ($public,$guest,@domains,@users,@courses,@groups);
 5931:     my $now = time;
 5932:     if (ref($access_hash) eq 'HASH') {
 5933:         foreach my $key (keys(%{$access_hash})) {
 5934:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 5935:             if ($start > $now) {
 5936:                 next;
 5937:             }
 5938:             if ($end && $end<$now) {
 5939:                 next;
 5940:             }
 5941:             if ($scope eq 'public') {
 5942:                 $public = $key;
 5943:                 last;
 5944:             } elsif ($scope eq 'guest') {
 5945:                 $guest = $key;
 5946:             } elsif ($scope eq 'domains') {
 5947:                 push(@domains,$key);
 5948:             } elsif ($scope eq 'users') {
 5949:                 push(@users,$key);
 5950:             } elsif ($scope eq 'course') {
 5951:                 push(@courses,$key);
 5952:             } elsif ($scope eq 'group') {
 5953:                 push(@groups,$key);
 5954:             }
 5955:         }
 5956:         if ($public) {
 5957:             return 'ok';
 5958:         }
 5959:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 5960:             if ($guest) {
 5961:                 return $guest;
 5962:             }
 5963:         } else {
 5964:             if (@domains > 0) {
 5965:                 foreach my $domkey (@domains) {
 5966:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 5967:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 5968:                             return 'ok';
 5969:                         }
 5970:                     }
 5971:                 }
 5972:             }
 5973:             if (@users > 0) {
 5974:                 foreach my $userkey (@users) {
 5975:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 5976:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 5977:                             if (ref($item) eq 'HASH') {
 5978:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 5979:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 5980:                                     return 'ok';
 5981:                                 }
 5982:                             }
 5983:                         }
 5984:                     } 
 5985:                 }
 5986:             }
 5987:             my %roleshash;
 5988:             my @courses_and_groups = @courses;
 5989:             push(@courses_and_groups,@groups); 
 5990:             if (@courses_and_groups > 0) {
 5991:                 my (%allgroups,%allroles); 
 5992:                 my ($start,$end,$role,$sec,$group);
 5993:                 foreach my $envkey (%env) {
 5994:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 5995:                         my $cid = $2.'_'.$3; 
 5996:                         if ($1 eq 'gr') {
 5997:                             $group = $4;
 5998:                             $allgroups{$cid}{$group} = $env{$envkey};
 5999:                         } else {
 6000:                             if ($4 eq '') {
 6001:                                 $sec = 'none';
 6002:                             } else {
 6003:                                 $sec = $4;
 6004:                             }
 6005:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 6006:                         }
 6007:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 6008:                         my $cid = $2.'_'.$3;
 6009:                         if ($4 eq '') {
 6010:                             $sec = 'none';
 6011:                         } else {
 6012:                             $sec = $4;
 6013:                         }
 6014:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 6015:                     }
 6016:                 }
 6017:                 if (keys(%allroles) == 0) {
 6018:                     return;
 6019:                 }
 6020:                 foreach my $key (@courses_and_groups) {
 6021:                     my %content = %{$$access_hash{$key}};
 6022:                     my $cnum = $content{'number'};
 6023:                     my $cdom = $content{'domain'};
 6024:                     my $cid = $cdom.'_'.$cnum;
 6025:                     if (!exists($allroles{$cid})) {
 6026:                         next;
 6027:                     }    
 6028:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 6029:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 6030:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 6031:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 6032:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 6033:                         foreach my $role (keys(%{$allroles{$cid}})) {
 6034:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 6035:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 6036:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 6037:                                         if (grep/^all$/,@sections) {
 6038:                                             return 'ok';
 6039:                                         } else {
 6040:                                             if (grep/^$sec$/,@sections) {
 6041:                                                 return 'ok';
 6042:                                             }
 6043:                                         }
 6044:                                     }
 6045:                                 }
 6046:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 6047:                                     if (grep/^none$/,@groups) {
 6048:                                         return 'ok';
 6049:                                     }
 6050:                                 } else {
 6051:                                     if (grep/^all$/,@groups) {
 6052:                                         return 'ok';
 6053:                                     } 
 6054:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 6055:                                         if (grep/^$group$/,@groups) {
 6056:                                             return 'ok';
 6057:                                         }
 6058:                                     }
 6059:                                 } 
 6060:                             }
 6061:                         }
 6062:                     }
 6063:                 }
 6064:             }
 6065:             if ($guest) {
 6066:                 return $guest;
 6067:             }
 6068:         }
 6069:     }
 6070:     return;
 6071: }
 6072: 
 6073: sub course_group_datechecker {
 6074:     my ($dates,$now,$status) = @_;
 6075:     my ($start,$end) = split(/\./,$dates);
 6076:     if (!$start && !$end) {
 6077:         return 'ok';
 6078:     }
 6079:     if (grep/^active$/,@{$status}) {
 6080:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 6081:             return 'ok';
 6082:         }
 6083:     }
 6084:     if (grep/^previous$/,@{$status}) {
 6085:         if ($end > $now ) {
 6086:             return 'ok';
 6087:         }
 6088:     }
 6089:     if (grep/^future$/,@{$status}) {
 6090:         if ($start > $now) {
 6091:             return 'ok';
 6092:         }
 6093:     }
 6094:     return; 
 6095: }
 6096: 
 6097: sub parse_portfolio_url {
 6098:     my ($url) = @_;
 6099: 
 6100:     my ($type,$udom,$unum,$group,$file_name);
 6101:     
 6102:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 6103: 	$type = 1;
 6104:         $udom = $1;
 6105:         $unum = $2;
 6106:         $file_name = $3;
 6107:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 6108: 	$type = 2;
 6109:         $udom = $1;
 6110:         $unum = $2;
 6111:         $group = $3;
 6112:         $file_name = $3.'/'.$4;
 6113:     }
 6114:     if (wantarray) {
 6115: 	return ($type,$udom,$unum,$file_name,$group);
 6116:     }
 6117:     return $type;
 6118: }
 6119: 
 6120: sub is_portfolio_url {
 6121:     my ($url) = @_;
 6122:     return scalar(&parse_portfolio_url($url));
 6123: }
 6124: 
 6125: sub is_portfolio_file {
 6126:     my ($file) = @_;
 6127:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 6128:         return 1;
 6129:     }
 6130:     return;
 6131: }
 6132: 
 6133: sub usertools_access {
 6134:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 6135:     my ($access,%tools);
 6136:     if ($context eq '') {
 6137:         $context = 'tools';
 6138:     }
 6139:     if ($context eq 'requestcourses') {
 6140:         %tools = (
 6141:                       official   => 1,
 6142:                       unofficial => 1,
 6143:                       community  => 1,
 6144:                  );
 6145:     } elsif ($context eq 'requestauthor') {
 6146:         %tools = (
 6147:                       requestauthor => 1,
 6148:                  );
 6149:     } else {
 6150:         %tools = (
 6151:                       aboutme   => 1,
 6152:                       blog      => 1,
 6153:                       webdav    => 1,
 6154:                       portfolio => 1,
 6155:                  );
 6156:     }
 6157:     return if (!defined($tools{$tool}));
 6158: 
 6159:     if ((!defined($udom)) || (!defined($uname))) {
 6160:         $udom = $env{'user.domain'};
 6161:         $uname = $env{'user.name'};
 6162:     }
 6163: 
 6164:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 6165:         if ($action ne 'reload') {
 6166:             if ($context eq 'requestcourses') {
 6167:                 return $env{'environment.canrequest.'.$tool};
 6168:             } elsif ($context eq 'requestauthor') {
 6169:                 return $env{'environment.canrequest.author'};
 6170:             } else {
 6171:                 return $env{'environment.availabletools.'.$tool};
 6172:             }
 6173:         }
 6174:     }
 6175: 
 6176:     my ($toolstatus,$inststatus,$envkey);
 6177:     if ($context eq 'requestauthor') {
 6178:         $envkey = $context; 
 6179:     } else {
 6180:         $envkey = $context.'.'.$tool;
 6181:     }
 6182: 
 6183:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 6184:          ($action ne 'reload')) {
 6185:         $toolstatus = $env{'environment.'.$envkey};
 6186:         $inststatus = $env{'environment.inststatus'};
 6187:     } else {
 6188:         if (ref($userenvref) eq 'HASH') {
 6189:             $toolstatus = $userenvref->{$envkey};
 6190:             $inststatus = $userenvref->{'inststatus'};
 6191:         } else {
 6192:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 6193:             $toolstatus = $userenv{$envkey};
 6194:             $inststatus = $userenv{'inststatus'};
 6195:         }
 6196:     }
 6197: 
 6198:     if ($toolstatus ne '') {
 6199:         if ($toolstatus) {
 6200:             $access = 1;
 6201:         } else {
 6202:             $access = 0;
 6203:         }
 6204:         return $access;
 6205:     }
 6206: 
 6207:     my ($is_adv,%domdef);
 6208:     if (ref($is_advref) eq 'HASH') {
 6209:         $is_adv = $is_advref->{'is_adv'};
 6210:     } else {
 6211:         $is_adv = &is_advanced_user($udom,$uname);
 6212:     }
 6213:     if (ref($domdefref) eq 'HASH') {
 6214:         %domdef = %{$domdefref};
 6215:     } else {
 6216:         %domdef = &get_domain_defaults($udom);
 6217:     }
 6218:     if (ref($domdef{$tool}) eq 'HASH') {
 6219:         if ($is_adv) {
 6220:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 6221:                 if ($domdef{$tool}{'_LC_adv'}) { 
 6222:                     $access = 1;
 6223:                 } else {
 6224:                     $access = 0;
 6225:                 }
 6226:                 return $access;
 6227:             }
 6228:         }
 6229:         if ($inststatus ne '') {
 6230:             my ($hasaccess,$hasnoaccess);
 6231:             foreach my $affiliation (split(/:/,$inststatus)) {
 6232:                 if ($domdef{$tool}{$affiliation} ne '') { 
 6233:                     if ($domdef{$tool}{$affiliation}) {
 6234:                         $hasaccess = 1;
 6235:                     } else {
 6236:                         $hasnoaccess = 1;
 6237:                     }
 6238:                 }
 6239:             }
 6240:             if ($hasaccess || $hasnoaccess) {
 6241:                 if ($hasaccess) {
 6242:                     $access = 1;
 6243:                 } elsif ($hasnoaccess) {
 6244:                     $access = 0; 
 6245:                 }
 6246:                 return $access;
 6247:             }
 6248:         } else {
 6249:             if ($domdef{$tool}{'default'} ne '') {
 6250:                 if ($domdef{$tool}{'default'}) {
 6251:                     $access = 1;
 6252:                 } elsif ($domdef{$tool}{'default'} == 0) {
 6253:                     $access = 0;
 6254:                 }
 6255:                 return $access;
 6256:             }
 6257:         }
 6258:     } else {
 6259:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 6260:             $access = 1;
 6261:         } else {
 6262:             $access = 0;
 6263:         }
 6264:         return $access;
 6265:     }
 6266: }
 6267: 
 6268: sub is_course_owner {
 6269:     my ($cdom,$cnum,$udom,$uname) = @_;
 6270:     if (($udom eq '') || ($uname eq '')) {
 6271:         $udom = $env{'user.domain'};
 6272:         $uname = $env{'user.name'};
 6273:     }
 6274:     unless (($udom eq '') || ($uname eq '')) {
 6275:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 6276:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 6277:                 return 1;
 6278:             } else {
 6279:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 6280:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 6281:                     return 1;
 6282:                 }
 6283:             }
 6284:         }
 6285:     }
 6286:     return;
 6287: }
 6288: 
 6289: sub is_advanced_user {
 6290:     my ($udom,$uname) = @_;
 6291:     if ($udom ne '' && $uname ne '') {
 6292:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 6293:             if (wantarray) {
 6294:                 return ($env{'user.adv'},$env{'user.author'});
 6295:             } else {
 6296:                 return $env{'user.adv'};
 6297:             }
 6298:         }
 6299:     }
 6300:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 6301:     my %allroles;
 6302:     my ($is_adv,$is_author);
 6303:     foreach my $role (keys(%roleshash)) {
 6304:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 6305:         my $area = '/'.$tdomain.'/'.$trest;
 6306:         if ($sec ne '') {
 6307:             $area .= '/'.$sec;
 6308:         }
 6309:         if (($area ne '') && ($trole ne '')) {
 6310:             my $spec=$trole.'.'.$area;
 6311:             if ($trole =~ /^cr\//) {
 6312:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 6313:             } elsif ($trole ne 'gr') {
 6314:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 6315:             }
 6316:             if ($trole eq 'au') {
 6317:                 $is_author = 1;
 6318:             }
 6319:         }
 6320:     }
 6321:     foreach my $role (keys(%allroles)) {
 6322:         last if ($is_adv);
 6323:         foreach my $item (split(/:/,$allroles{$role})) {
 6324:             if ($item ne '') {
 6325:                 my ($privilege,$restrictions)=split(/&/,$item);
 6326:                 if ($privilege eq 'adv') {
 6327:                     $is_adv = 1;
 6328:                     last;
 6329:                 }
 6330:             }
 6331:         }
 6332:     }
 6333:     if (wantarray) {
 6334:         return ($is_adv,$is_author);
 6335:     }
 6336:     return $is_adv;
 6337: }
 6338: 
 6339: sub check_can_request {
 6340:     my ($dom,$can_request,$request_domains) = @_;
 6341:     my $canreq = 0;
 6342:     my ($types,$typename) = &Apache::loncommon::course_types();
 6343:     my @options = ('approval','validate','autolimit');
 6344:     my $optregex = join('|',@options);
 6345:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 6346:         foreach my $type (@{$types}) {
 6347:             if (&usertools_access($env{'user.name'},
 6348:                                   $env{'user.domain'},
 6349:                                   $type,undef,'requestcourses')) {
 6350:                 $canreq ++;
 6351:                 if (ref($request_domains) eq 'HASH') {
 6352:                     push(@{$request_domains->{$type}},$env{'user.domain'});
 6353:                 }
 6354:                 if ($dom eq $env{'user.domain'}) {
 6355:                     $can_request->{$type} = 1;
 6356:                 }
 6357:             }
 6358:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
 6359:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 6360:                 if (@curr > 0) {
 6361:                     foreach my $item (@curr) {
 6362:                         if (ref($request_domains) eq 'HASH') {
 6363:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 6364:                             if ($otherdom ne '') {
 6365:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 6366:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 6367:                                         push(@{$request_domains->{$type}},$otherdom);
 6368:                                     }
 6369:                                 } else {
 6370:                                     push(@{$request_domains->{$type}},$otherdom);
 6371:                                 }
 6372:                             }
 6373:                         }
 6374:                     }
 6375:                     unless($dom eq $env{'user.domain'}) {
 6376:                         $canreq ++;
 6377:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 6378:                             $can_request->{$type} = 1;
 6379:                         }
 6380:                     }
 6381:                 }
 6382:             }
 6383:         }
 6384:     }
 6385:     return $canreq;
 6386: }
 6387: 
 6388: # ---------------------------------------------- Custom access rule evaluation
 6389: 
 6390: sub customaccess {
 6391:     my ($priv,$uri)=@_;
 6392:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 6393:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 6394:     $udom = &LONCAPA::clean_domain($udom);
 6395:     $ucrs = &LONCAPA::clean_username($ucrs);
 6396:     my $access=0;
 6397:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 6398: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 6399: 	if ($type eq 'user') {
 6400: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 6401: 		my ($tdom,$tuname)=split(m{/},$scope);
 6402: 		if ($tdom) {
 6403: 		    if ($tdom ne $env{'user.domain'}) { next; }
 6404: 		}
 6405: 		if ($tuname) {
 6406: 		    if ($tuname ne $env{'user.name'}) { next; }
 6407: 		}
 6408: 		$access=($effect eq 'allow');
 6409: 		last;
 6410: 	    }
 6411: 	} else {
 6412: 	    if ($role) {
 6413: 		if ($role ne $urole) { next; }
 6414: 	    }
 6415: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 6416: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 6417: 		if ($tdom) {
 6418: 		    if ($tdom ne $udom) { next; }
 6419: 		}
 6420: 		if ($tcrs) {
 6421: 		    if ($tcrs ne $ucrs) { next; }
 6422: 		}
 6423: 		if ($tsec) {
 6424: 		    if ($tsec ne $usec) { next; }
 6425: 		}
 6426: 		$access=($effect eq 'allow');
 6427: 		last;
 6428: 	    }
 6429: 	    if ($realm eq '' && $role eq '') {
 6430: 		$access=($effect eq 'allow');
 6431: 	    }
 6432: 	}
 6433:     }
 6434:     return $access;
 6435: }
 6436: 
 6437: # ------------------------------------------------- Check for a user privilege
 6438: 
 6439: sub allowed {
 6440:     my ($priv,$uri,$symb,$role)=@_;
 6441:     my $ver_orguri=$uri;
 6442:     $uri=&deversion($uri);
 6443:     my $orguri=$uri;
 6444:     $uri=&declutter($uri);
 6445: 
 6446:     if ($priv eq 'evb') {
 6447: # Evade communication block restrictions for specified role in a course
 6448:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 6449:             return $1;
 6450:         } else {
 6451:             return;
 6452:         }
 6453:     }
 6454: 
 6455:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 6456: # Free bre access to adm and meta resources
 6457:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 6458: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 6459: 	&& ($priv eq 'bre')) {
 6460: 	return 'F';
 6461:     }
 6462: 
 6463: # Free bre access to user's own portfolio contents
 6464:     my ($space,$domain,$name,@dir)=split('/',$uri);
 6465:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 6466: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 6467:         my %setters;
 6468:         my ($startblock,$endblock) = 
 6469:             &Apache::loncommon::blockcheck(\%setters,'port');
 6470:         if ($startblock && $endblock) {
 6471:             return 'B';
 6472:         } else {
 6473:             return 'F';
 6474:         }
 6475:     }
 6476: 
 6477: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 6478:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 6479:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 6480:         if (exists($env{'request.course.id'})) {
 6481:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6482:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6483:             if (($domain eq $cdom) && ($name eq $cnum)) {
 6484:                 my $courseprivid=$env{'request.course.id'};
 6485:                 $courseprivid=~s/\_/\//;
 6486:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 6487:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 6488:                     return $1; 
 6489:                 } else {
 6490:                     if ($env{'request.course.sec'}) {
 6491:                         $courseprivid.='/'.$env{'request.course.sec'};
 6492:                     }
 6493:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 6494:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 6495:                         return $2;
 6496:                     }
 6497:                 }
 6498:             }
 6499:         }
 6500:     }
 6501: 
 6502: # Free bre to public access
 6503: 
 6504:     if ($priv eq 'bre') {
 6505:         my $copyright=&metadata($uri,'copyright');
 6506: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 6507:            return 'F'; 
 6508:         }
 6509:         if ($copyright eq 'priv') {
 6510:             $uri=~/([^\/]+)\/([^\/]+)\//;
 6511: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 6512: 		return '';
 6513:             }
 6514:         }
 6515:         if ($copyright eq 'domain') {
 6516:             $uri=~/([^\/]+)\/([^\/]+)\//;
 6517: 	    unless (($env{'user.domain'} eq $1) ||
 6518:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 6519: 		return '';
 6520:             }
 6521:         }
 6522:         if ($env{'request.role'}=~ /li\.\//) {
 6523:             # Library role, so allow browsing of resources in this domain.
 6524:             return 'F';
 6525:         }
 6526:         if ($copyright eq 'custom') {
 6527: 	    unless (&customaccess($priv,$uri)) { return ''; }
 6528:         }
 6529:     }
 6530:     # Domain coordinator is trying to create a course
 6531:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 6532:         # uri is the requested domain in this case.
 6533:         # comparison to 'request.role.domain' shows if the user has selected
 6534:         # a role of dc for the domain in question.
 6535:         return 'F' if ($uri eq $env{'request.role.domain'});
 6536:     }
 6537: 
 6538:     my $thisallowed='';
 6539:     my $statecond=0;
 6540:     my $courseprivid='';
 6541: 
 6542:     my $ownaccess;
 6543:     # Community Coordinator or Assistant Co-author browsing resource space.
 6544:     if (($priv eq 'bro') && ($env{'user.author'})) {
 6545:         if ($uri eq '') {
 6546:             $ownaccess = 1;
 6547:         } else {
 6548:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 6549:                 my $udom = $env{'user.domain'};
 6550:                 my $uname = $env{'user.name'};
 6551:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 6552:                     $ownaccess = 1;
 6553:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 6554:                     unless ($uri =~ m{\.\./}) {
 6555:                         $ownaccess = 1;
 6556:                     }
 6557:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 6558:                     my $now = time;
 6559:                     if ($uri =~ m{^([^/]+)/?$}) {
 6560:                         my $adom = $1;
 6561:                         foreach my $key (keys(%env)) {
 6562:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 6563:                                 my ($start,$end) = split('.',$env{$key});
 6564:                                 if (($now >= $start) && (!$end || $end < $now)) {
 6565:                                     $ownaccess = 1;
 6566:                                     last;
 6567:                                 }
 6568:                             }
 6569:                         }
 6570:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 6571:                         my $adom = $1;
 6572:                         my $aname = $2;
 6573:                         foreach my $role ('ca','aa') { 
 6574:                             if ($env{"user.role.$role./$adom/$aname"}) {
 6575:                                 my ($start,$end) =
 6576:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 6577:                                 if (($now >= $start) && (!$end || $end < $now)) {
 6578:                                     $ownaccess = 1;
 6579:                                     last;
 6580:                                 }
 6581:                             }
 6582:                         }
 6583:                     }
 6584:                 }
 6585:             }
 6586:         }
 6587:     }
 6588: 
 6589: # Course
 6590: 
 6591:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 6592:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6593:             $thisallowed.=$1;
 6594:         }
 6595:     }
 6596: 
 6597: # Domain
 6598: 
 6599:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 6600:        =~/\Q$priv\E\&([^\:]*)/) {
 6601:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6602:             $thisallowed.=$1;
 6603:         }
 6604:     }
 6605: 
 6606: # User who is not author or co-author might still be able to edit
 6607: # resource of an author in the domain (e.g., if Domain Coordinator).
 6608:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 6609:         (&allowed('mdc',$env{'request.course.id'}))) {
 6610:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 6611:             $thisallowed.=$1;
 6612:         }
 6613:     }
 6614: 
 6615: # Course: uri itself is a course
 6616:     my $courseuri=$uri;
 6617:     $courseuri=~s/\_(\d)/\/$1/;
 6618:     $courseuri=~s/^([^\/])/\/$1/;
 6619: 
 6620:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 6621:        =~/\Q$priv\E\&([^\:]*)/) {
 6622:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6623:             $thisallowed.=$1;
 6624:         }
 6625:     }
 6626: 
 6627: # URI is an uploaded document for this course, default permissions don't matter
 6628: # not allowing 'edit' access (editupload) to uploaded course docs
 6629:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 6630: 	$thisallowed='';
 6631:         my ($match)=&is_on_map($uri);
 6632:         if ($match) {
 6633:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 6634:                   =~/\Q$priv\E\&([^\:]*)/) {
 6635:                 my @blockers = &has_comm_blocking($priv,$symb,$uri);
 6636:                 if (@blockers > 0) {
 6637:                     $thisallowed = 'B';
 6638:                 } else {
 6639:                     $thisallowed.=$1;
 6640:                 }
 6641:             }
 6642:         } else {
 6643:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 6644:             if ($refuri) {
 6645:                 if ($refuri =~ m|^/adm/|) {
 6646:                     $thisallowed='F';
 6647:                 } else {
 6648:                     $refuri=&declutter($refuri);
 6649:                     my ($match) = &is_on_map($refuri);
 6650:                     if ($match) {
 6651:                         my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 6652:                         if (@blockers > 0) {
 6653:                             $thisallowed = 'B';
 6654:                         } else {
 6655:                             $thisallowed='F';
 6656:                         }
 6657:                     }
 6658:                 }
 6659:             }
 6660:         }
 6661:     }
 6662: 
 6663:     if ($priv eq 'bre'
 6664: 	&& $thisallowed ne 'F' 
 6665: 	&& $thisallowed ne '2'
 6666: 	&& &is_portfolio_url($uri)) {
 6667: 	$thisallowed = &portfolio_access($uri);
 6668:     }
 6669:     
 6670: # Full access at system, domain or course-wide level? Exit.
 6671:     if ($thisallowed=~/F/) {
 6672: 	return 'F';
 6673:     }
 6674: 
 6675: # If this is generating or modifying users, exit with special codes
 6676: 
 6677:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 6678: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 6679: 	    my ($audom,$auname)=split('/',$uri);
 6680: # no author name given, so this just checks on the general right to make a co-author in this domain
 6681: 	    unless ($auname) { return $thisallowed; }
 6682: # an author name is given, so we are about to actually make a co-author for a certain account
 6683: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 6684: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 6685: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 6686: 	}
 6687: 	return $thisallowed;
 6688:     }
 6689: #
 6690: # Gathered so far: system, domain and course wide privileges
 6691: #
 6692: # Course: See if uri or referer is an individual resource that is part of 
 6693: # the course
 6694: 
 6695:     if ($env{'request.course.id'}) {
 6696: 
 6697:        $courseprivid=$env{'request.course.id'};
 6698:        if ($env{'request.course.sec'}) {
 6699:           $courseprivid.='/'.$env{'request.course.sec'};
 6700:        }
 6701:        $courseprivid=~s/\_/\//;
 6702:        my $checkreferer=1;
 6703:        my ($match,$cond)=&is_on_map($uri);
 6704:        if ($match) {
 6705:            $statecond=$cond;
 6706:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 6707:                =~/\Q$priv\E\&([^\:]*)/) {
 6708:                my $value = $1;
 6709:                if ($priv eq 'bre') {
 6710:                    my @blockers = &has_comm_blocking($priv,$symb,$uri);
 6711:                    if (@blockers > 0) {
 6712:                        $thisallowed = 'B';
 6713:                    } else {
 6714:                        $thisallowed.=$value;
 6715:                    }
 6716:                } else {
 6717:                    $thisallowed.=$value;
 6718:                }
 6719:                $checkreferer=0;
 6720:            }
 6721:        }
 6722:        
 6723:        if ($checkreferer) {
 6724: 	  my $refuri=$env{'httpref.'.$orguri};
 6725:             unless ($refuri) {
 6726:                 foreach my $key (keys(%env)) {
 6727: 		    if ($key=~/^httpref\..*\*/) {
 6728: 			my $pattern=$key;
 6729:                         $pattern=~s/^httpref\.\/res\///;
 6730:                         $pattern=~s/\*/\[\^\/\]\+/g;
 6731:                         $pattern=~s/\//\\\//g;
 6732:                         if ($orguri=~/$pattern/) {
 6733: 			    $refuri=$env{$key};
 6734:                         }
 6735:                     }
 6736:                 }
 6737:             }
 6738: 
 6739:          if ($refuri) { 
 6740: 	  $refuri=&declutter($refuri);
 6741:           my ($match,$cond)=&is_on_map($refuri);
 6742:             if ($match) {
 6743:               my $refstatecond=$cond;
 6744:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 6745:                   =~/\Q$priv\E\&([^\:]*)/) {
 6746:                   my $value = $1;
 6747:                   if ($priv eq 'bre') {
 6748:                       my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 6749:                       if (@blockers > 0) {
 6750:                           $thisallowed = 'B';
 6751:                       } else {
 6752:                           $thisallowed.=$value;
 6753:                       }
 6754:                   } else {
 6755:                       $thisallowed.=$value;
 6756:                   }
 6757:                   $uri=$refuri;
 6758:                   $statecond=$refstatecond;
 6759:               }
 6760:           }
 6761:         }
 6762:        }
 6763:    }
 6764: 
 6765: #
 6766: # Gathered now: all privileges that could apply, and condition number
 6767: # 
 6768: #
 6769: # Full or no access?
 6770: #
 6771: 
 6772:     if ($thisallowed=~/F/) {
 6773: 	return 'F';
 6774:     }
 6775: 
 6776:     unless ($thisallowed) {
 6777:         return '';
 6778:     }
 6779: 
 6780: # Restrictions exist, deal with them
 6781: #
 6782: #   C:according to course preferences
 6783: #   R:according to resource settings
 6784: #   L:unless locked
 6785: #   X:according to user session state
 6786: #
 6787: 
 6788: # Possibly locked functionality, check all courses
 6789: # Locks might take effect only after 10 minutes cache expiration for other
 6790: # courses, and 2 minutes for current course
 6791: 
 6792:     my $envkey;
 6793:     if ($thisallowed=~/L/) {
 6794:         foreach $envkey (keys(%env)) {
 6795:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 6796:                my $courseid=$2;
 6797:                my $roleid=$1.'.'.$2;
 6798:                $courseid=~s/^\///;
 6799:                my $expiretime=600;
 6800:                if ($env{'request.role'} eq $roleid) {
 6801: 		  $expiretime=120;
 6802:                }
 6803: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 6804:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 6805:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 6806: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 6807:                }
 6808:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 6809:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 6810: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 6811:                        &log($env{'user.domain'},$env{'user.name'},
 6812:                             $env{'user.home'},
 6813:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 6814:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 6815:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 6816: 		       return '';
 6817:                    }
 6818:                }
 6819:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 6820:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 6821: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 6822:                        &log($env{'user.domain'},$env{'user.name'},
 6823:                             $env{'user.home'},
 6824:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 6825:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 6826:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 6827: 		       return '';
 6828:                    }
 6829:                }
 6830: 	   }
 6831:        }
 6832:     }
 6833:    
 6834: #
 6835: # Rest of the restrictions depend on selected course
 6836: #
 6837: 
 6838:     unless ($env{'request.course.id'}) {
 6839: 	if ($thisallowed eq 'A') {
 6840: 	    return 'A';
 6841:         } elsif ($thisallowed eq 'B') {
 6842:             return 'B';
 6843: 	} else {
 6844: 	    return '1';
 6845: 	}
 6846:     }
 6847: 
 6848: #
 6849: # Now user is definitely in a course
 6850: #
 6851: 
 6852: 
 6853: # Course preferences
 6854: 
 6855:    if ($thisallowed=~/C/) {
 6856:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 6857:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 6858:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 6859: 	   =~/\Q$rolecode\E/) {
 6860: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6861: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 6862: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 6863: 			$env{'request.course.id'});
 6864: 	   }
 6865:            return '';
 6866:        }
 6867: 
 6868:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 6869: 	   =~/\Q$unamedom\E/) {
 6870: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6871: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 6872: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 6873: 			$env{'request.course.id'});
 6874: 	   }
 6875:            return '';
 6876:        }
 6877:    }
 6878: 
 6879: # Resource preferences
 6880: 
 6881:    if ($thisallowed=~/R/) {
 6882:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 6883:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 6884: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6885: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 6886: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 6887: 	   }
 6888: 	   return '';
 6889:        }
 6890:    }
 6891: 
 6892: # Restricted by state or randomout?
 6893: 
 6894:    if ($thisallowed=~/X/) {
 6895:       if ($env{'acc.randomout'}) {
 6896: 	 if (!$symb) { $symb=&symbread($uri,1); }
 6897:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 6898:             return ''; 
 6899:          }
 6900:       }
 6901:       if (&condval($statecond)) {
 6902: 	 return '2';
 6903:       } else {
 6904:          return '';
 6905:       }
 6906:    }
 6907: 
 6908:     if ($thisallowed eq 'A') {
 6909: 	return 'A';
 6910:     } elsif ($thisallowed eq 'B') {
 6911:         return 'B';
 6912:     }
 6913:    return 'F';
 6914: }
 6915: 
 6916: # ------------------------------------------- Check construction space access
 6917: 
 6918: sub constructaccess {
 6919:     my ($url,$setpriv)=@_;
 6920: 
 6921: # We do not allow editing of previous versions of files
 6922:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
 6923: 
 6924: # Get username and domain from URL
 6925:     my ($ownername,$ownerdomain,$ownerhome);
 6926: 
 6927:     ($ownerdomain,$ownername) =
 6928:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
 6929: 
 6930: # The URL does not really point to any authorspace, forget it
 6931:     unless (($ownername) && ($ownerdomain)) { return ''; }
 6932: 
 6933: # Now we need to see if the user has access to the authorspace of
 6934: # $ownername at $ownerdomain
 6935: 
 6936:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
 6937: # Real author for this?
 6938:        $ownerhome = $env{'user.home'};
 6939:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
 6940:           return ($ownername,$ownerdomain,$ownerhome);
 6941:        }
 6942:     } else {
 6943: # Co-author for this?
 6944:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
 6945:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
 6946:             $ownerhome = &homeserver($ownername,$ownerdomain);
 6947:             return ($ownername,$ownerdomain,$ownerhome);
 6948:         }
 6949:     }
 6950: 
 6951: # We don't have any access right now. If we are not possibly going to do anything about this,
 6952: # we might as well leave
 6953:    unless ($setpriv) { return ''; }
 6954: 
 6955: # Backdoor access?
 6956:     my $allowed=&allowed('eco',$ownerdomain);
 6957: # Nope
 6958:     unless ($allowed) { return ''; }
 6959: # Looks like we may have access, but could be locked by the owner of the construction space
 6960:     if ($allowed eq 'U') {
 6961:         my %blocked=&get('environment',['domcoord.author'],
 6962:                          $ownerdomain,$ownername);
 6963: # Is blocked by owner
 6964:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
 6965:     }
 6966:     if (($allowed eq 'F') || ($allowed eq 'U')) {
 6967: # Grant temporary access
 6968:         my $then=$env{'user.login.time'};
 6969:         my $update=$env{'user.update.time'};
 6970:         if (!$update) { $update = $then; }
 6971:         my $refresh=$env{'user.refresh.time'};
 6972:         if (!$refresh) { $refresh = $update; }
 6973:         my $now = time;
 6974:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
 6975:                            $now,'ca','constructaccess');
 6976:         $ownerhome = &homeserver($ownername,$ownerdomain);
 6977:         return($ownername,$ownerdomain,$ownerhome);
 6978:     }
 6979: # No business here
 6980:     return '';
 6981: }
 6982: 
 6983: sub get_comm_blocks {
 6984:     my ($cdom,$cnum) = @_;
 6985:     if ($cdom eq '' || $cnum eq '') {
 6986:         return unless ($env{'request.course.id'});
 6987:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6988:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6989:     }
 6990:     my %commblocks;
 6991:     my $hashid=$cdom.'_'.$cnum;
 6992:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 6993:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 6994:         %commblocks = %{$blocksref};
 6995:     } else {
 6996:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 6997:         my $cachetime = 600;
 6998:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 6999:     }
 7000:     return %commblocks;
 7001: }
 7002: 
 7003: sub has_comm_blocking {
 7004:     my ($priv,$symb,$uri,$blocks) = @_;
 7005:     return unless ($env{'request.course.id'});
 7006:     return unless ($priv eq 'bre');
 7007:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 7008:     my %commblocks;
 7009:     if (ref($blocks) eq 'HASH') {
 7010:         %commblocks = %{$blocks};
 7011:     } else {
 7012:         %commblocks = &get_comm_blocks();
 7013:     }
 7014:     return unless (keys(%commblocks) > 0);
 7015:     if (!$symb) { $symb=&symbread($uri,1); }
 7016:     my ($map,$resid,undef)=&decode_symb($symb);
 7017:     my %tocheck = (
 7018:                     maps      => $map,
 7019:                     resources => $symb,
 7020:                   );
 7021:     my @blockers;
 7022:     my $now = time;
 7023:     my $navmap = Apache::lonnavmaps::navmap->new();
 7024:     foreach my $block (keys(%commblocks)) {
 7025:         if ($block =~ /^(\d+)____(\d+)$/) {
 7026:             my ($start,$end) = ($1,$2);
 7027:             if ($start <= $now && $end >= $now) {
 7028:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 7029:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 7030:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 7031:                             if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
 7032:                                 unless (grep(/^\Q$block\E$/,@blockers)) {
 7033:                                     push(@blockers,$block);
 7034:                                 }
 7035:                             }
 7036:                         }
 7037:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 7038:                             if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
 7039:                                 unless (grep(/^\Q$block\E$/,@blockers)) {  
 7040:                                     push(@blockers,$block);
 7041:                                 }
 7042:                             }
 7043:                         }
 7044:                     }
 7045:                 }
 7046:             }
 7047:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 7048:             my $item = $1;
 7049:             my @to_test;
 7050:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 7051:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 7052:                     my $check_interval;
 7053:                     if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
 7054:                         my @interval;
 7055:                         my $type = 'map';
 7056:                         if ($item eq 'course') {
 7057:                             $type = 'course';
 7058:                             @interval=&EXT("resource.0.interval");
 7059:                         } else {
 7060:                             if ($item =~ /___\d+___/) {
 7061:                                 $type = 'resource';
 7062:                                 @interval=&EXT("resource.0.interval",$item);
 7063:                                 if (ref($navmap)) {                        
 7064:                                     my $res = $navmap->getBySymb($item); 
 7065:                                     push(@to_test,$res);
 7066:                                 }
 7067:                             } else {
 7068:                                 my $mapsymb = &symbread($item,1);
 7069:                                 if ($mapsymb) {
 7070:                                     if (ref($navmap)) {
 7071:                                         my $mapres = $navmap->getBySymb($mapsymb);
 7072:                                         @to_test = $mapres->retrieveResources($mapres,undef,0,1);
 7073:                                         foreach my $res (@to_test) {
 7074:                                             my $symb = $res->symb();
 7075:                                             next if ($symb eq $mapsymb);
 7076:                                             if ($symb ne '') {
 7077:                                                 @interval=&EXT("resource.0.interval",$symb);
 7078:                                                 last;
 7079:                                             }
 7080:                                         }
 7081:                                     }
 7082:                                 }
 7083:                             }
 7084:                         }
 7085:                         if ($interval[0] =~ /\d+/) {
 7086:                             my $first_access;
 7087:                             if ($type eq 'resource') {
 7088:                                 $first_access=&get_first_access($interval[1],$item);
 7089:                             } elsif ($type eq 'map') {
 7090:                                 $first_access=&get_first_access($interval[1],undef,$item);
 7091:                             } else {
 7092:                                 $first_access=&get_first_access($interval[1]);
 7093:                             }
 7094:                             if ($first_access) {
 7095:                                 my $timesup = $first_access+$interval[0];
 7096:                                 if ($timesup > $now) {
 7097:                                     foreach my $res (@to_test) {
 7098:                                         if ($res->is_problem()) {
 7099:                                             if ($res->completable()) {
 7100:                                                 unless (grep(/^\Q$block\E$/,@blockers)) {
 7101:                                                     push(@blockers,$block);
 7102:                                                 }
 7103:                                                 last;
 7104:                                             }
 7105:                                         }
 7106:                                     }
 7107:                                 }
 7108:                             }
 7109:                         }
 7110:                     }
 7111:                 }
 7112:             }
 7113:         }
 7114:     }
 7115:     return @blockers;
 7116: }
 7117: 
 7118: sub check_docs_block {
 7119:     my ($docsblock,$tocheck) =@_;
 7120:     if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
 7121:         return;
 7122:     }
 7123:     if (ref($docsblock->{'maps'}) eq 'HASH') {
 7124:         if ($tocheck->{'maps'}) {
 7125:             if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
 7126:                 return 1;
 7127:             }
 7128:         }
 7129:     }
 7130:     if (ref($docsblock->{'resources'}) eq 'HASH') {
 7131:         if ($tocheck->{'resources'}) {
 7132:             if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
 7133:                 return 1;
 7134:             }
 7135:         }
 7136:     }
 7137:     return;
 7138: }
 7139: 
 7140: #
 7141: #   Removes the versino from a URI and
 7142: #   splits it in to its filename and path to the filename.
 7143: #   Seems like File::Basename could have done this more clearly.
 7144: #   Parameters:
 7145: #      $uri   - input URI
 7146: #   Returns:
 7147: #     Two element list consisting of 
 7148: #     $pathname  - the URI up to and excluding the trailing /
 7149: #     $filename  - The part of the URI following the last /
 7150: #  NOTE:
 7151: #    Another realization of this is simply:
 7152: #    use File::Basename;
 7153: #    ...
 7154: #    $uri = shift;
 7155: #    $filename = basename($uri);
 7156: #    $path     = dirname($uri);
 7157: #    return ($filename, $path);
 7158: #
 7159: #     The implementation below is probably faster however.
 7160: #
 7161: sub split_uri_for_cond {
 7162:     my $uri=&deversion(&declutter(shift));
 7163:     my @uriparts=split(/\//,$uri);
 7164:     my $filename=pop(@uriparts);
 7165:     my $pathname=join('/',@uriparts);
 7166:     return ($pathname,$filename);
 7167: }
 7168: # --------------------------------------------------- Is a resource on the map?
 7169: 
 7170: sub is_on_map {
 7171:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 7172:     #Trying to find the conditional for the file
 7173:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 7174: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 7175:     if ($match) {
 7176: 	return (1,$1);
 7177:     } else {
 7178: 	return (0,0);
 7179:     }
 7180: }
 7181: 
 7182: # --------------------------------------------------------- Get symb from alias
 7183: 
 7184: sub get_symb_from_alias {
 7185:     my $symb=shift;
 7186:     my ($map,$resid,$url)=&decode_symb($symb);
 7187: # Already is a symb
 7188:     if ($url) { return $symb; }
 7189: # Must be an alias
 7190:     my $aliassymb='';
 7191:     my %bighash;
 7192:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7193:                             &GDBM_READER(),0640)) {
 7194:         my $rid=$bighash{'mapalias_'.$symb};
 7195: 	if ($rid) {
 7196: 	    my ($mapid,$resid)=split(/\./,$rid);
 7197: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 7198: 				    $resid,$bighash{'src_'.$rid});
 7199: 	}
 7200:         untie %bighash;
 7201:     }
 7202:     return $aliassymb;
 7203: }
 7204: 
 7205: # ----------------------------------------------------------------- Define Role
 7206: 
 7207: sub definerole {
 7208:   if (allowed('mcr','/')) {
 7209:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 7210:     foreach my $role (split(':',$sysrole)) {
 7211: 	my ($crole,$cqual)=split(/\&/,$role);
 7212:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 7213:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 7214: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 7215:                return "refused:s:$crole&$cqual"; 
 7216:             }
 7217:         }
 7218:     }
 7219:     foreach my $role (split(':',$domrole)) {
 7220: 	my ($crole,$cqual)=split(/\&/,$role);
 7221:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 7222:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 7223: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 7224:                return "refused:d:$crole&$cqual"; 
 7225:             }
 7226:         }
 7227:     }
 7228:     foreach my $role (split(':',$courole)) {
 7229: 	my ($crole,$cqual)=split(/\&/,$role);
 7230:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 7231:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 7232: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 7233:                return "refused:c:$crole&$cqual"; 
 7234:             }
 7235:         }
 7236:     }
 7237:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 7238:                 "$env{'user.domain'}:$env{'user.name'}:".
 7239: 	        "rolesdef_$rolename=".
 7240:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 7241:     return reply($command,$env{'user.home'});
 7242:   } else {
 7243:     return 'refused';
 7244:   }
 7245: }
 7246: 
 7247: # ---------------- Make a metadata query against the network of library servers
 7248: 
 7249: sub metadata_query {
 7250:     my ($query,$custom,$customshow,$server_array)=@_;
 7251:     my %rhash;
 7252:     my %libserv = &all_library();
 7253:     my @server_list = (defined($server_array) ? @$server_array
 7254:                                               : keys(%libserv) );
 7255:     for my $server (@server_list) {
 7256: 	unless ($custom or $customshow) {
 7257: 	    my $reply=&reply("querysend:".&escape($query),$server);
 7258: 	    $rhash{$server}=$reply;
 7259: 	}
 7260: 	else {
 7261: 	    my $reply=&reply("querysend:".&escape($query).':'.
 7262: 			     &escape($custom).':'.&escape($customshow),
 7263: 			     $server);
 7264: 	    $rhash{$server}=$reply;
 7265: 	}
 7266:     }
 7267:     return \%rhash;
 7268: }
 7269: 
 7270: # ----------------------------------------- Send log queries and wait for reply
 7271: 
 7272: sub log_query {
 7273:     my ($uname,$udom,$query,%filters)=@_;
 7274:     my $uhome=&homeserver($uname,$udom);
 7275:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 7276:     my $uhost=&hostname($uhome);
 7277:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 7278:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 7279:                        $uhome);
 7280:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 7281:     return get_query_reply($queryid);
 7282: }
 7283: 
 7284: # -------------------------- Update MySQL table for portfolio file
 7285: 
 7286: sub update_portfolio_table {
 7287:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 7288:     if ($group ne '') {
 7289:         $file_name =~s /^\Q$group\E//;
 7290:     }
 7291:     my $homeserver = &homeserver($uname,$udom);
 7292:     my $queryid=
 7293:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 7294:                ':'.&escape($file_name).':'.$action,$homeserver);
 7295:     my $reply = &get_query_reply($queryid);
 7296:     return $reply;
 7297: }
 7298: 
 7299: # -------------------------- Update MySQL allusers table
 7300: 
 7301: sub update_allusers_table {
 7302:     my ($uname,$udom,$names) = @_;
 7303:     my $homeserver = &homeserver($uname,$udom);
 7304:     my $queryid=
 7305:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 7306:                'lastname='.&escape($names->{'lastname'}).'%%'.
 7307:                'firstname='.&escape($names->{'firstname'}).'%%'.
 7308:                'middlename='.&escape($names->{'middlename'}).'%%'.
 7309:                'generation='.&escape($names->{'generation'}).'%%'.
 7310:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 7311:                'id='.&escape($names->{'id'}),$homeserver);
 7312:     return;
 7313: }
 7314: 
 7315: # ------- Request retrieval of institutional classlists for course(s)
 7316: 
 7317: sub fetch_enrollment_query {
 7318:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 7319:     my $homeserver;
 7320:     my $maxtries = 1;
 7321:     if ($context eq 'automated') {
 7322:         $homeserver = $perlvar{'lonHostID'};
 7323:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 7324:     } else {
 7325:         $homeserver = &homeserver($cnum,$dom);
 7326:     }
 7327:     my $host=&hostname($homeserver);
 7328:     my $cmd = '';
 7329:     foreach my $affiliate (keys(%{$affiliatesref})) {
 7330:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 7331:     }
 7332:     $cmd =~ s/%%$//;
 7333:     $cmd = &escape($cmd);
 7334:     my $query = 'fetchenrollment';
 7335:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 7336:     unless ($queryid=~/^\Q$host\E\_/) { 
 7337:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 7338:         return 'error: '.$queryid;
 7339:     }
 7340:     my $reply = &get_query_reply($queryid);
 7341:     my $tries = 1;
 7342:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 7343:         $reply = &get_query_reply($queryid);
 7344:         $tries ++;
 7345:     }
 7346:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 7347:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 7348:     } else {
 7349:         my @responses = split(/:/,$reply);
 7350:         if ($homeserver eq $perlvar{'lonHostID'}) {
 7351:             foreach my $line (@responses) {
 7352:                 my ($key,$value) = split(/=/,$line,2);
 7353:                 $$replyref{$key} = $value;
 7354:             }
 7355:         } else {
 7356:             my $pathname = LONCAPA::tempdir();
 7357:             foreach my $line (@responses) {
 7358:                 my ($key,$value) = split(/=/,$line);
 7359:                 $$replyref{$key} = $value;
 7360:                 if ($value > 0) {
 7361:                     foreach my $item (@{$$affiliatesref{$key}}) {
 7362:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 7363:                         my $destname = $pathname.'/'.$filename;
 7364:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 7365:                         if ($xml_classlist =~ /^error/) {
 7366:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 7367:                         } else {
 7368:                             if ( open(FILE,">$destname") ) {
 7369:                                 print FILE &unescape($xml_classlist);
 7370:                                 close(FILE);
 7371:                             } else {
 7372:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 7373:                             }
 7374:                         }
 7375:                     }
 7376:                 }
 7377:             }
 7378:         }
 7379:         return 'ok';
 7380:     }
 7381:     return 'error';
 7382: }
 7383: 
 7384: sub get_query_reply {
 7385:     my $queryid=shift;
 7386:     my $replyfile=LONCAPA::tempdir().$queryid;
 7387:     my $reply='';
 7388:     for (1..100) {
 7389: 	sleep 2;
 7390:         if (-e $replyfile.'.end') {
 7391: 	    if (open(my $fh,$replyfile)) {
 7392: 		$reply = join('',<$fh>);
 7393: 		close($fh);
 7394: 	   } else { return 'error: reply_file_error'; }
 7395:            return &unescape($reply);
 7396: 	}
 7397:     }
 7398:     return 'timeout:'.$queryid;
 7399: }
 7400: 
 7401: sub courselog_query {
 7402: #
 7403: # possible filters:
 7404: # url: url or symb
 7405: # username
 7406: # domain
 7407: # action: view, submit, grade
 7408: # start: timestamp
 7409: # end: timestamp
 7410: #
 7411:     my (%filters)=@_;
 7412:     unless ($env{'request.course.id'}) { return 'no_course'; }
 7413:     if ($filters{'url'}) {
 7414: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 7415:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 7416:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 7417:     }
 7418:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7419:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7420:     return &log_query($cname,$cdom,'courselog',%filters);
 7421: }
 7422: 
 7423: sub userlog_query {
 7424: #
 7425: # possible filters:
 7426: # action: log check role
 7427: # start: timestamp
 7428: # end: timestamp
 7429: #
 7430:     my ($uname,$udom,%filters)=@_;
 7431:     return &log_query($uname,$udom,'userlog',%filters);
 7432: }
 7433: 
 7434: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 7435: 
 7436: sub auto_run {
 7437:     my ($cnum,$cdom) = @_;
 7438:     my $response = 0;
 7439:     my $settings;
 7440:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 7441:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 7442:         $settings = $domconfig{'autoenroll'};
 7443:         if ($settings->{'run'} eq '1') {
 7444:             $response = 1;
 7445:         }
 7446:     } else {
 7447:         my $homeserver;
 7448:         if (&is_course($cdom,$cnum)) {
 7449:             $homeserver = &homeserver($cnum,$cdom);
 7450:         } else {
 7451:             $homeserver = &domain($cdom,'primary');
 7452:         }
 7453:         if ($homeserver ne 'no_host') {
 7454:             $response = &reply('autorun:'.$cdom,$homeserver);
 7455:         }
 7456:     }
 7457:     return $response;
 7458: }
 7459: 
 7460: sub auto_get_sections {
 7461:     my ($cnum,$cdom,$inst_coursecode) = @_;
 7462:     my $homeserver;
 7463:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 7464:         $homeserver = &homeserver($cnum,$cdom);
 7465:     }
 7466:     if (!defined($homeserver)) { 
 7467:         if ($cdom =~ /^$match_domain$/) {
 7468:             $homeserver = &domain($cdom,'primary');
 7469:         }
 7470:     }
 7471:     my @secs;
 7472:     if (defined($homeserver)) {
 7473:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 7474:         unless ($response eq 'refused') {
 7475:             @secs = split(/:/,$response);
 7476:         }
 7477:     }
 7478:     return @secs;
 7479: }
 7480: 
 7481: sub auto_new_course {
 7482:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 7483:     my $homeserver = &homeserver($cnum,$cdom);
 7484:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 7485:     return $response;
 7486: }
 7487: 
 7488: sub auto_validate_courseID {
 7489:     my ($cnum,$cdom,$inst_course_id) = @_;
 7490:     my $homeserver = &homeserver($cnum,$cdom);
 7491:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 7492:     return $response;
 7493: }
 7494: 
 7495: sub auto_validate_instcode {
 7496:     my ($cnum,$cdom,$instcode,$owner) = @_;
 7497:     my ($homeserver,$response);
 7498:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 7499:         $homeserver = &homeserver($cnum,$cdom);
 7500:     }
 7501:     if (!defined($homeserver)) {
 7502:         if ($cdom =~ /^$match_domain$/) {
 7503:             $homeserver = &domain($cdom,'primary');
 7504:         }
 7505:     }
 7506:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 7507:                         &escape($instcode).':'.&escape($owner),$homeserver));
 7508:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
 7509:     return ($outcome,$description,$defaultcredits);
 7510: }
 7511: 
 7512: sub auto_create_password {
 7513:     my ($cnum,$cdom,$authparam,$udom) = @_;
 7514:     my ($homeserver,$response);
 7515:     my $create_passwd = 0;
 7516:     my $authchk = '';
 7517:     if ($udom =~ /^$match_domain$/) {
 7518:         $homeserver = &domain($udom,'primary');
 7519:     }
 7520:     if ($homeserver eq '') {
 7521:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 7522:             $homeserver = &homeserver($cnum,$cdom);
 7523:         }
 7524:     }
 7525:     if ($homeserver eq '') {
 7526:         $authchk = 'nodomain';
 7527:     } else {
 7528:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 7529:         if ($response eq 'refused') {
 7530:             $authchk = 'refused';
 7531:         } else {
 7532:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 7533:         }
 7534:     }
 7535:     return ($authparam,$create_passwd,$authchk);
 7536: }
 7537: 
 7538: sub auto_photo_permission {
 7539:     my ($cnum,$cdom,$students) = @_;
 7540:     my $homeserver = &homeserver($cnum,$cdom);
 7541:     my ($outcome,$perm_reqd,$conditions) = 
 7542: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 7543:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7544: 	return (undef,undef);
 7545:     }
 7546:     return ($outcome,$perm_reqd,$conditions);
 7547: }
 7548: 
 7549: sub auto_checkphotos {
 7550:     my ($uname,$udom,$pid) = @_;
 7551:     my $homeserver = &homeserver($uname,$udom);
 7552:     my ($result,$resulttype);
 7553:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 7554: 				   &escape($uname).':'.&escape($pid),
 7555: 				   $homeserver));
 7556:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7557: 	return (undef,undef);
 7558:     }
 7559:     if ($outcome) {
 7560:         ($result,$resulttype) = split(/:/,$outcome);
 7561:     } 
 7562:     return ($result,$resulttype);
 7563: }
 7564: 
 7565: sub auto_photochoice {
 7566:     my ($cnum,$cdom) = @_;
 7567:     my $homeserver = &homeserver($cnum,$cdom);
 7568:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 7569: 						       &escape($cdom),
 7570: 						       $homeserver)));
 7571:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7572: 	return (undef,undef);
 7573:     }
 7574:     return ($update,$comment);
 7575: }
 7576: 
 7577: sub auto_photoupdate {
 7578:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 7579:     my $homeserver = &homeserver($cnum,$dom);
 7580:     my $host=&hostname($homeserver);
 7581:     my $cmd = '';
 7582:     my $maxtries = 1;
 7583:     foreach my $affiliate (keys(%{$affiliatesref})) {
 7584:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 7585:     }
 7586:     $cmd =~ s/%%$//;
 7587:     $cmd = &escape($cmd);
 7588:     my $query = 'institutionalphotos';
 7589:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 7590:     unless ($queryid=~/^\Q$host\E\_/) {
 7591:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 7592:         return 'error: '.$queryid;
 7593:     }
 7594:     my $reply = &get_query_reply($queryid);
 7595:     my $tries = 1;
 7596:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 7597:         $reply = &get_query_reply($queryid);
 7598:         $tries ++;
 7599:     }
 7600:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 7601:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 7602:     } else {
 7603:         my @responses = split(/:/,$reply);
 7604:         my $outcome = shift(@responses); 
 7605:         foreach my $item (@responses) {
 7606:             my ($key,$value) = split(/=/,$item);
 7607:             $$photo{$key} = $value;
 7608:         }
 7609:         return $outcome;
 7610:     }
 7611:     return 'error';
 7612: }
 7613: 
 7614: sub auto_instcode_format {
 7615:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 7616: 	$cat_order) = @_;
 7617:     my $courses = '';
 7618:     my @homeservers;
 7619:     if ($caller eq 'global') {
 7620: 	my %servers = &get_servers($codedom,'library');
 7621: 	foreach my $tryserver (keys(%servers)) {
 7622: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7623: 		push(@homeservers,$tryserver);
 7624: 	    }
 7625:         }
 7626:     } elsif ($caller eq 'requests') {
 7627:         if ($codedom =~ /^$match_domain$/) {
 7628:             my $chome = &domain($codedom,'primary');
 7629:             unless ($chome eq 'no_host') {
 7630:                 push(@homeservers,$chome);
 7631:             }
 7632:         }
 7633:     } else {
 7634:         push(@homeservers,&homeserver($caller,$codedom));
 7635:     }
 7636:     foreach my $code (keys(%{$instcodes})) {
 7637:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 7638:     }
 7639:     chop($courses);
 7640:     my $ok_response = 0;
 7641:     my $response;
 7642:     while (@homeservers > 0 && $ok_response == 0) {
 7643:         my $server = shift(@homeservers); 
 7644:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 7645:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 7646:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 7647: 		split(/:/,$response);
 7648:             %{$codes} = (%{$codes},&str2hash($codes_str));
 7649:             push(@{$codetitles},&str2array($codetitles_str));
 7650:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 7651:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 7652:             $ok_response = 1;
 7653:         }
 7654:     }
 7655:     if ($ok_response) {
 7656:         return 'ok';
 7657:     } else {
 7658:         return $response;
 7659:     }
 7660: }
 7661: 
 7662: sub auto_instcode_defaults {
 7663:     my ($domain,$returnhash,$code_order) = @_;
 7664:     my @homeservers;
 7665: 
 7666:     my %servers = &get_servers($domain,'library');
 7667:     foreach my $tryserver (keys(%servers)) {
 7668: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7669: 	    push(@homeservers,$tryserver);
 7670: 	}
 7671:     }
 7672: 
 7673:     my $response;
 7674:     foreach my $server (@homeservers) {
 7675:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 7676:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 7677: 	
 7678: 	foreach my $pair (split(/\&/,$response)) {
 7679: 	    my ($name,$value)=split(/\=/,$pair);
 7680: 	    if ($name eq 'code_order') {
 7681: 		@{$code_order} = split(/\&/,&unescape($value));
 7682: 	    } else {
 7683: 		$returnhash->{&unescape($name)}=&unescape($value);
 7684: 	    }
 7685: 	}
 7686: 	return 'ok';
 7687:     }
 7688: 
 7689:     return $response;
 7690: }
 7691: 
 7692: sub auto_possible_instcodes {
 7693:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 7694:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 7695:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 7696:         return;
 7697:     }
 7698:     my (@homeservers,$uhome);
 7699:     if (defined(&domain($domain,'primary'))) {
 7700:         $uhome=&domain($domain,'primary');
 7701:         push(@homeservers,&domain($domain,'primary'));
 7702:     } else {
 7703:         my %servers = &get_servers($domain,'library');
 7704:         foreach my $tryserver (keys(%servers)) {
 7705:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7706:                 push(@homeservers,$tryserver);
 7707:             }
 7708:         }
 7709:     }
 7710:     my $response;
 7711:     foreach my $server (@homeservers) {
 7712:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 7713:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 7714:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 7715:             split(':',$response);
 7716:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 7717:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 7718:         foreach my $item (split('&',$cat_title)) {   
 7719:             my ($name,$value)=split('=',$item);
 7720:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 7721:         }
 7722:         foreach my $item (split('&',$cat_order)) {
 7723:             my ($name,$value)=split('=',$item);
 7724:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 7725:         }
 7726:         return 'ok';
 7727:     }
 7728:     return $response;
 7729: }
 7730: 
 7731: sub auto_courserequest_checks {
 7732:     my ($dom) = @_;
 7733:     my ($homeserver,%validations);
 7734:     if ($dom =~ /^$match_domain$/) {
 7735:         $homeserver = &domain($dom,'primary');
 7736:     }
 7737:     unless ($homeserver eq 'no_host') {
 7738:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 7739:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 7740:             my @items = split(/&/,$response);
 7741:             foreach my $item (@items) {
 7742:                 my ($key,$value) = split('=',$item);
 7743:                 $validations{&unescape($key)} = &thaw_unescape($value);
 7744:             }
 7745:         }
 7746:     }
 7747:     return %validations; 
 7748: }
 7749: 
 7750: sub auto_courserequest_validation {
 7751:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
 7752:     my ($homeserver,$response);
 7753:     if ($dom =~ /^$match_domain$/) {
 7754:         $homeserver = &domain($dom,'primary');
 7755:     }
 7756:     unless ($homeserver eq 'no_host') {  
 7757:           
 7758:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 7759:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 7760:                                     ':'.&escape($instcode).':'.&escape($instseclist),
 7761:                                     $homeserver));
 7762:     }
 7763:     return $response;
 7764: }
 7765: 
 7766: sub auto_validate_class_sec {
 7767:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 7768:     my $homeserver = &homeserver($cnum,$cdom);
 7769:     my $ownerlist;
 7770:     if (ref($owners) eq 'ARRAY') {
 7771:         $ownerlist = join(',',@{$owners});
 7772:     } else {
 7773:         $ownerlist = $owners;
 7774:     }
 7775:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 7776:                         &escape($ownerlist).':'.$cdom,$homeserver);
 7777:     return $response;
 7778: }
 7779: 
 7780: # ------------------------------------------------------- Course Group routines
 7781: 
 7782: sub get_coursegroups {
 7783:     my ($cdom,$cnum,$group,$namespace) = @_;
 7784:     return(&dump($namespace,$cdom,$cnum,$group));
 7785: }
 7786: 
 7787: sub modify_coursegroup {
 7788:     my ($cdom,$cnum,$groupsettings) = @_;
 7789:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 7790: }
 7791: 
 7792: sub toggle_coursegroup_status {
 7793:     my ($cdom,$cnum,$group,$action) = @_;
 7794:     my ($from_namespace,$to_namespace);
 7795:     if ($action eq 'delete') {
 7796:         $from_namespace = 'coursegroups';
 7797:         $to_namespace = 'deleted_groups';
 7798:     } else {
 7799:         $from_namespace = 'deleted_groups';
 7800:         $to_namespace = 'coursegroups';
 7801:     }
 7802:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 7803:     if (my $tmp = &error(%curr_group)) {
 7804:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 7805:         return ('read error',$tmp);
 7806:     } else {
 7807:         my %savedsettings = %curr_group; 
 7808:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 7809:         my $deloutcome;
 7810:         if ($result eq 'ok') {
 7811:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 7812:         } else {
 7813:             return ('write error',$result);
 7814:         }
 7815:         if ($deloutcome eq 'ok') {
 7816:             return 'ok';
 7817:         } else {
 7818:             return ('delete error',$deloutcome);
 7819:         }
 7820:     }
 7821: }
 7822: 
 7823: sub modify_group_roles {
 7824:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 7825:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 7826:     my $role = 'gr/'.&escape($userprivs);
 7827:     my ($uname,$udom) = split(/:/,$user);
 7828:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 7829:     if ($result eq 'ok') {
 7830:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 7831:     }
 7832:     return $result;
 7833: }
 7834: 
 7835: sub modify_coursegroup_membership {
 7836:     my ($cdom,$cnum,$membership) = @_;
 7837:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 7838:     return $result;
 7839: }
 7840: 
 7841: sub get_active_groups {
 7842:     my ($udom,$uname,$cdom,$cnum) = @_;
 7843:     my $now = time;
 7844:     my %groups = ();
 7845:     foreach my $key (keys(%env)) {
 7846:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 7847:             my ($start,$end) = split(/\./,$env{$key});
 7848:             if (($end!=0) && ($end<$now)) { next; }
 7849:             if (($start!=0) && ($start>$now)) { next; }
 7850:             if ($1 eq $cdom && $2 eq $cnum) {
 7851:                 $groups{$3} = $env{$key} ;
 7852:             }
 7853:         }
 7854:     }
 7855:     return %groups;
 7856: }
 7857: 
 7858: sub get_group_membership {
 7859:     my ($cdom,$cnum,$group) = @_;
 7860:     return(&dump('groupmembership',$cdom,$cnum,$group));
 7861: }
 7862: 
 7863: sub get_users_groups {
 7864:     my ($udom,$uname,$courseid) = @_;
 7865:     my @usersgroups;
 7866:     my $cachetime=1800;
 7867: 
 7868:     my $hashid="$udom:$uname:$courseid";
 7869:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 7870:     if (defined($cached)) {
 7871:         @usersgroups = split(/:/,$grouplist);
 7872:     } else {  
 7873:         $grouplist = '';
 7874:         my $courseurl = &courseid_to_courseurl($courseid);
 7875:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 7876:         my $access_end = $env{'course.'.$courseid.
 7877:                               '.default_enrollment_end_date'};
 7878:         my $now = time;
 7879:         foreach my $key (keys(%roleshash)) {
 7880:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 7881:                 my $group = $1;
 7882:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 7883:                     my $start = $2;
 7884:                     my $end = $1;
 7885:                     if ($start == -1) { next; } # deleted from group
 7886:                     if (($start!=0) && ($start>$now)) { next; }
 7887:                     if (($end!=0) && ($end<$now)) {
 7888:                         if ($access_end && $access_end < $now) {
 7889:                             if ($access_end - $end < 86400) {
 7890:                                 push(@usersgroups,$group);
 7891:                             }
 7892:                         }
 7893:                         next;
 7894:                     }
 7895:                     push(@usersgroups,$group);
 7896:                 }
 7897:             }
 7898:         }
 7899:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 7900:         $grouplist = join(':',@usersgroups);
 7901:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 7902:     }
 7903:     return @usersgroups;
 7904: }
 7905: 
 7906: sub devalidate_getgroups_cache {
 7907:     my ($udom,$uname,$cdom,$cnum)=@_;
 7908:     my $courseid = $cdom.'_'.$cnum;
 7909: 
 7910:     my $hashid="$udom:$uname:$courseid";
 7911:     &devalidate_cache_new('getgroups',$hashid);
 7912: }
 7913: 
 7914: # ------------------------------------------------------------------ Plain Text
 7915: 
 7916: sub plaintext {
 7917:     my ($short,$type,$cid,$forcedefault) = @_;
 7918:     if ($short =~ m{^cr/}) {
 7919: 	return (split('/',$short))[-1];
 7920:     }
 7921:     if (!defined($cid)) {
 7922:         $cid = $env{'request.course.id'};
 7923:     }
 7924:     my %rolenames = (
 7925:                       Course    => 'std',
 7926:                       Community => 'alt1',
 7927:                     );
 7928:     if ($cid ne '') {
 7929:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 7930:             unless ($forcedefault) {
 7931:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 7932:                 &Apache::lonlocal::mt_escape(\$roletext);
 7933:                 return &Apache::lonlocal::mt($roletext);
 7934:             }
 7935:         }
 7936:     }
 7937:     if ((defined($type)) && (defined($rolenames{$type})) &&
 7938:         (defined($rolenames{$type})) && 
 7939:         (defined($prp{$short}{$rolenames{$type}}))) {
 7940:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 7941:     } elsif ($cid ne '') {
 7942:         my $crstype = $env{'course.'.$cid.'.type'};
 7943:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
 7944:             (defined($prp{$short}{$rolenames{$crstype}}))) {
 7945:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
 7946:         }
 7947:     }
 7948:     return &Apache::lonlocal::mt($prp{$short}{'std'});
 7949: }
 7950: 
 7951: # ----------------------------------------------------------------- Assign Role
 7952: 
 7953: sub assignrole {
 7954:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 7955:         $context)=@_;
 7956:     my $mrole;
 7957:     if ($role =~ /^cr\//) {
 7958:         my $cwosec=$url;
 7959:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 7960: 	unless (&allowed('ccr',$cwosec)) {
 7961:            my $refused = 1;
 7962:            if ($context eq 'requestcourses') {
 7963:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 7964:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
 7965:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
 7966:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 7967:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 7968:                            if ($crsenv{'internal.courseowner'} eq
 7969:                                $env{'user.name'}.':'.$env{'user.domain'}) {
 7970:                                $refused = '';
 7971:                            }
 7972:                        }
 7973:                    }
 7974:                }
 7975:            }
 7976:            if ($refused) {
 7977:                &logthis('Refused custom assignrole: '.
 7978:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
 7979:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
 7980:                return 'refused';
 7981:            }
 7982:         }
 7983:         $mrole='cr';
 7984:     } elsif ($role =~ /^gr\//) {
 7985:         my $cwogrp=$url;
 7986:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 7987:         unless (&allowed('mdg',$cwogrp)) {
 7988:             &logthis('Refused group assignrole: '.
 7989:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 7990:                     $env{'user.name'}.' at '.$env{'user.domain'});
 7991:             return 'refused';
 7992:         }
 7993:         $mrole='gr';
 7994:     } else {
 7995:         my $cwosec=$url;
 7996:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 7997:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 7998:             my $refused;
 7999:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 8000:                 if (!(&allowed('c'.$role,$url))) {
 8001:                     $refused = 1;
 8002:                 }
 8003:             } else {
 8004:                 $refused = 1;
 8005:             }
 8006:             if ($refused) {
 8007:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 8008:                 if (!$selfenroll && $context eq 'course') {
 8009:                     my %crsenv;
 8010:                     if ($role eq 'cc' || $role eq 'co') {
 8011:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 8012:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
 8013:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
 8014:                                 if ($crsenv{'internal.courseowner'} eq 
 8015:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 8016:                                     $refused = '';
 8017:                                 }
 8018:                             }
 8019:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
 8020:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
 8021:                                 if ($crsenv{'internal.courseowner'} eq 
 8022:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 8023:                                     $refused = '';
 8024:                                 }
 8025:                             }
 8026:                         }
 8027:                     }
 8028:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 8029:                     $refused = '';
 8030:                 } elsif ($context eq 'requestcourses') {
 8031:                     my @possroles = ('st','ta','ep','in','cc','co');
 8032:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
 8033:                         my $wrongcc;
 8034:                         if ($cnum =~ /^$match_community$/) {
 8035:                             $wrongcc = 1 if ($role eq 'cc');
 8036:                         } else {
 8037:                             $wrongcc = 1 if ($role eq 'co');
 8038:                         }
 8039:                         unless ($wrongcc) {
 8040:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 8041:                             if ($crsenv{'internal.courseowner'} eq 
 8042:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
 8043:                                 $refused = '';
 8044:                             }
 8045:                         }
 8046:                     }
 8047:                 } elsif ($context eq 'requestauthor') {
 8048:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
 8049:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
 8050:                         if ($env{'environment.requestauthor'} eq 'automatic') {
 8051:                             $refused = '';
 8052:                         } else {
 8053:                             my %domdefaults = &get_domain_defaults($udom);
 8054:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
 8055:                                 my $checkbystatus;
 8056:                                 if ($env{'user.adv'}) { 
 8057:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
 8058:                                     if ($disposition eq 'automatic') {
 8059:                                         $refused = '';
 8060:                                     } elsif ($disposition eq '') {
 8061:                                         $checkbystatus = 1;
 8062:                                     } 
 8063:                                 } else {
 8064:                                     $checkbystatus = 1;
 8065:                                 }
 8066:                                 if ($checkbystatus) {
 8067:                                     if ($env{'environment.inststatus'}) {
 8068:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
 8069:                                         foreach my $type (@inststatuses) {
 8070:                                             if (($type ne '') &&
 8071:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
 8072:                                                 $refused = '';
 8073:                                             }
 8074:                                         }
 8075:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
 8076:                                         $refused = '';
 8077:                                     }
 8078:                                 }
 8079:                             }
 8080:                         }
 8081:                     }
 8082:                 }
 8083:                 if ($refused) {
 8084:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 8085:                              ' '.$role.' '.$end.' '.$start.' by '.
 8086: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 8087:                     return 'refused';
 8088:                 }
 8089:             }
 8090:         } elsif ($role eq 'au') {
 8091:             if ($url ne '/'.$udom.'/') {
 8092:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
 8093:                          ' to assign author role for '.$uname.':'.$udom.
 8094:                          ' in domain: '.$url.' refused (wrong domain).');
 8095:                 return 'refused';
 8096:             }
 8097:         }
 8098:         $mrole=$role;
 8099:     }
 8100:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 8101:                 "$udom:$uname:$url".'_'."$mrole=$role";
 8102:     if ($end) { $command.='_'.$end; }
 8103:     if ($start) {
 8104: 	if ($end) { 
 8105:            $command.='_'.$start; 
 8106:         } else {
 8107:            $command.='_0_'.$start;
 8108:         }
 8109:     }
 8110:     my $origstart = $start;
 8111:     my $origend = $end;
 8112:     my $delflag;
 8113: # actually delete
 8114:     if ($deleteflag) {
 8115: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 8116: # modify command to delete the role
 8117:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 8118:                 "$udom:$uname:$url".'_'."$mrole";
 8119: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 8120: # set start and finish to negative values for userrolelog
 8121:            $start=-1;
 8122:            $end=-1;
 8123:            $delflag = 1;
 8124:         }
 8125:     }
 8126: # send command
 8127:     my $answer=&reply($command,&homeserver($uname,$udom));
 8128: # log new user role if status is ok
 8129:     if ($answer eq 'ok') {
 8130: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 8131:         if (($role eq 'cc') || ($role eq 'in') ||
 8132:             ($role eq 'ep') || ($role eq 'ad') ||
 8133:             ($role eq 'ta') || ($role eq 'st') ||
 8134:             ($role=~/^cr/) || ($role eq 'gr') ||
 8135:             ($role eq 'co')) {
 8136: # for course roles, perform group memberships changes triggered by role change.
 8137:             unless ($role =~ /^gr/) {
 8138:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 8139:                                                  $origstart,$selfenroll,$context);
 8140:             }
 8141:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 8142:                            $selfenroll,$context);
 8143:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
 8144:                  ($role eq 'au') || ($role eq 'dc')) {
 8145:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 8146:                            $context);
 8147:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
 8148:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 8149:                              $context); 
 8150:         }
 8151:         if ($role eq 'cc') {
 8152:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
 8153:         }
 8154:     }
 8155:     return $answer;
 8156: }
 8157: 
 8158: sub autoupdate_coowners {
 8159:     my ($url,$end,$start,$uname,$udom) = @_;
 8160:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
 8161:     if (($cdom ne '') && ($cnum ne '')) {
 8162:         my $now = time;
 8163:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
 8164:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
 8165:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
 8166:             my $instcode = $coursehash{'internal.coursecode'};
 8167:             if ($instcode ne '') {
 8168:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
 8169:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
 8170:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
 8171:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
 8172:                         if ($result eq 'valid') {
 8173:                             if ($coursehash{'internal.co-owners'}) {
 8174:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 8175:                                     push(@newcoowners,$coowner);
 8176:                                 }
 8177:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
 8178:                                     push(@newcoowners,$uname.':'.$udom);
 8179:                                 }
 8180:                                 @newcoowners = sort(@newcoowners);
 8181:                             } else {
 8182:                                 push(@newcoowners,$uname.':'.$udom);
 8183:                             }
 8184:                         } else {
 8185:                             if ($coursehash{'internal.co-owners'}) {
 8186:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 8187:                                     unless ($coowner eq $uname.':'.$udom) {
 8188:                                         push(@newcoowners,$coowner);
 8189:                                     }
 8190:                                 }
 8191:                                 unless (@newcoowners > 0) {
 8192:                                     $delcoowners = 1;
 8193:                                     $coowners = '';
 8194:                                 }
 8195:                             }
 8196:                         }
 8197:                         if (@newcoowners || $delcoowners) {
 8198:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
 8199:                                             $delcoowners,@newcoowners);
 8200:                         }
 8201:                     }
 8202:                 }
 8203:             }
 8204:         }
 8205:     }
 8206: }
 8207: 
 8208: sub store_coowners {
 8209:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
 8210:     my $cid = $cdom.'_'.$cnum;
 8211:     my ($coowners,$delresult,$putresult);
 8212:     if (@newcoowners) {
 8213:         $coowners = join(',',@newcoowners);
 8214:         my %coownershash = (
 8215:                             'internal.co-owners' => $coowners,
 8216:                            );
 8217:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
 8218:         if ($putresult eq 'ok') {
 8219:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
 8220:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
 8221:             }
 8222:         }
 8223:     }
 8224:     if ($delcoowners) {
 8225:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
 8226:         if ($delresult eq 'ok') {
 8227:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
 8228:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
 8229:             }
 8230:         }
 8231:     }
 8232:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
 8233:         my %crsinfo =
 8234:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 8235:         if (ref($crsinfo{$cid}) eq 'HASH') {
 8236:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
 8237:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
 8238:         }
 8239:     }
 8240: }
 8241: 
 8242: # -------------------------------------------------- Modify user authentication
 8243: # Overrides without validation
 8244: 
 8245: sub modifyuserauth {
 8246:     my ($udom,$uname,$umode,$upass)=@_;
 8247:     my $uhome=&homeserver($uname,$udom);
 8248:     unless (&allowed('mau',$udom)) { return 'refused'; }
 8249:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 8250:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 8251:              ' in domain '.$env{'request.role.domain'});  
 8252:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 8253: 		     &escape($upass),$uhome);
 8254:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 8255:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 8256:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 8257:     &log($udom,,$uname,$uhome,
 8258:         'Authentication changed by '.$env{'user.domain'}.', '.
 8259:                                      $env{'user.name'}.', '.$umode.
 8260:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 8261:     unless ($reply eq 'ok') {
 8262:         &logthis('Authentication mode error: '.$reply);
 8263: 	return 'error: '.$reply;
 8264:     }   
 8265:     return 'ok';
 8266: }
 8267: 
 8268: # --------------------------------------------------------------- Modify a user
 8269: 
 8270: sub modifyuser {
 8271:     my ($udom,    $uname, $uid,
 8272:         $umode,   $upass, $first,
 8273:         $middle,  $last,  $gene,
 8274:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
 8275:     $udom= &LONCAPA::clean_domain($udom);
 8276:     $uname=&LONCAPA::clean_username($uname);
 8277:     my $showcandelete = 'none';
 8278:     if (ref($candelete) eq 'ARRAY') {
 8279:         if (@{$candelete} > 0) {
 8280:             $showcandelete = join(', ',@{$candelete});
 8281:         }
 8282:     }
 8283:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 8284:              $umode.', '.$first.', '.$middle.', '.
 8285: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
 8286:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 8287:                                      ' desiredhome not specified'). 
 8288:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 8289:              ' in domain '.$env{'request.role.domain'});
 8290:     my $uhome=&homeserver($uname,$udom,'true');
 8291:     my $newuser;
 8292:     if ($uhome eq 'no_host') {
 8293:         $newuser = 1;
 8294:     }
 8295: # ----------------------------------------------------------------- Create User
 8296:     if (($uhome eq 'no_host') && 
 8297: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 8298:         my $unhome='';
 8299:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 8300:             $unhome = $desiredhome;
 8301: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 8302: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 8303:         } else { # load balancing routine for determining $unhome
 8304:             my $loadm=10000000;
 8305: 	    my %servers = &get_servers($udom,'library');
 8306: 	    foreach my $tryserver (keys(%servers)) {
 8307: 		my $answer=reply('load',$tryserver);
 8308: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 8309: 		    $loadm=$answer;
 8310: 		    $unhome=$tryserver;
 8311: 		}
 8312: 	    }
 8313:         }
 8314:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 8315: 	    return 'error: unable to find a home server for '.$uname.
 8316:                    ' in domain '.$udom;
 8317:         }
 8318:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 8319:                          &escape($upass),$unhome);
 8320: 	unless ($reply eq 'ok') {
 8321:             return 'error: '.$reply;
 8322:         }   
 8323:         $uhome=&homeserver($uname,$udom,'true');
 8324:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 8325: 	    return 'error: unable verify users home machine.';
 8326:         }
 8327:     }   # End of creation of new user
 8328: # ---------------------------------------------------------------------- Add ID
 8329:     if ($uid) {
 8330:        $uid=~tr/A-Z/a-z/;
 8331:        my %uidhash=&idrget($udom,$uname);
 8332:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 8333:          && (!$forceid)) {
 8334: 	  unless ($uid eq $uidhash{$uname}) {
 8335: 	      return 'error: user id "'.$uid.'" does not match '.
 8336:                   'current user id "'.$uidhash{$uname}.'".';
 8337:           }
 8338:        } else {
 8339: 	  &idput($udom,($uname => $uid));
 8340:        }
 8341:     }
 8342: # -------------------------------------------------------------- Add names, etc
 8343:     my @tmp=&get('environment',
 8344: 		   ['firstname','middlename','lastname','generation','id',
 8345:                     'permanentemail','inststatus'],
 8346: 		   $udom,$uname);
 8347:     my (%names,%oldnames);
 8348:     if ($tmp[0] =~ m/^error:.*/) { 
 8349:         %names=(); 
 8350:     } else {
 8351:         %names = @tmp;
 8352:         %oldnames = %names;
 8353:     }
 8354: #
 8355: # If name, email and/or uid are blank (e.g., because an uploaded file
 8356: # of users did not contain them), do not overwrite existing values
 8357: # unless field is in $candelete array ref.  
 8358: #
 8359: 
 8360:     my @fields = ('firstname','middlename','lastname','generation',
 8361:                   'permanentemail','id');
 8362:     my %newvalues;
 8363:     if (ref($candelete) eq 'ARRAY') {
 8364:         foreach my $field (@fields) {
 8365:             if (grep(/^\Q$field\E$/,@{$candelete})) {
 8366:                 if ($field eq 'firstname') {
 8367:                     $names{$field} = $first;
 8368:                 } elsif ($field eq 'middlename') {
 8369:                     $names{$field} = $middle;
 8370:                 } elsif ($field eq 'lastname') {
 8371:                     $names{$field} = $last;
 8372:                 } elsif ($field eq 'generation') { 
 8373:                     $names{$field} = $gene;
 8374:                 } elsif ($field eq 'permanentemail') {
 8375:                     $names{$field} = $email;
 8376:                 } elsif ($field eq 'id') {
 8377:                     $names{$field}  = $uid;
 8378:                 }
 8379:             }
 8380:         }
 8381:     }
 8382:     if ($first)  { $names{'firstname'}  = $first; }
 8383:     if (defined($middle)) { $names{'middlename'} = $middle; }
 8384:     if ($last)   { $names{'lastname'}   = $last; }
 8385:     if (defined($gene))   { $names{'generation'} = $gene; }
 8386:     if ($email) {
 8387:        $email=~s/[^\w\@\.\-\,]//gs;
 8388:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 8389:     }
 8390:     if ($uid) { $names{'id'}  = $uid; }
 8391:     if (defined($inststatus)) {
 8392:         $names{'inststatus'} = '';
 8393:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
 8394:         if (ref($usertypes) eq 'HASH') {
 8395:             my @okstatuses; 
 8396:             foreach my $item (split(/:/,$inststatus)) {
 8397:                 if (defined($usertypes->{$item})) {
 8398:                     push(@okstatuses,$item);  
 8399:                 }
 8400:             }
 8401:             if (@okstatuses) {
 8402:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
 8403:             }
 8404:         }
 8405:     }
 8406:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
 8407:                  $umode.', '.$first.', '.$middle.', '.
 8408:                  $last.', '.$gene.', '.$email.', '.$inststatus;
 8409:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 8410:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 8411:     } else {
 8412:         $logmsg .= ' during self creation';
 8413:     }
 8414:     my $changed;
 8415:     if ($newuser) {
 8416:         $changed = 1;
 8417:     } else {
 8418:         foreach my $field (@fields) {
 8419:             if ($names{$field} ne $oldnames{$field}) {
 8420:                 $changed = 1;
 8421:                 last;
 8422:             }
 8423:         }
 8424:     }
 8425:     unless ($changed) {
 8426:         $logmsg = 'No changes in user information needed for: '.$logmsg;
 8427:         &logthis($logmsg);
 8428:         return 'ok';
 8429:     }
 8430:     my $reply = &put('environment', \%names, $udom,$uname);
 8431:     if ($reply ne 'ok') { 
 8432:         return 'error: '.$reply;
 8433:     }
 8434:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
 8435:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
 8436:     }
 8437:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 8438:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 8439:     $logmsg = 'Success modifying user '.$logmsg;
 8440:     &logthis($logmsg);
 8441:     return 'ok';
 8442: }
 8443: 
 8444: # -------------------------------------------------------------- Modify student
 8445: 
 8446: sub modifystudent {
 8447:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 8448:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 8449:         $selfenroll,$context,$inststatus,$credits)=@_;
 8450:     if (!$cid) {
 8451: 	unless ($cid=$env{'request.course.id'}) {
 8452: 	    return 'not_in_class';
 8453: 	}
 8454:     }
 8455: # --------------------------------------------------------------- Make the user
 8456:     my $reply=&modifyuser
 8457: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 8458:          $desiredhome,$email,$inststatus);
 8459:     unless ($reply eq 'ok') { return $reply; }
 8460:     # This will cause &modify_student_enrollment to get the uid from the
 8461:     # students environment
 8462:     $uid = undef if (!$forceid);
 8463:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 8464:                                         $gene,$usec,$end,$start,$type,$locktype,
 8465:                                         $cid,$selfenroll,$context,$credits);
 8466:     return $reply;
 8467: }
 8468: 
 8469: sub modify_student_enrollment {
 8470:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
 8471:         $locktype,$cid,$selfenroll,$context,$credits) = @_;
 8472:     my ($cdom,$cnum,$chome);
 8473:     if (!$cid) {
 8474: 	unless ($cid=$env{'request.course.id'}) {
 8475: 	    return 'not_in_class';
 8476: 	}
 8477: 	$cdom=$env{'course.'.$cid.'.domain'};
 8478: 	$cnum=$env{'course.'.$cid.'.num'};
 8479:     } else {
 8480: 	($cdom,$cnum)=split(/_/,$cid);
 8481:     }
 8482:     $chome=$env{'course.'.$cid.'.home'};
 8483:     if (!$chome) {
 8484: 	$chome=&homeserver($cnum,$cdom);
 8485:     }
 8486:     if (!$chome) { return 'unknown_course'; }
 8487:     # Make sure the user exists
 8488:     my $uhome=&homeserver($uname,$udom);
 8489:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 8490: 	return 'error: no such user';
 8491:     }
 8492:     # Get student data if we were not given enough information
 8493:     if (!defined($first)  || $first  eq '' || 
 8494:         !defined($last)   || $last   eq '' || 
 8495:         !defined($uid)    || $uid    eq '' || 
 8496:         !defined($middle) || $middle eq '' || 
 8497:         !defined($gene)   || $gene   eq '') {
 8498:         # They did not supply us with enough data to enroll the student, so
 8499:         # we need to pick up more information.
 8500:         my %tmp = &get('environment',
 8501:                        ['firstname','middlename','lastname', 'generation','id']
 8502:                        ,$udom,$uname);
 8503: 
 8504:         #foreach my $key (keys(%tmp)) {
 8505:         #    &logthis("key $key = ".$tmp{$key});
 8506:         #}
 8507:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 8508:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 8509:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 8510:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 8511:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 8512:     }
 8513:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 8514:     my $user = "$uname:$udom";
 8515:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
 8516:     my $reply=cput('classlist',
 8517: 		   {$user => 
 8518: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
 8519: 		   $cdom,$cnum);
 8520:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
 8521:         &devalidate_getsection_cache($udom,$uname,$cid);
 8522:     } else { 
 8523: 	return 'error: '.$reply;
 8524:     }
 8525:     # Add student role to user
 8526:     my $uurl='/'.$cid;
 8527:     $uurl=~s/\_/\//g;
 8528:     if ($usec) {
 8529: 	$uurl.='/'.$usec;
 8530:     }
 8531:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
 8532:                              $selfenroll,$context);
 8533:     if ($result ne 'ok') {
 8534:         if ($old_entry{$user} ne '') {
 8535:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
 8536:         } else {
 8537:             $reply = &del('classlist',[$user],$cdom,$cnum);
 8538:         }
 8539:     }
 8540:     return $result; 
 8541: }
 8542: 
 8543: sub format_name {
 8544:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 8545:     my $name;
 8546:     if ($first ne 'lastname') {
 8547: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 8548:     } else {
 8549: 	if ($lastname=~/\S/) {
 8550: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 8551: 	    $name=~s/\s+,/,/;
 8552: 	} else {
 8553: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 8554: 	}
 8555:     }
 8556:     $name=~s/^\s+//;
 8557:     $name=~s/\s+$//;
 8558:     $name=~s/\s+/ /g;
 8559:     return $name;
 8560: }
 8561: 
 8562: # ------------------------------------------------- Write to course preferences
 8563: 
 8564: sub writecoursepref {
 8565:     my ($courseid,%prefs)=@_;
 8566:     $courseid=~s/^\///;
 8567:     $courseid=~s/\_/\//g;
 8568:     my ($cdomain,$cnum)=split(/\//,$courseid);
 8569:     my $chome=homeserver($cnum,$cdomain);
 8570:     if (($chome eq '') || ($chome eq 'no_host')) { 
 8571: 	return 'error: no such course';
 8572:     }
 8573:     my $cstring='';
 8574:     foreach my $pref (keys(%prefs)) {
 8575: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 8576:     }
 8577:     $cstring=~s/\&$//;
 8578:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 8579: }
 8580: 
 8581: # ---------------------------------------------------------- Make/modify course
 8582: 
 8583: sub createcourse {
 8584:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 8585:         $course_owner,$crstype,$cnum,$context,$category)=@_;
 8586:     $url=&declutter($url);
 8587:     my $cid='';
 8588:     if ($context eq 'requestcourses') {
 8589:         my $can_create = 0;
 8590:         my ($ownername,$ownerdom) = split(':',$course_owner);
 8591:         if ($udom eq $ownerdom) {
 8592:             if (&usertools_access($ownername,$ownerdom,$category,undef,
 8593:                                   $context)) {
 8594:                 $can_create = 1;
 8595:             }
 8596:         } else {
 8597:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
 8598:                                            $category);
 8599:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
 8600:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
 8601:                 if (@curr > 0) {
 8602:                     my @options = qw(approval validate autolimit);
 8603:                     my $optregex = join('|',@options);
 8604:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
 8605:                         $can_create = 1;
 8606:                     }
 8607:                 }
 8608:             }
 8609:         }
 8610:         if ($can_create) {
 8611:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
 8612:                 unless (&allowed('ccc',$udom)) {
 8613:                     return 'refused'; 
 8614:                 }
 8615:             }
 8616:         } else {
 8617:             return 'refused';
 8618:         }
 8619:     } elsif (!&allowed('ccc',$udom)) {
 8620:         return 'refused';
 8621:     }
 8622: # --------------------------------------------------------------- Get Unique ID
 8623:     my $uname;
 8624:     if ($cnum =~ /^$match_courseid$/) {
 8625:         my $chome=&homeserver($cnum,$udom,'true');
 8626:         if (($chome eq '') || ($chome eq 'no_host')) {
 8627:             $uname = $cnum;
 8628:         } else {
 8629:             $uname = &generate_coursenum($udom,$crstype);
 8630:         }
 8631:     } else {
 8632:         $uname = &generate_coursenum($udom,$crstype);
 8633:     }
 8634:     return $uname if ($uname =~ /^error/);
 8635: # -------------------------------------------------- Check supplied server name
 8636:     if (!defined($course_server)) {
 8637:         if (defined(&domain($udom,'primary'))) {
 8638:             $course_server = &domain($udom,'primary');
 8639:         } else {
 8640:             $course_server = $env{'user.home'}; 
 8641:         }
 8642:     }
 8643:     my %host_servers =
 8644:         &Apache::lonnet::get_servers($udom,'library');
 8645:     unless ($host_servers{$course_server}) {
 8646:         return 'error: invalid home server for course: '.$course_server;
 8647:     }
 8648: # ------------------------------------------------------------- Make the course
 8649:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 8650:                       $course_server);
 8651:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 8652:     my $uhome=&homeserver($uname,$udom,'true');
 8653:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 8654: 	return 'error: no such course';
 8655:     }
 8656: # ----------------------------------------------------------------- Course made
 8657: # log existence
 8658:     my $now = time;
 8659:     my $newcourse = {
 8660:                     $udom.'_'.$uname => {
 8661:                                      description => $description,
 8662:                                      inst_code   => $inst_code,
 8663:                                      owner       => $course_owner,
 8664:                                      type        => $crstype,
 8665:                                      creator     => $env{'user.name'}.':'.
 8666:                                                     $env{'user.domain'},
 8667:                                      created     => $now,
 8668:                                      context     => $context,
 8669:                                                 },
 8670:                     };
 8671:     &courseidput($udom,$newcourse,$uhome,'notime');
 8672: # set toplevel url
 8673:     my $topurl=$url;
 8674:     unless ($nonstandard) {
 8675: # ------------------------------------------ For standard courses, make top url
 8676:         my $mapurl=&clutter($url);
 8677:         if ($mapurl eq '/res/') { $mapurl=''; }
 8678:         $env{'form.initmap'}=(<<ENDINITMAP);
 8679: <map>
 8680: <resource id="1" type="start"></resource>
 8681: <resource id="2" src="$mapurl"></resource>
 8682: <resource id="3" type="finish"></resource>
 8683: <link index="1" from="1" to="2"></link>
 8684: <link index="2" from="2" to="3"></link>
 8685: </map>
 8686: ENDINITMAP
 8687:         $topurl=&declutter(
 8688:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 8689:                           );
 8690:     }
 8691: # ----------------------------------------------------------- Write preferences
 8692:     &writecoursepref($udom.'_'.$uname,
 8693:                      ('description'              => $description,
 8694:                       'url'                      => $topurl,
 8695:                       'internal.creator'         => $env{'user.name'}.':'.
 8696:                                                     $env{'user.domain'},
 8697:                       'internal.created'         => $now,
 8698:                       'internal.creationcontext' => $context)
 8699:                     );
 8700:     return '/'.$udom.'/'.$uname;
 8701: }
 8702: 
 8703: # ------------------------------------------------------------------- Create ID
 8704: sub generate_coursenum {
 8705:     my ($udom,$crstype) = @_;
 8706:     my $domdesc = &domain($udom);
 8707:     return 'error: invalid domain' if ($domdesc eq '');
 8708:     my $first;
 8709:     if ($crstype eq 'Community') {
 8710:         $first = '0';
 8711:     } else {
 8712:         $first = int(1+rand(9)); 
 8713:     } 
 8714:     my $uname=$first.
 8715:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 8716:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
 8717:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 8718: # ----------------------------------------------- Make sure that does not exist
 8719:     my $uhome=&homeserver($uname,$udom,'true');
 8720:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
 8721:         if ($crstype eq 'Community') {
 8722:             $first = '0';
 8723:         } else {
 8724:             $first = int(1+rand(9));
 8725:         }
 8726:         $uname=$first.
 8727:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 8728:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
 8729:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 8730:         $uhome=&homeserver($uname,$udom,'true');
 8731:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
 8732:             return 'error: unable to generate unique course-ID';
 8733:         }
 8734:     }
 8735:     return $uname;
 8736: }
 8737: 
 8738: sub is_course {
 8739:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
 8740:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
 8741: 
 8742:     return unless $cdom and $cnum;
 8743: 
 8744:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
 8745:         '.');
 8746: 
 8747:     return unless(exists($courses{$cdom.'_'.$cnum}));
 8748:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
 8749: }
 8750: 
 8751: sub store_userdata {
 8752:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
 8753:     my $result;
 8754:     if ($datakey ne '') {
 8755:         if (ref($storehash) eq 'HASH') {
 8756:             if ($udom eq '' || $uname eq '') {
 8757:                 $udom = $env{'user.domain'};
 8758:                 $uname = $env{'user.name'};
 8759:             }
 8760:             my $uhome=&homeserver($uname,$udom);
 8761:             if (($uhome eq '') || ($uhome eq 'no_host')) {
 8762:                 $result = 'error: no_host';
 8763:             } else {
 8764:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
 8765:                 $storehash->{'host'} = $perlvar{'lonHostID'};
 8766: 
 8767:                 my $namevalue='';
 8768:                 foreach my $key (keys(%{$storehash})) {
 8769:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 8770:                 }
 8771:                 $namevalue=~s/\&$//;
 8772:                 unless ($namespace eq 'courserequests') {
 8773:                     $datakey = &escape($datakey);
 8774:                 }
 8775:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
 8776:                                   $namevalue,$uhome);
 8777:             }
 8778:         } else {
 8779:             $result = 'error: data to store was not a hash reference'; 
 8780:         }
 8781:     } else {
 8782:         $result= 'error: invalid requestkey'; 
 8783:     }
 8784:     return $result;
 8785: }
 8786: 
 8787: # ---------------------------------------------------------- Assign Custom Role
 8788: 
 8789: sub assigncustomrole {
 8790:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
 8791:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 8792:                        $end,$start,$deleteflag,$selfenroll,$context);
 8793: }
 8794: 
 8795: # ----------------------------------------------------------------- Revoke Role
 8796: 
 8797: sub revokerole {
 8798:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
 8799:     my $now=time;
 8800:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
 8801: }
 8802: 
 8803: # ---------------------------------------------------------- Revoke Custom Role
 8804: 
 8805: sub revokecustomrole {
 8806:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
 8807:     my $now=time;
 8808:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 8809:            $deleteflag,$selfenroll,$context);
 8810: }
 8811: 
 8812: # ------------------------------------------------------------ Disk usage
 8813: sub diskusage {
 8814:     my ($udom,$uname,$directorypath,$getpropath)=@_;
 8815:     $directorypath =~ s/\/$//;
 8816:     my $listing=&reply('du2:'.&escape($directorypath).':'
 8817:                        .&escape($getpropath).':'.&escape($uname).':'
 8818:                        .&escape($udom),homeserver($uname,$udom));
 8819:     if ($listing eq 'unknown_cmd') {
 8820:         if ($getpropath) {
 8821:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
 8822:         }
 8823:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
 8824:     }
 8825:     return $listing;
 8826: }
 8827: 
 8828: sub is_locked {
 8829:     my ($file_name, $domain, $user, $which) = @_;
 8830:     my @check;
 8831:     my $is_locked;
 8832:     push (@check,$file_name);
 8833:     my %locked = &get('file_permissions',\@check,
 8834: 		      $env{'user.domain'},$env{'user.name'});
 8835:     my ($tmp)=keys(%locked);
 8836:     if ($tmp=~/^error:/) { undef(%locked); }
 8837:     
 8838:     if (ref($locked{$file_name}) eq 'ARRAY') {
 8839:         $is_locked = 'false';
 8840:         foreach my $entry (@{$locked{$file_name}}) {
 8841:            if (ref($entry) eq 'ARRAY') {
 8842:                $is_locked = 'true';
 8843:                if (ref($which) eq 'ARRAY') {
 8844:                    push(@{$which},$entry);
 8845:                } else {
 8846:                    last;
 8847:                }
 8848:            }
 8849:        }
 8850:     } else {
 8851:         $is_locked = 'false';
 8852:     }
 8853:     return $is_locked;
 8854: }
 8855: 
 8856: sub declutter_portfile {
 8857:     my ($file) = @_;
 8858:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 8859:     return $file;
 8860: }
 8861: 
 8862: # ------------------------------------------------------------- Mark as Read Only
 8863: 
 8864: sub mark_as_readonly {
 8865:     my ($domain,$user,$files,$what) = @_;
 8866:     my %current_permissions = &dump('file_permissions',$domain,$user);
 8867:     my ($tmp)=keys(%current_permissions);
 8868:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 8869:     foreach my $file (@{$files}) {
 8870: 	$file = &declutter_portfile($file);
 8871:         push(@{$current_permissions{$file}},$what);
 8872:     }
 8873:     &put('file_permissions',\%current_permissions,$domain,$user);
 8874:     return;
 8875: }
 8876: 
 8877: # ------------------------------------------------------------Save Selected Files
 8878: 
 8879: sub save_selected_files {
 8880:     my ($user, $path, @files) = @_;
 8881:     my $filename = $user."savedfiles";
 8882:     my @other_files = &files_not_in_path($user, $path);
 8883:     open (OUT, '>'.$tmpdir.$filename);
 8884:     foreach my $file (@files) {
 8885:         print (OUT $env{'form.currentpath'}.$file."\n");
 8886:     }
 8887:     foreach my $file (@other_files) {
 8888:         print (OUT $file."\n");
 8889:     }
 8890:     close (OUT);
 8891:     return 'ok';
 8892: }
 8893: 
 8894: sub clear_selected_files {
 8895:     my ($user) = @_;
 8896:     my $filename = $user."savedfiles";
 8897:     open (OUT, '>'.LONCAPA::tempdir().$filename);
 8898:     print (OUT undef);
 8899:     close (OUT);
 8900:     return ("ok");    
 8901: }
 8902: 
 8903: sub files_in_path {
 8904:     my ($user, $path) = @_;
 8905:     my $filename = $user."savedfiles";
 8906:     my %return_files;
 8907:     open (IN, '<'.LONCAPA::tempdir().$filename);
 8908:     while (my $line_in = <IN>) {
 8909:         chomp ($line_in);
 8910:         my @paths_and_file = split (m!/!, $line_in);
 8911:         my $file_part = pop (@paths_and_file);
 8912:         my $path_part = join ('/', @paths_and_file);
 8913:         $path_part.='/';
 8914:         my $path_and_file = $path_part.$file_part;
 8915:         if ($path_part eq $path) {
 8916:             $return_files{$file_part}= 'selected';
 8917:         }
 8918:     }
 8919:     close (IN);
 8920:     return (\%return_files);
 8921: }
 8922: 
 8923: # called in portfolio select mode, to show files selected NOT in current directory
 8924: sub files_not_in_path {
 8925:     my ($user, $path) = @_;
 8926:     my $filename = $user."savedfiles";
 8927:     my @return_files;
 8928:     my $path_part;
 8929:     open(IN, '<'.LONCAPA::.$filename);
 8930:     while (my $line = <IN>) {
 8931:         #ok, I know it's clunky, but I want it to work
 8932:         my @paths_and_file = split(m|/|, $line);
 8933:         my $file_part = pop(@paths_and_file);
 8934:         chomp($file_part);
 8935:         my $path_part = join('/', @paths_and_file);
 8936:         $path_part .= '/';
 8937:         my $path_and_file = $path_part.$file_part;
 8938:         if ($path_part ne $path) {
 8939:             push(@return_files, ($path_and_file));
 8940:         }
 8941:     }
 8942:     close(OUT);
 8943:     return (@return_files);
 8944: }
 8945: 
 8946: #----------------------------------------------Get portfolio file permissions
 8947: 
 8948: sub get_portfile_permissions {
 8949:     my ($domain,$user) = @_;
 8950:     my %current_permissions = &dump('file_permissions',$domain,$user);
 8951:     my ($tmp)=keys(%current_permissions);
 8952:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 8953:     return \%current_permissions;
 8954: }
 8955: 
 8956: #---------------------------------------------Get portfolio file access controls
 8957: 
 8958: sub get_access_controls {
 8959:     my ($current_permissions,$group,$file) = @_;
 8960:     my %access;
 8961:     my $real_file = $file;
 8962:     $file =~ s/\.meta$//;
 8963:     if (defined($file)) {
 8964:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 8965:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 8966:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 8967:             }
 8968:         }
 8969:     } else {
 8970:         foreach my $key (keys(%{$current_permissions})) {
 8971:             if ($key =~ /\0accesscontrol$/) {
 8972:                 if (defined($group)) {
 8973:                     if ($key !~ m-^\Q$group\E/-) {
 8974:                         next;
 8975:                     }
 8976:                 }
 8977:                 my ($fullpath) = split(/\0/,$key);
 8978:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 8979:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 8980:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 8981:                     }
 8982:                 }
 8983:             }
 8984:         }
 8985:     }
 8986:     return %access;
 8987: }
 8988: 
 8989: sub modify_access_controls {
 8990:     my ($file_name,$changes,$domain,$user)=@_;
 8991:     my ($outcome,$deloutcome);
 8992:     my %store_permissions;
 8993:     my %new_values;
 8994:     my %new_control;
 8995:     my %translation;
 8996:     my @deletions = ();
 8997:     my $now = time;
 8998:     if (exists($$changes{'activate'})) {
 8999:         if (ref($$changes{'activate'}) eq 'HASH') {
 9000:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 9001:             my $numnew = scalar(@newitems);
 9002:             for (my $i=0; $i<$numnew; $i++) {
 9003:                 my $newkey = $newitems[$i];
 9004:                 my $newid = &Apache::loncommon::get_cgi_id();
 9005:                 if ($newkey =~ /^\d+:/) { 
 9006:                     $newkey =~ s/^(\d+)/$newid/;
 9007:                     $translation{$1} = $newid;
 9008:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 9009:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 9010:                     $translation{$1} = $newid;
 9011:                 }
 9012:                 $new_values{$file_name."\0".$newkey} = 
 9013:                                           $$changes{'activate'}{$newitems[$i]};
 9014:                 $new_control{$newkey} = $now;
 9015:             }
 9016:         }
 9017:     }
 9018:     my %todelete;
 9019:     my %changed_items;
 9020:     foreach my $action ('delete','update') {
 9021:         if (exists($$changes{$action})) {
 9022:             if (ref($$changes{$action}) eq 'HASH') {
 9023:                 foreach my $key (keys(%{$$changes{$action}})) {
 9024:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 9025:                     if ($action eq 'delete') { 
 9026:                         $todelete{$itemnum} = 1;
 9027:                     } else {
 9028:                         $changed_items{$itemnum} = $key;
 9029:                     }
 9030:                 }
 9031:             }
 9032:         }
 9033:     }
 9034:     # get lock on access controls for file.
 9035:     my $lockhash = {
 9036:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 9037:                                                        ':'.$env{'user.domain'},
 9038:                    }; 
 9039:     my $tries = 0;
 9040:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 9041:    
 9042:     while (($gotlock ne 'ok') && $tries <3) {
 9043:         $tries ++;
 9044:         sleep 1;
 9045:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 9046:     }
 9047:     if ($gotlock eq 'ok') {
 9048:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 9049:         my ($tmp)=keys(%curr_permissions);
 9050:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 9051:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 9052:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 9053:             if (ref($curr_controls) eq 'HASH') {
 9054:                 foreach my $control_item (keys(%{$curr_controls})) {
 9055:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 9056:                     if (defined($todelete{$itemnum})) {
 9057:                         push(@deletions,$file_name."\0".$control_item);
 9058:                     } else {
 9059:                         if (defined($changed_items{$itemnum})) {
 9060:                             $new_control{$changed_items{$itemnum}} = $now;
 9061:                             push(@deletions,$file_name."\0".$control_item);
 9062:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 9063:                         } else {
 9064:                             $new_control{$control_item} = $$curr_controls{$control_item};
 9065:                         }
 9066:                     }
 9067:                 }
 9068:             }
 9069:         }
 9070:         my ($group);
 9071:         if (&is_course($domain,$user)) {
 9072:             ($group,my $file) = split(/\//,$file_name,2);
 9073:         }
 9074:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 9075:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 9076:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 9077:         #  remove lock
 9078:         my @del_lock = ($file_name."\0".'locked_access_records');
 9079:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 9080:         my $sqlresult =
 9081:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
 9082:                                     $group);
 9083:     } else {
 9084:         $outcome = "error: could not obtain lockfile\n";  
 9085:     }
 9086:     return ($outcome,$deloutcome,\%new_values,\%translation);
 9087: }
 9088: 
 9089: sub make_public_indefinitely {
 9090:     my ($requrl) = @_;
 9091:     my $now = time;
 9092:     my $action = 'activate';
 9093:     my $aclnum = 0;
 9094:     if (&is_portfolio_url($requrl)) {
 9095:         my (undef,$udom,$unum,$file_name,$group) =
 9096:             &parse_portfolio_url($requrl);
 9097:         my $current_perms = &get_portfile_permissions($udom,$unum);
 9098:         my %access_controls = &get_access_controls($current_perms,
 9099:                                                    $group,$file_name);
 9100:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 9101:             my ($num,$scope,$end,$start) = 
 9102:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 9103:             if ($scope eq 'public') {
 9104:                 if ($start <= $now && $end == 0) {
 9105:                     $action = 'none';
 9106:                 } else {
 9107:                     $action = 'update';
 9108:                     $aclnum = $num;
 9109:                 }
 9110:                 last;
 9111:             }
 9112:         }
 9113:         if ($action eq 'none') {
 9114:              return 'ok';
 9115:         } else {
 9116:             my %changes;
 9117:             my $newend = 0;
 9118:             my $newstart = $now;
 9119:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 9120:             $changes{$action}{$newkey} = {
 9121:                 type => 'public',
 9122:                 time => {
 9123:                     start => $newstart,
 9124:                     end   => $newend,
 9125:                 },
 9126:             };
 9127:             my ($outcome,$deloutcome,$new_values,$translation) =
 9128:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 9129:             return $outcome;
 9130:         }
 9131:     } else {
 9132:         return 'invalid';
 9133:     }
 9134: }
 9135: 
 9136: #------------------------------------------------------Get Marked as Read Only
 9137: 
 9138: sub get_marked_as_readonly {
 9139:     my ($domain,$user,$what,$group) = @_;
 9140:     my $current_permissions = &get_portfile_permissions($domain,$user);
 9141:     my @readonly_files;
 9142:     my $cmp1=$what;
 9143:     if (ref($what)) { $cmp1=join('',@{$what}) };
 9144:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 9145:         if (defined($group)) {
 9146:             if ($file_name !~ m-^\Q$group\E/-) {
 9147:                 next;
 9148:             }
 9149:         }
 9150:         if (ref($value) eq "ARRAY"){
 9151:             foreach my $stored_what (@{$value}) {
 9152:                 my $cmp2=$stored_what;
 9153:                 if (ref($stored_what) eq 'ARRAY') {
 9154:                     $cmp2=join('',@{$stored_what});
 9155:                 }
 9156:                 if ($cmp1 eq $cmp2) {
 9157:                     push(@readonly_files, $file_name);
 9158:                     last;
 9159:                 } elsif (!defined($what)) {
 9160:                     push(@readonly_files, $file_name);
 9161:                     last;
 9162:                 }
 9163:             }
 9164:         }
 9165:     }
 9166:     return @readonly_files;
 9167: }
 9168: #-----------------------------------------------------------Get Marked as Read Only Hash
 9169: 
 9170: sub get_marked_as_readonly_hash {
 9171:     my ($current_permissions,$group,$what) = @_;
 9172:     my %readonly_files;
 9173:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 9174:         if (defined($group)) {
 9175:             if ($file_name !~ m-^\Q$group\E/-) {
 9176:                 next;
 9177:             }
 9178:         }
 9179:         if (ref($value) eq "ARRAY"){
 9180:             foreach my $stored_what (@{$value}) {
 9181:                 if (ref($stored_what) eq 'ARRAY') {
 9182:                     foreach my $lock_descriptor(@{$stored_what}) {
 9183:                         if ($lock_descriptor eq 'graded') {
 9184:                             $readonly_files{$file_name} = 'graded';
 9185:                         } elsif ($lock_descriptor eq 'handback') {
 9186:                             $readonly_files{$file_name} = 'handback';
 9187:                         } else {
 9188:                             if (!exists($readonly_files{$file_name})) {
 9189:                                 $readonly_files{$file_name} = 'locked';
 9190:                             }
 9191:                         }
 9192:                     }
 9193:                 } 
 9194:             }
 9195:         } 
 9196:     }
 9197:     return %readonly_files;
 9198: }
 9199: # ------------------------------------------------------------ Unmark as Read Only
 9200: 
 9201: sub unmark_as_readonly {
 9202:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 9203:     # for portfolio submissions, $what contains [$symb,$crsid] 
 9204:     my ($domain,$user,$what,$file_name,$group) = @_;
 9205:     $file_name = &declutter_portfile($file_name);
 9206:     my $symb_crs = $what;
 9207:     if (ref($what)) { $symb_crs=join('',@$what); }
 9208:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 9209:     my ($tmp)=keys(%current_permissions);
 9210:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 9211:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 9212:     foreach my $file (@readonly_files) {
 9213: 	my $clean_file = &declutter_portfile($file);
 9214: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 9215: 	my $current_locks = $current_permissions{$file};
 9216:         my @new_locks;
 9217:         my @del_keys;
 9218:         if (ref($current_locks) eq "ARRAY"){
 9219:             foreach my $locker (@{$current_locks}) {
 9220:                 my $compare=$locker;
 9221:                 if (ref($locker) eq 'ARRAY') {
 9222:                     $compare=join('',@{$locker});
 9223:                     if ($compare ne $symb_crs) {
 9224:                         push(@new_locks, $locker);
 9225:                     }
 9226:                 }
 9227:             }
 9228:             if (scalar(@new_locks) > 0) {
 9229:                 $current_permissions{$file} = \@new_locks;
 9230:             } else {
 9231:                 push(@del_keys, $file);
 9232:                 &del('file_permissions',\@del_keys, $domain, $user);
 9233:                 delete($current_permissions{$file});
 9234:             }
 9235:         }
 9236:     }
 9237:     &put('file_permissions',\%current_permissions,$domain,$user);
 9238:     return;
 9239: }
 9240: 
 9241: # ------------------------------------------------------------ Directory lister
 9242: 
 9243: sub dirlist {
 9244:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
 9245:     $uri=~s/^\///;
 9246:     $uri=~s/\/$//;
 9247:     my ($udom, $uname);
 9248:     if ($getuserdir) {
 9249:         $udom = $userdomain;
 9250:         $uname = $username;
 9251:     } else {
 9252:         (undef,$udom,$uname)=split(/\//,$uri);
 9253:         if(defined($userdomain)) {
 9254:             $udom = $userdomain;
 9255:         }
 9256:         if(defined($username)) {
 9257:             $uname = $username;
 9258:         }
 9259:     }
 9260:     my ($dirRoot,$listing,@listing_results);
 9261: 
 9262:     $dirRoot = $perlvar{'lonDocRoot'};
 9263:     if (defined($getpropath)) {
 9264:         $dirRoot = &propath($udom,$uname);
 9265:         $dirRoot =~ s/\/$//;
 9266:     } elsif (defined($getuserdir)) {
 9267:         my $subdir=$uname.'__';
 9268:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 9269:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
 9270:                    ."/$udom/$subdir/$uname";
 9271:     } elsif (defined($alternateRoot)) {
 9272:         $dirRoot = $alternateRoot;
 9273:     }
 9274: 
 9275:     if($udom) {
 9276:         if($uname) {
 9277:             my $uhome = &homeserver($uname,$udom);
 9278:             if ($uhome eq 'no_host') {
 9279:                 return ([],'no_host');
 9280:             }
 9281:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
 9282:                               .$getuserdir.':'.&escape($dirRoot)
 9283:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
 9284:             if ($listing eq 'unknown_cmd') {
 9285:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
 9286:             } else {
 9287:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 9288:             }
 9289:             if ($listing eq 'unknown_cmd') {
 9290:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
 9291:                 @listing_results = split(/:/,$listing);
 9292:             } else {
 9293:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 9294:             }
 9295:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
 9296:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
 9297:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 9298:                 return ([],$listing);
 9299:             } else {
 9300:                 return (\@listing_results);
 9301:             }
 9302:         } elsif(!$alternateRoot) {
 9303:             my (%allusers,%listerror);
 9304: 	    my %servers = &get_servers($udom,'library');
 9305:  	    foreach my $tryserver (keys(%servers)) {
 9306:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
 9307:                                   &escape($udom),$tryserver);
 9308:                 if ($listing eq 'unknown_cmd') {
 9309: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 9310: 				      $udom, $tryserver);
 9311:                 } else {
 9312:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
 9313:                 }
 9314: 		if ($listing eq 'unknown_cmd') {
 9315: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 9316: 				      $udom, $tryserver);
 9317: 		    @listing_results = split(/:/,$listing);
 9318: 		} else {
 9319: 		    @listing_results =
 9320: 			map { &unescape($_); } split(/:/,$listing);
 9321: 		}
 9322:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
 9323:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
 9324:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 9325:                     $listerror{$tryserver} = $listing;
 9326:                 } else {
 9327: 		    foreach my $line (@listing_results) {
 9328: 			my ($entry) = split(/&/,$line,2);
 9329: 			$allusers{$entry} = 1;
 9330: 		    }
 9331: 		}
 9332:             }
 9333:             my @alluserslist=();
 9334:             foreach my $user (sort(keys(%allusers))) {
 9335:                 push(@alluserslist,$user.'&user');
 9336:             }
 9337:             return (\@alluserslist);
 9338:         } else {
 9339:             return ([],'missing username');
 9340:         }
 9341:     } elsif(!defined($getpropath)) {
 9342:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
 9343:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
 9344:         return (\@all_domains);
 9345:     } else {
 9346:         return ([],'missing domain');
 9347:     }
 9348: }
 9349: 
 9350: # --------------------------------------------- GetFileTimestamp
 9351: # This function utilizes dirlist and returns the date stamp for
 9352: # when it was last modified.  It will also return an error of -1
 9353: # if an error occurs
 9354: 
 9355: sub GetFileTimestamp {
 9356:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
 9357:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 9358:     $studentName   = &LONCAPA::clean_username($studentName);
 9359:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
 9360:                                     undef,$getuserdir);
 9361:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 9362:         return -1;
 9363:     }
 9364:     if (ref($fileref) eq 'ARRAY') {
 9365:         my @stats = split('&',$fileref->[0]);
 9366:         # @stats contains first the filename, then the stat output
 9367:         return $stats[10]; # so this is 10 instead of 9.
 9368:     } else {
 9369:         return -1;
 9370:     }
 9371: }
 9372: 
 9373: sub stat_file {
 9374:     my ($uri) = @_;
 9375:     $uri = &clutter_with_no_wrapper($uri);
 9376: 
 9377:     my ($udom,$uname,$file);
 9378:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 9379: 	($udom,$uname,$file) =
 9380: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 9381: 	$file = 'userfiles/'.$file;
 9382:     }
 9383:     if ($uri =~ m-^/res/-) {
 9384: 	($udom,$uname) = 
 9385: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 9386: 	$file = $uri;
 9387:     }
 9388: 
 9389:     if (!$udom || !$uname || !$file) {
 9390: 	# unable to handle the uri
 9391: 	return ();
 9392:     }
 9393:     my $getpropath;
 9394:     if ($file =~ /^userfiles\//) {
 9395:         $getpropath = 1;
 9396:     }
 9397:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
 9398:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 9399:         return ();
 9400:     } else {
 9401:         if (ref($listref) eq 'ARRAY') {
 9402:             my @stats = split('&',$listref->[0]);
 9403: 	    shift(@stats); #filename is first
 9404: 	    return @stats;
 9405:         }
 9406:     }
 9407:     return ();
 9408: }
 9409: 
 9410: # -------------------------------------------------------- Value of a Condition
 9411: 
 9412: # gets the value of a specific preevaluated condition
 9413: #    stored in the string  $env{user.state.<cid>}
 9414: # or looks up a condition reference in the bighash and if if hasn't
 9415: # already been evaluated recurses into docondval to get the value of
 9416: # the condition, then memoizing it to 
 9417: #   $env{user.state.<cid>.<condition>}
 9418: sub directcondval {
 9419:     my $number=shift;
 9420:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 9421: 	&Apache::lonuserstate::evalstate();
 9422:     }
 9423:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 9424: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 9425:     } elsif ($number =~ /^_/) {
 9426: 	my $sub_condition;
 9427: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9428: 		&GDBM_READER(),0640)) {
 9429: 	    $sub_condition=$bighash{'conditions'.$number};
 9430: 	    untie(%bighash);
 9431: 	}
 9432: 	my $value = &docondval($sub_condition);
 9433: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
 9434: 	return $value;
 9435:     }
 9436:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 9437:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 9438:     } else {
 9439:        return 2;
 9440:     }
 9441: }
 9442: 
 9443: # get the collection of conditions for this resource
 9444: sub condval {
 9445:     my $condidx=shift;
 9446:     my $allpathcond='';
 9447:     foreach my $cond (split(/\|/,$condidx)) {
 9448: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 9449: 	    $allpathcond.=
 9450: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 9451: 	}
 9452:     }
 9453:     $allpathcond=~s/\|$//;
 9454:     return &docondval($allpathcond);
 9455: }
 9456: 
 9457: #evaluates an expression of conditions
 9458: sub docondval {
 9459:     my ($allpathcond) = @_;
 9460:     my $result=0;
 9461:     if ($env{'request.course.id'}
 9462: 	&& defined($allpathcond)) {
 9463: 	my $operand='|';
 9464: 	my @stack;
 9465: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 9466: 	    if ($chunk eq '(') {
 9467: 		push @stack,($operand,$result);
 9468: 	    } elsif ($chunk eq ')') {
 9469: 		my $before=pop @stack;
 9470: 		if (pop @stack eq '&') {
 9471: 		    $result=$result>$before?$before:$result;
 9472: 		} else {
 9473: 		    $result=$result>$before?$result:$before;
 9474: 		}
 9475: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 9476: 		$operand=$chunk;
 9477: 	    } else {
 9478: 		my $new=directcondval($chunk);
 9479: 		if ($operand eq '&') {
 9480: 		    $result=$result>$new?$new:$result;
 9481: 		} else {
 9482: 		    $result=$result>$new?$result:$new;
 9483: 		}
 9484: 	    }
 9485: 	}
 9486:     }
 9487:     return $result;
 9488: }
 9489: 
 9490: # ---------------------------------------------------- Devalidate courseresdata
 9491: 
 9492: sub devalidatecourseresdata {
 9493:     my ($coursenum,$coursedomain)=@_;
 9494:     my $hashid=$coursenum.':'.$coursedomain;
 9495:     &devalidate_cache_new('courseres',$hashid);
 9496: }
 9497: 
 9498: 
 9499: # --------------------------------------------------- Course Resourcedata Query
 9500: #
 9501: #  Parameters:
 9502: #      $coursenum    - Number of the course.
 9503: #      $coursedomain - Domain at which the course was created.
 9504: #  Returns:
 9505: #     A hash of the course parameters along (I think) with timestamps
 9506: #     and version info.
 9507: 
 9508: sub get_courseresdata {
 9509:     my ($coursenum,$coursedomain)=@_;
 9510:     my $coursehom=&homeserver($coursenum,$coursedomain);
 9511:     my $hashid=$coursenum.':'.$coursedomain;
 9512:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 9513:     my %dumpreply;
 9514:     unless (defined($cached)) {
 9515: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 9516: 	$result=\%dumpreply;
 9517: 	my ($tmp) = keys(%dumpreply);
 9518: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 9519: 	    &do_cache_new('courseres',$hashid,$result,600);
 9520: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 9521: 	    return $tmp;
 9522: 	} elsif ($tmp =~ /^(error)/) {
 9523: 	    $result=undef;
 9524: 	    &do_cache_new('courseres',$hashid,$result,600);
 9525: 	}
 9526:     }
 9527:     return $result;
 9528: }
 9529: 
 9530: sub devalidateuserresdata {
 9531:     my ($uname,$udom)=@_;
 9532:     my $hashid="$udom:$uname";
 9533:     &devalidate_cache_new('userres',$hashid);
 9534: }
 9535: 
 9536: sub get_userresdata {
 9537:     my ($uname,$udom)=@_;
 9538:     #most student don\'t have any data set, check if there is some data
 9539:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 9540: 
 9541:     my $hashid="$udom:$uname";
 9542:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 9543:     if (!defined($cached)) {
 9544: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 9545: 	$result=\%resourcedata;
 9546: 	&do_cache_new('userres',$hashid,$result,600);
 9547:     }
 9548:     my ($tmp)=keys(%$result);
 9549:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 9550: 	return $result;
 9551:     }
 9552:     #error 2 occurs when the .db doesn't exist
 9553:     if ($tmp!~/error: 2 /) {
 9554: 	&logthis("<font color=\"blue\">WARNING:".
 9555: 		 " Trying to get resource data for ".
 9556: 		 $uname." at ".$udom.": ".
 9557: 		 $tmp."</font>");
 9558:     } elsif ($tmp=~/error: 2 /) {
 9559: 	#&EXT_cache_set($udom,$uname);
 9560: 	&do_cache_new('userres',$hashid,undef,600);
 9561: 	undef($tmp); # not really an error so don't send it back
 9562:     }
 9563:     return $tmp;
 9564: }
 9565: #----------------------------------------------- resdata - return resource data
 9566: #  Purpose:
 9567: #    Return resource data for either users or for a course.
 9568: #  Parameters:
 9569: #     $name      - Course/user name.
 9570: #     $domain    - Name of the domain the user/course is registered on.
 9571: #     $type      - Type of thing $name is (must be 'course' or 'user'
 9572: #     @which     - Array of names of resources desired.
 9573: #  Returns:
 9574: #     The value of the first reasource in @which that is found in the
 9575: #     resource hash.
 9576: #  Exceptional Conditions:
 9577: #     If the $type passed in is not valid (not the string 'course' or 
 9578: #     'user', an undefined  reference is returned.
 9579: #     If none of the resources are found, an undef is returned
 9580: sub resdata {
 9581:     my ($name,$domain,$type,@which)=@_;
 9582:     my $result;
 9583:     if ($type eq 'course') {
 9584: 	$result=&get_courseresdata($name,$domain);
 9585:     } elsif ($type eq 'user') {
 9586: 	$result=&get_userresdata($name,$domain);
 9587:     }
 9588:     if (!ref($result)) { return $result; }    
 9589:     foreach my $item (@which) {
 9590: 	if (defined($result->{$item->[0]})) {
 9591: 	    return [$result->{$item->[0]},$item->[1]];
 9592: 	}
 9593:     }
 9594:     return undef;
 9595: }
 9596: 
 9597: #
 9598: # EXT resource caching routines
 9599: #
 9600: 
 9601: sub clear_EXT_cache_status {
 9602:     &delenv('cache.EXT.');
 9603: }
 9604: 
 9605: sub EXT_cache_status {
 9606:     my ($target_domain,$target_user) = @_;
 9607:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 9608:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 9609:         # We know already the user has no data
 9610:         return 1;
 9611:     } else {
 9612:         return 0;
 9613:     }
 9614: }
 9615: 
 9616: sub EXT_cache_set {
 9617:     my ($target_domain,$target_user) = @_;
 9618:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 9619:     #&appenv({$cachename => time});
 9620: }
 9621: 
 9622: # --------------------------------------------------------- Value of a Variable
 9623: sub EXT {
 9624: 
 9625:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
 9626:     unless ($varname) { return ''; }
 9627:     #get real user name/domain, courseid and symb
 9628:     my $courseid;
 9629:     my $publicuser;
 9630:     if ($symbparm) {
 9631: 	$symbparm=&get_symb_from_alias($symbparm);
 9632:     }
 9633:     if (!($uname && $udom)) {
 9634:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 9635:       if (!$symbparm) {	$symbparm=$cursymb; }
 9636:     } else {
 9637: 	$courseid=$env{'request.course.id'};
 9638:     }
 9639:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 9640:     my $rest;
 9641:     if (defined($therest[0])) {
 9642:        $rest=join('.',@therest);
 9643:     } else {
 9644:        $rest='';
 9645:     }
 9646: 
 9647:     my $qualifierrest=$qualifier;
 9648:     if ($rest) { $qualifierrest.='.'.$rest; }
 9649:     my $spacequalifierrest=$space;
 9650:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 9651:     if ($realm eq 'user') {
 9652: # --------------------------------------------------------------- user.resource
 9653: 	if ($space eq 'resource') {
 9654: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 9655: 		  || defined($Apache::lonhomework::parsing_a_task))
 9656: 		 &&
 9657: 		 ($symbparm eq &symbread()) ) {	
 9658: 		# if we are in the middle of processing the resource the
 9659: 		# get the value we are planning on committing
 9660:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 9661:                     return $Apache::lonhomework::results{$qualifierrest};
 9662:                 } else {
 9663:                     return $Apache::lonhomework::history{$qualifierrest};
 9664:                 }
 9665: 	    } else {
 9666: 		my %restored;
 9667: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 9668: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 9669: 		} else {
 9670: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 9671: 		}
 9672: 		return $restored{$qualifierrest};
 9673: 	    }
 9674: # ----------------------------------------------------------------- user.access
 9675:         } elsif ($space eq 'access') {
 9676: 	    # FIXME - not supporting calls for a specific user
 9677:             return &allowed($qualifier,$rest);
 9678: # ------------------------------------------ user.preferences, user.environment
 9679:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 9680: 	    if (($uname eq $env{'user.name'}) &&
 9681: 		($udom eq $env{'user.domain'})) {
 9682: 		return $env{join('.',('environment',$qualifierrest))};
 9683: 	    } else {
 9684: 		my %returnhash;
 9685: 		if (!$publicuser) {
 9686: 		    %returnhash=&userenvironment($udom,$uname,
 9687: 						 $qualifierrest);
 9688: 		}
 9689: 		return $returnhash{$qualifierrest};
 9690: 	    }
 9691: # ----------------------------------------------------------------- user.course
 9692:         } elsif ($space eq 'course') {
 9693: 	    # FIXME - not supporting calls for a specific user
 9694:             return $env{join('.',('request.course',$qualifier))};
 9695: # ------------------------------------------------------------------- user.role
 9696:         } elsif ($space eq 'role') {
 9697: 	    # FIXME - not supporting calls for a specific user
 9698:             my ($role,$where)=split(/\./,$env{'request.role'});
 9699:             if ($qualifier eq 'value') {
 9700: 		return $role;
 9701:             } elsif ($qualifier eq 'extent') {
 9702:                 return $where;
 9703:             }
 9704: # ----------------------------------------------------------------- user.domain
 9705:         } elsif ($space eq 'domain') {
 9706:             return $udom;
 9707: # ------------------------------------------------------------------- user.name
 9708:         } elsif ($space eq 'name') {
 9709:             return $uname;
 9710: # ---------------------------------------------------- Any other user namespace
 9711:         } else {
 9712: 	    my %reply;
 9713: 	    if (!$publicuser) {
 9714: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 9715: 	    }
 9716: 	    return $reply{$qualifierrest};
 9717:         }
 9718:     } elsif ($realm eq 'query') {
 9719: # ---------------------------------------------- pull stuff out of query string
 9720:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 9721: 						[$spacequalifierrest]);
 9722: 	return $env{'form.'.$spacequalifierrest}; 
 9723:    } elsif ($realm eq 'request') {
 9724: # ------------------------------------------------------------- request.browser
 9725:         if ($space eq 'browser') {
 9726:             return $env{'browser.'.$qualifier};
 9727: # ------------------------------------------------------------ request.filename
 9728:         } else {
 9729:             return $env{'request.'.$spacequalifierrest};
 9730:         }
 9731:     } elsif ($realm eq 'course') {
 9732: # ---------------------------------------------------------- course.description
 9733:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 9734:     } elsif ($realm eq 'resource') {
 9735: 
 9736: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 9737: 	    if (!$symbparm) { $symbparm=&symbread(); }
 9738: 	}
 9739: 
 9740: 	if ($space eq 'title') {
 9741: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 9742: 	    return &gettitle($symbparm);
 9743: 	}
 9744: 	
 9745: 	if ($space eq 'map') {
 9746: 	    my ($map) = &decode_symb($symbparm);
 9747: 	    return &symbread($map);
 9748: 	}
 9749: 	if ($space eq 'filename') {
 9750: 	    if ($symbparm) {
 9751: 		return &clutter((&decode_symb($symbparm))[2]);
 9752: 	    }
 9753: 	    return &hreflocation('',$env{'request.filename'});
 9754: 	}
 9755: 
 9756: 	my ($section, $group, @groups);
 9757: 	my ($courselevelm,$courselevel);
 9758: 	if ($symbparm && defined($courseid) && 
 9759: 	    $courseid eq $env{'request.course.id'}) {
 9760: 
 9761: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 9762: 
 9763: # ----------------------------------------------------- Cascading lookup scheme
 9764: 	    my $symbp=$symbparm;
 9765: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 9766: 
 9767: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 9768: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 9769: 
 9770: 	    if (($env{'user.name'} eq $uname) &&
 9771: 		($env{'user.domain'} eq $udom)) {
 9772: 		$section=$env{'request.course.sec'};
 9773:                 @groups = split(/:/,$env{'request.course.groups'});  
 9774:                 @groups=&sort_course_groups($courseid,@groups); 
 9775: 	    } else {
 9776: 		if (! defined($usection)) {
 9777: 		    $section=&getsection($udom,$uname,$courseid);
 9778: 		} else {
 9779: 		    $section = $usection;
 9780: 		}
 9781:                 @groups = &get_users_groups($udom,$uname,$courseid);
 9782: 	    }
 9783: 
 9784: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 9785: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 9786: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 9787: 
 9788: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 9789: 	    my $courselevelr=$courseid.'.'.$symbparm;
 9790: 	    $courselevelm=$courseid.'.'.$mapparm;
 9791: 
 9792: # ----------------------------------------------------------- first, check user
 9793: 
 9794: 	    my $userreply=&resdata($uname,$udom,'user',
 9795: 				       ([$courselevelr,'resource'],
 9796: 					[$courselevelm,'map'     ],
 9797: 					[$courselevel, 'course'  ]));
 9798: 	    if (defined($userreply)) { return &get_reply($userreply); }
 9799: 
 9800: # ------------------------------------------------ second, check some of course
 9801:             my $coursereply;
 9802:             if (@groups > 0) {
 9803:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 9804:                                        $mapparm,$spacequalifierrest);
 9805:                 if (defined($coursereply)) { return &get_reply($coursereply); }
 9806:             }
 9807: 
 9808: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 9809: 				  $env{'course.'.$courseid.'.domain'},
 9810: 				  'course',
 9811: 				  ([$seclevelr,   'resource'],
 9812: 				   [$seclevelm,   'map'     ],
 9813: 				   [$seclevel,    'course'  ],
 9814: 				   [$courselevelr,'resource']));
 9815: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 9816: 
 9817: # ------------------------------------------------------ third, check map parms
 9818: 	    my %parmhash=();
 9819: 	    my $thisparm='';
 9820: 	    if (tie(%parmhash,'GDBM_File',
 9821: 		    $env{'request.course.fn'}.'_parms.db',
 9822: 		    &GDBM_READER(),0640)) {
 9823: 		$thisparm=$parmhash{$symbparm};
 9824: 		untie(%parmhash);
 9825: 	    }
 9826: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
 9827: 	}
 9828: # ------------------------------------------ fourth, look in resource metadata
 9829: 
 9830: 	$spacequalifierrest=~s/\./\_/;
 9831: 	my $filename;
 9832: 	if (!$symbparm) { $symbparm=&symbread(); }
 9833: 	if ($symbparm) {
 9834: 	    $filename=(&decode_symb($symbparm))[2];
 9835: 	} else {
 9836: 	    $filename=$env{'request.filename'};
 9837: 	}
 9838: 	my $metadata=&metadata($filename,$spacequalifierrest);
 9839: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 9840: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 9841: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 9842: 
 9843: # ---------------------------------------------- fourth, look in rest of course
 9844: 	if ($symbparm && defined($courseid) && 
 9845: 	    $courseid eq $env{'request.course.id'}) {
 9846: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 9847: 				     $env{'course.'.$courseid.'.domain'},
 9848: 				     'course',
 9849: 				     ([$courselevelm,'map'   ],
 9850: 				      [$courselevel, 'course']));
 9851: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 9852: 	}
 9853: # ------------------------------------------------------------------ Cascade up
 9854: 	unless ($space eq '0') {
 9855: 	    my @parts=split(/_/,$space);
 9856: 	    my $id=pop(@parts);
 9857: 	    my $part=join('_',@parts);
 9858: 	    if ($part eq '') { $part='0'; }
 9859: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 9860: 				 $symbparm,$udom,$uname,$section,1);
 9861: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
 9862: 	}
 9863: 	if ($recurse) { return undef; }
 9864: 	my $pack_def=&packages_tab_default($filename,$varname);
 9865: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
 9866: # ---------------------------------------------------- Any other user namespace
 9867:     } elsif ($realm eq 'environment') {
 9868: # ----------------------------------------------------------------- environment
 9869: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 9870: 	    return $env{'environment.'.$spacequalifierrest};
 9871: 	} else {
 9872: 	    if ($uname eq 'anonymous' && $udom eq '') {
 9873: 		return '';
 9874: 	    }
 9875: 	    my %returnhash=&userenvironment($udom,$uname,
 9876: 					    $spacequalifierrest);
 9877: 	    return $returnhash{$spacequalifierrest};
 9878: 	}
 9879:     } elsif ($realm eq 'system') {
 9880: # ----------------------------------------------------------------- system.time
 9881: 	if ($space eq 'time') {
 9882: 	    return time;
 9883:         }
 9884:     } elsif ($realm eq 'server') {
 9885: # ----------------------------------------------------------------- system.time
 9886: 	if ($space eq 'name') {
 9887: 	    return $ENV{'SERVER_NAME'};
 9888:         }
 9889:     }
 9890:     return '';
 9891: }
 9892: 
 9893: sub get_reply {
 9894:     my ($reply_value) = @_;
 9895:     if (ref($reply_value) eq 'ARRAY') {
 9896:         if (wantarray) {
 9897: 	    return @$reply_value;
 9898:         }
 9899:         return $reply_value->[0];
 9900:     } else {
 9901:         return $reply_value;
 9902:     }
 9903: }
 9904: 
 9905: sub check_group_parms {
 9906:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
 9907:     my @groupitems = ();
 9908:     my $resultitem;
 9909:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
 9910:     foreach my $group (@{$groups}) {
 9911:         foreach my $level (@levels) {
 9912:              my $item = $courseid.'.['.$group.'].'.$level->[0];
 9913:              push(@groupitems,[$item,$level->[1]]);
 9914:         }
 9915:     }
 9916:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
 9917:                             $env{'course.'.$courseid.'.domain'},
 9918:                                      'course',@groupitems);
 9919:     return $coursereply;
 9920: }
 9921: 
 9922: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
 9923:     my ($courseid,@groups) = @_;
 9924:     @groups = sort(@groups);
 9925:     return @groups;
 9926: }
 9927: 
 9928: sub packages_tab_default {
 9929:     my ($uri,$varname)=@_;
 9930:     my (undef,$part,$name)=split(/\./,$varname);
 9931: 
 9932:     my (@extension,@specifics,$do_default);
 9933:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
 9934: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 9935: 	if ($pack_type eq 'default') {
 9936: 	    $do_default=1;
 9937: 	} elsif ($pack_type eq 'extension') {
 9938: 	    push(@extension,[$package,$pack_type,$pack_part]);
 9939: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
 9940: 	    # only look at packages defaults for packages that this id is
 9941: 	    push(@specifics,[$package,$pack_type,$pack_part]);
 9942: 	}
 9943:     }
 9944:     # first look for a package that matches the requested part id
 9945:     foreach my $package (@specifics) {
 9946: 	my (undef,$pack_type,$pack_part)=@{$package};
 9947: 	next if ($pack_part ne $part);
 9948: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 9949: 	    return $packagetab{"$pack_type&$name&default"};
 9950: 	}
 9951:     }
 9952:     # look for any possible matching non extension_ package
 9953:     foreach my $package (@specifics) {
 9954: 	my (undef,$pack_type,$pack_part)=@{$package};
 9955: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 9956: 	    return $packagetab{"$pack_type&$name&default"};
 9957: 	}
 9958: 	if ($pack_type eq 'part') { $pack_part='0'; }
 9959: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
 9960: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
 9961: 	}
 9962:     }
 9963:     # look for any posible extension_ match
 9964:     foreach my $package (@extension) {
 9965: 	my ($package,$pack_type)=@{$package};
 9966: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 9967: 	    return $packagetab{"$pack_type&$name&default"};
 9968: 	}
 9969: 	if (defined($packagetab{$package."&$name&default"})) {
 9970: 	    return $packagetab{$package."&$name&default"};
 9971: 	}
 9972:     }
 9973:     # look for a global default setting
 9974:     if ($do_default && defined($packagetab{"default&$name&default"})) {
 9975: 	return $packagetab{"default&$name&default"};
 9976:     }
 9977:     return undef;
 9978: }
 9979: 
 9980: sub add_prefix_and_part {
 9981:     my ($prefix,$part)=@_;
 9982:     my $keyroot;
 9983:     if (defined($prefix) && $prefix !~ /^__/) {
 9984: 	# prefix that has a part already
 9985: 	$keyroot=$prefix;
 9986:     } elsif (defined($prefix)) {
 9987: 	# prefix that is missing a part
 9988: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 9989:     } else {
 9990: 	# no prefix at all
 9991: 	if (defined($part)) { $keyroot='_'.$part; }
 9992:     }
 9993:     return $keyroot;
 9994: }
 9995: 
 9996: # ---------------------------------------------------------------- Get metadata
 9997: 
 9998: my %metaentry;
 9999: my %importedpartids;
10000: sub metadata {
10001:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
10002:     $uri=&declutter($uri);
10003:     # if it is a non metadata possible uri return quickly
10004:     if (($uri eq '') || 
10005: 	(($uri =~ m|^/*adm/|) && 
10006: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
10007:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
10008: 	return undef;
10009:     }
10010:     if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) 
10011: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
10012: 	return undef;
10013:     }
10014:     my $filename=$uri;
10015:     $uri=~s/\.meta$//;
10016: #
10017: # Is the metadata already cached?
10018: # Look at timestamp of caching
10019: # Everything is cached by the main uri, libraries are never directly cached
10020: #
10021:     if (!defined($liburi)) {
10022: 	my ($result,$cached)=&is_cached_new('meta',$uri);
10023: 	if (defined($cached)) { return $result->{':'.$what}; }
10024:     }
10025:     {
10026: # Imported parts would go here
10027:         my %importedids=();
10028:         my @origfileimportpartids=();
10029:         my $importedparts=0;
10030: #
10031: # Is this a recursive call for a library?
10032: #
10033: #	if (! exists($metacache{$uri})) {
10034: #	    $metacache{$uri}={};
10035: #	}
10036: 	my $cachetime = 60*60;
10037:         if ($liburi) {
10038: 	    $liburi=&declutter($liburi);
10039:             $filename=$liburi;
10040:         } else {
10041: 	    &devalidate_cache_new('meta',$uri);
10042: 	    undef(%metaentry);
10043: 	}
10044:         my %metathesekeys=();
10045:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
10046: 	my $metastring;
10047: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
10048: 	    my $which = &hreflocation('','/'.($liburi || $uri));
10049: 	    $metastring = 
10050: 		&Apache::lonnet::ssi_body($which,
10051: 					  ('grade_target' => 'meta'));
10052: 	    $cachetime = 1; # only want this cached in the child not long term
10053: 	} elsif (($uri !~ m -^(editupload)/-) && 
10054:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
10055: 	    my $file=&filelocation('',&clutter($filename));
10056: 	    #push(@{$metaentry{$uri.'.file'}},$file);
10057: 	    $metastring=&getfile($file);
10058: 	}
10059:         my $parser=HTML::LCParser->new(\$metastring);
10060:         my $token;
10061:         undef %metathesekeys;
10062:         while ($token=$parser->get_token) {
10063: 	    if ($token->[0] eq 'S') {
10064: 		if (defined($token->[2]->{'package'})) {
10065: #
10066: # This is a package - get package info
10067: #
10068: 		    my $package=$token->[2]->{'package'};
10069: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10070: 		    if (defined($token->[2]->{'id'})) { 
10071: 			$keyroot.='_'.$token->[2]->{'id'}; 
10072: 		    }
10073: 		    if ($metaentry{':packages'}) {
10074: 			$metaentry{':packages'}.=','.$package.$keyroot;
10075: 		    } else {
10076: 			$metaentry{':packages'}=$package.$keyroot;
10077: 		    }
10078: 		    foreach my $pack_entry (keys(%packagetab)) {
10079: 			my $part=$keyroot;
10080: 			$part=~s/^\_//;
10081: 			if ($pack_entry=~/^\Q$package\E\&/ || 
10082: 			    $pack_entry=~/^\Q$package\E_0\&/) {
10083: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
10084: 			    # ignore package.tab specified default values
10085:                             # here &package_tab_default() will fetch those
10086: 			    if ($subp eq 'default') { next; }
10087: 			    my $value=$packagetab{$pack_entry};
10088: 			    my $unikey;
10089: 			    if ($pack =~ /_0$/) {
10090: 				$unikey='parameter_0_'.$name;
10091: 				$part=0;
10092: 			    } else {
10093: 				$unikey='parameter'.$keyroot.'_'.$name;
10094: 			    }
10095: 			    if ($subp eq 'display') {
10096: 				$value.=' [Part: '.$part.']';
10097: 			    }
10098: 			    $metaentry{':'.$unikey.'.part'}=$part;
10099: 			    $metathesekeys{$unikey}=1;
10100: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10101: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
10102: 			    }
10103: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
10104: 				$metaentry{':'.$unikey}=
10105: 				    $metaentry{':'.$unikey.'.default'};
10106: 			    }
10107: 			}
10108: 		    }
10109: 		} else {
10110: #
10111: # This is not a package - some other kind of start tag
10112: #
10113: 		    my $entry=$token->[1];
10114: 		    my $unikey='';
10115: 
10116: 		    if ($entry eq 'import') {
10117: #
10118: # Importing a library here
10119: #
10120:                         my $location=$parser->get_text('/import');
10121:                         my $dir=$filename;
10122:                         $dir=~s|[^/]*$||;
10123:                         $location=&filelocation($dir,$location);
10124:                        
10125:                         my $importmode=$token->[2]->{'importmode'};
10126:                         if ($importmode eq 'problem') {
10127: # Import as problem/response
10128:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10129:                         } elsif ($importmode eq 'part') {
10130: # Import as part(s)
10131:                            $importedparts=1;
10132: # We need to get the original file and the imported file to get the part order correct
10133: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
10134: # Load and inspect original file
10135:                            if ($#origfileimportpartids<0) {
10136:                               undef(%importedpartids);
10137:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
10138:                               my $origfile=&getfile($origfilelocation);
10139:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10140:                            }
10141: 
10142: # Load and inspect imported file
10143:                            my $impfile=&getfile($location);
10144:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10145:                            if ($#impfilepartids>=0) {
10146: # This problem had parts
10147:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
10148:                            } else {
10149: # Importing by turning a single problem into a problem part
10150: # It gets the import-tags ID as part-ID
10151:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
10152:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
10153:                            }
10154:                         } else {
10155: # Normal import
10156:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10157:                            if (defined($token->[2]->{'id'})) {
10158:                               $unikey.='_'.$token->[2]->{'id'};
10159:                            }
10160:                         }
10161: 
10162: 			if ($depthcount<20) {
10163: 			    my $metadata = 
10164: 				&metadata($uri,'keys', $location,$unikey,
10165: 					  $depthcount+1);
10166: 			    foreach my $meta (split(',',$metadata)) {
10167: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
10168: 				$metathesekeys{$meta}=1;
10169: 			    }
10170: 			
10171:                         }
10172: 		    } else {
10173: #
10174: # Not importing, some other kind of non-package, non-library start tag
10175: # 
10176:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
10177:                         if (defined($token->[2]->{'id'})) {
10178:                             $unikey.='_'.$token->[2]->{'id'};
10179:                         }
10180: 			if (defined($token->[2]->{'name'})) { 
10181: 			    $unikey.='_'.$token->[2]->{'name'}; 
10182: 			}
10183: 			$metathesekeys{$unikey}=1;
10184: 			foreach my $param (@{$token->[3]}) {
10185: 			    $metaentry{':'.$unikey.'.'.$param} =
10186: 				$token->[2]->{$param};
10187: 			}
10188: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
10189: 			my $default=$metaentry{':'.$unikey.'.default'};
10190: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
10191: 		 # only ws inside the tag, and not in default, so use default
10192: 		 # as value
10193: 			    $metaentry{':'.$unikey}=$default;
10194: 			} elsif ( $internaltext =~ /\S/ ) {
10195: 		  # something interesting inside the tag
10196: 			    $metaentry{':'.$unikey}=$internaltext;
10197: 			} else {
10198: 		  # no interesting values, don't set a default
10199: 			}
10200: # end of not-a-package not-a-library import
10201: 		    }
10202: # end of not-a-package start tag
10203: 		}
10204: # the next is the end of "start tag"
10205: 	    }
10206: 	}
10207: 	my ($extension) = ($uri =~ /\.(\w+)$/);
10208: 	$extension = lc($extension);
10209: 	if ($extension eq 'htm') { $extension='html'; }
10210: 
10211: 	foreach my $key (keys(%packagetab)) {
10212: 	    #no specific packages #how's our extension
10213: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
10214: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
10215: 					 \%metathesekeys);
10216: 	}
10217: 
10218: 	if (!exists($metaentry{':packages'})
10219: 	    || $packagetab{"import_defaults&extension_$extension"}) {
10220: 	    foreach my $key (keys(%packagetab)) {
10221: 		#no specific packages well let's get default then
10222: 		if ($key!~/^default&/) { next; }
10223: 		&metadata_create_package_def($uri,$key,'default',
10224: 					     \%metathesekeys);
10225: 	    }
10226: 	}
10227: # are there custom rights to evaluate
10228: 	if ($metaentry{':copyright'} eq 'custom') {
10229: 
10230:     #
10231:     # Importing a rights file here
10232:     #
10233: 	    unless ($depthcount) {
10234: 		my $location=$metaentry{':customdistributionfile'};
10235: 		my $dir=$filename;
10236: 		$dir=~s|[^/]*$||;
10237: 		$location=&filelocation($dir,$location);
10238: 		my $rights_metadata =
10239: 		    &metadata($uri,'keys',$location,'_rights',
10240: 			      $depthcount+1);
10241: 		foreach my $rights (split(',',$rights_metadata)) {
10242: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
10243: 		    $metathesekeys{$rights}=1;
10244: 		}
10245: 	    }
10246: 	}
10247: 	# uniqifiy package listing
10248: 	my %seen;
10249: 	my @uniq_packages =
10250: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
10251: 	$metaentry{':packages'} = join(',',@uniq_packages);
10252: 
10253:         if ($importedparts) {
10254: # We had imported parts and need to rebuild partorder
10255:            $metaentry{':partorder'}='';
10256:            $metathesekeys{'partorder'}=1;
10257:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
10258:                if ($origfileimportpartids[$index] eq 'part') {
10259: # original part, part of the problem
10260:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
10261:                } else {
10262: # we have imported parts at this position
10263:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
10264:                }
10265:            }
10266:            $metaentry{':partorder'}=~s/^\,//;
10267:         }
10268: 
10269: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
10270: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
10271: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
10272: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
10273: # this is the end of "was not already recently cached
10274:     }
10275:     return $metaentry{':'.$what};
10276: }
10277: 
10278: sub metadata_create_package_def {
10279:     my ($uri,$key,$package,$metathesekeys)=@_;
10280:     my ($pack,$name,$subp)=split(/\&/,$key);
10281:     if ($subp eq 'default') { next; }
10282:     
10283:     if (defined($metaentry{':packages'})) {
10284: 	$metaentry{':packages'}.=','.$package;
10285:     } else {
10286: 	$metaentry{':packages'}=$package;
10287:     }
10288:     my $value=$packagetab{$key};
10289:     my $unikey;
10290:     $unikey='parameter_0_'.$name;
10291:     $metaentry{':'.$unikey.'.part'}=0;
10292:     $$metathesekeys{$unikey}=1;
10293:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10294: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
10295:     }
10296:     if (defined($metaentry{':'.$unikey.'.default'})) {
10297: 	$metaentry{':'.$unikey}=
10298: 	    $metaentry{':'.$unikey.'.default'};
10299:     }
10300: }
10301: 
10302: sub metadata_generate_part0 {
10303:     my ($metadata,$metacache,$uri) = @_;
10304:     my %allnames;
10305:     foreach my $metakey (keys(%$metadata)) {
10306: 	if ($metakey=~/^parameter\_(.*)/) {
10307: 	  my $part=$$metacache{':'.$metakey.'.part'};
10308: 	  my $name=$$metacache{':'.$metakey.'.name'};
10309: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
10310: 	    $allnames{$name}=$part;
10311: 	  }
10312: 	}
10313:     }
10314:     foreach my $name (keys(%allnames)) {
10315:       $$metadata{"parameter_0_$name"}=1;
10316:       my $key=":parameter_0_$name";
10317:       $$metacache{"$key.part"}='0';
10318:       $$metacache{"$key.name"}=$name;
10319:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
10320: 					   $allnames{$name}.'_'.$name.
10321: 					   '.type'};
10322:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
10323: 			     '.display'};
10324:       my $expr='[Part: '.$allnames{$name}.']';
10325:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
10326:       $$metacache{"$key.display"}=$olddis;
10327:     }
10328: }
10329: 
10330: # ------------------------------------------------------ Devalidate title cache
10331: 
10332: sub devalidate_title_cache {
10333:     my ($url)=@_;
10334:     if (!$env{'request.course.id'}) { return; }
10335:     my $symb=&symbread($url);
10336:     if (!$symb) { return; }
10337:     my $key=$env{'request.course.id'}."\0".$symb;
10338:     &devalidate_cache_new('title',$key);
10339: }
10340: 
10341: # ------------------------------------------------- Get the title of a course
10342: 
10343: sub current_course_title {
10344:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
10345: }
10346: # ------------------------------------------------- Get the title of a resource
10347: 
10348: sub gettitle {
10349:     my $urlsymb=shift;
10350:     my $symb=&symbread($urlsymb);
10351:     if ($symb) {
10352: 	my $key=$env{'request.course.id'}."\0".$symb;
10353: 	my ($result,$cached)=&is_cached_new('title',$key);
10354: 	if (defined($cached)) { 
10355: 	    return $result;
10356: 	}
10357: 	my ($map,$resid,$url)=&decode_symb($symb);
10358: 	my $title='';
10359: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
10360: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
10361: 	} else {
10362: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10363: 		    &GDBM_READER(),0640)) {
10364: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
10365: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
10366: 		untie(%bighash);
10367: 	    }
10368: 	}
10369: 	$title=~s/\&colon\;/\:/gs;
10370: 	if ($title) {
10371: # Remember both $symb and $title for dynamic metadata
10372:             $accesshash{$symb.'___crstitle'}=$title;
10373:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
10374: # Cache this title and then return it
10375: 	    return &do_cache_new('title',$key,$title,600);
10376: 	}
10377: 	$urlsymb=$url;
10378:     }
10379:     my $title=&metadata($urlsymb,'title');
10380:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
10381:     return $title;
10382: }
10383: 
10384: sub get_slot {
10385:     my ($which,$cnum,$cdom)=@_;
10386:     if (!$cnum || !$cdom) {
10387: 	(undef,my $courseid)=&whichuser();
10388: 	$cdom=$env{'course.'.$courseid.'.domain'};
10389: 	$cnum=$env{'course.'.$courseid.'.num'};
10390:     }
10391:     my $key=join("\0",'slots',$cdom,$cnum,$which);
10392:     my %slotinfo;
10393:     if (exists($remembered{$key})) {
10394: 	$slotinfo{$which} = $remembered{$key};
10395:     } else {
10396: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
10397: 	&Apache::lonhomework::showhash(%slotinfo);
10398: 	my ($tmp)=keys(%slotinfo);
10399: 	if ($tmp=~/^error:/) { return (); }
10400: 	$remembered{$key} = $slotinfo{$which};
10401:     }
10402:     if (ref($slotinfo{$which}) eq 'HASH') {
10403: 	return %{$slotinfo{$which}};
10404:     }
10405:     return $slotinfo{$which};
10406: }
10407: 
10408: sub get_reservable_slots {
10409:     my ($cnum,$cdom,$uname,$udom) = @_;
10410:     my $now = time;
10411:     my $reservable_info;
10412:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
10413:     if (exists($remembered{$key})) {
10414:         $reservable_info = $remembered{$key};
10415:     } else {
10416:         my %resv;
10417:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
10418:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
10419:         $reservable_info = \%resv;
10420:         $remembered{$key} = $reservable_info;
10421:     }
10422:     return $reservable_info;
10423: }
10424: 
10425: sub get_course_slots {
10426:     my ($cnum,$cdom) = @_;
10427:     my $hashid=$cnum.':'.$cdom;
10428:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
10429:     if (defined($cached)) {
10430:         if (ref($result) eq 'HASH') {
10431:             return %{$result};
10432:         }
10433:     } else {
10434:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
10435:         my ($tmp) = keys(%slots);
10436:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
10437:             &do_cache_new('allslots',$hashid,\%slots,600);
10438:             return %slots;
10439:         }
10440:     }
10441:     return;
10442: }
10443: 
10444: sub devalidate_slots_cache {
10445:     my ($cnum,$cdom)=@_;
10446:     my $hashid=$cnum.':'.$cdom;
10447:     &devalidate_cache_new('allslots',$hashid);
10448: }
10449: 
10450: sub get_coursechange {
10451:     my ($cdom,$cnum) = @_;
10452:     if ($cdom eq '' || $cnum eq '') {
10453:         return unless ($env{'request.course.id'});
10454:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10455:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10456:     }
10457:     my $hashid=$cdom.'_'.$cnum;
10458:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
10459:     if ((defined($cached)) && ($change ne '')) {
10460:         return $change;
10461:     } else {
10462:         my %crshash;
10463:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
10464:         if ($crshash{'internal.contentchange'} eq '') {
10465:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
10466:             if ($change eq '') {
10467:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
10468:                 $change = $crshash{'internal.created'};
10469:             }
10470:         } else {
10471:             $change = $crshash{'internal.contentchange'};
10472:         }
10473:         my $cachetime = 600;
10474:         &do_cache_new('crschange',$hashid,$change,$cachetime);
10475:     }
10476:     return $change;
10477: }
10478: 
10479: sub devalidate_coursechange_cache {
10480:     my ($cnum,$cdom)=@_;
10481:     my $hashid=$cnum.':'.$cdom;
10482:     &devalidate_cache_new('crschange',$hashid);
10483: }
10484: 
10485: # ------------------------------------------------- Update symbolic store links
10486: 
10487: sub symblist {
10488:     my ($mapname,%newhash)=@_;
10489:     $mapname=&deversion(&declutter($mapname));
10490:     my %hash;
10491:     if (($env{'request.course.fn'}) && (%newhash)) {
10492:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
10493:                       &GDBM_WRCREAT(),0640)) {
10494: 	    foreach my $url (keys(%newhash)) {
10495: 		next if ($url eq 'last_known'
10496: 			 && $env{'form.no_update_last_known'});
10497: 		$hash{declutter($url)}=&encode_symb($mapname,
10498: 						    $newhash{$url}->[1],
10499: 						    $newhash{$url}->[0]);
10500:             }
10501:             if (untie(%hash)) {
10502: 		return 'ok';
10503:             }
10504:         }
10505:     }
10506:     return 'error';
10507: }
10508: 
10509: # --------------------------------------------------------------- Verify a symb
10510: 
10511: sub symbverify {
10512:     my ($symb,$thisurl,$encstate)=@_;
10513:     my $thisfn=$thisurl;
10514:     $thisfn=&declutter($thisfn);
10515: # direct jump to resource in page or to a sequence - will construct own symbs
10516:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
10517: # check URL part
10518:     my ($map,$resid,$url)=&decode_symb($symb);
10519: 
10520:     unless ($url eq $thisfn) { return 0; }
10521: 
10522:     $symb=&symbclean($symb);
10523:     $thisurl=&deversion($thisurl);
10524:     $thisfn=&deversion($thisfn);
10525: 
10526:     my %bighash;
10527:     my $okay=0;
10528: 
10529:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10530:                             &GDBM_READER(),0640)) {
10531:         my $noclutter;
10532:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
10533:             $thisurl =~ s/\?.+$//;
10534:             if ($map =~ m{^uploaded/.+\.page$}) {
10535:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
10536:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
10537:                 $noclutter = 1;
10538:             }
10539:         }
10540:         my $ids;
10541:         if ($noclutter) {
10542:             $ids=$bighash{'ids_'.$thisurl};
10543:         } else {
10544:             $ids=$bighash{'ids_'.&clutter($thisurl)};
10545:         }
10546:         unless ($ids) {
10547:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
10548:             $ids=$bighash{$idkey};
10549:         }
10550:         if ($ids) {
10551: # ------------------------------------------------------------------- Has ID(s)
10552:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
10553:                 $symb =~ s/\?.+$//;
10554:             }
10555: 	    foreach my $id (split(/\,/,$ids)) {
10556: 	       my ($mapid,$resid)=split(/\./,$id);
10557:                if (
10558:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
10559:    eq $symb) {
10560:                    if (ref($encstate)) {
10561:                        $$encstate = $bighash{'encrypted_'.$id};
10562:                    }
10563: 		   if (($env{'request.role.adv'}) ||
10564: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
10565:                        ($thisurl eq '/adm/navmaps')) {
10566: 		       $okay=1;
10567:                        last;
10568: 		   }
10569: 	       }
10570: 	   }
10571:         }
10572: 	untie(%bighash);
10573:     }
10574:     return $okay;
10575: }
10576: 
10577: # --------------------------------------------------------------- Clean-up symb
10578: 
10579: sub symbclean {
10580:     my $symb=shift;
10581:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10582: # remove version from map
10583:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
10584: 
10585: # remove version from URL
10586:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
10587: 
10588: # remove wrapper
10589: 
10590:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
10591:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
10592:     return $symb;
10593: }
10594: 
10595: # ---------------------------------------------- Split symb to find map and url
10596: 
10597: sub encode_symb {
10598:     my ($map,$resid,$url)=@_;
10599:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
10600: }
10601: 
10602: sub decode_symb {
10603:     my $symb=shift;
10604:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10605:     my ($map,$resid,$url)=split(/___/,$symb);
10606:     return (&fixversion($map),$resid,&fixversion($url));
10607: }
10608: 
10609: sub fixversion {
10610:     my $fn=shift;
10611:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
10612:     my %bighash;
10613:     my $uri=&clutter($fn);
10614:     my $key=$env{'request.course.id'}.'_'.$uri;
10615: # is this cached?
10616:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
10617:     if (defined($cached)) { return $result; }
10618: # unfortunately not cached, or expired
10619:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10620: 	    &GDBM_READER(),0640)) {
10621:  	if ($bighash{'version_'.$uri}) {
10622:  	    my $version=$bighash{'version_'.$uri};
10623:  	    unless (($version eq 'mostrecent') || 
10624: 		    ($version==&getversion($uri))) {
10625:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
10626:  	    }
10627:  	}
10628:  	untie %bighash;
10629:     }
10630:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
10631: }
10632: 
10633: sub deversion {
10634:     my $url=shift;
10635:     $url=~s/\.\d+\.(\w+)$/\.$1/;
10636:     return $url;
10637: }
10638: 
10639: # ------------------------------------------------------ Return symb list entry
10640: 
10641: sub symbread {
10642:     my ($thisfn,$donotrecurse)=@_;
10643:     my $cache_str;
10644:     if ($thisfn ne '') {
10645:         $cache_str='request.symbread.cached.'.$thisfn;
10646:         if ($env{$cache_str} ne '') {
10647:             return $env{$cache_str};
10648:         }
10649:     } else {
10650: # no filename provided? try from environment
10651:         if ($env{'request.symb'}) {
10652: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
10653: 	}
10654: 	$thisfn=$env{'request.filename'};
10655:     }
10656:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
10657: # is that filename actually a symb? Verify, clean, and return
10658:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
10659: 	if (&symbverify($thisfn,$1)) {
10660: 	    return $env{$cache_str}=&symbclean($thisfn);
10661: 	}
10662:     }
10663:     $thisfn=declutter($thisfn);
10664:     my %hash;
10665:     my %bighash;
10666:     my $syval='';
10667:     if (($env{'request.course.fn'}) && ($thisfn)) {
10668:         my $targetfn = $thisfn;
10669:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
10670:             $targetfn = 'adm/wrapper/'.$thisfn;
10671:         }
10672: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
10673: 	    $targetfn=$1;
10674: 	}
10675:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
10676:                       &GDBM_READER(),0640)) {
10677: 	    $syval=$hash{$targetfn};
10678:             untie(%hash);
10679:         }
10680: # ---------------------------------------------------------- There was an entry
10681:         if ($syval) {
10682: 	    #unless ($syval=~/\_\d+$/) {
10683: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
10684: 		    #&appenv({'request.ambiguous' => $thisfn});
10685: 		    #return $env{$cache_str}='';
10686: 		#}    
10687: 		#$syval.=$1;
10688: 	    #}
10689:         } else {
10690: # ------------------------------------------------------- Was not in symb table
10691:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10692:                             &GDBM_READER(),0640)) {
10693: # ---------------------------------------------- Get ID(s) for current resource
10694:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
10695:               unless ($ids) { 
10696:                  $ids=$bighash{'ids_/'.$thisfn};
10697:               }
10698:               unless ($ids) {
10699: # alias?
10700: 		  $ids=$bighash{'mapalias_'.$thisfn};
10701:               }
10702:               if ($ids) {
10703: # ------------------------------------------------------------------- Has ID(s)
10704:                  my @possibilities=split(/\,/,$ids);
10705:                  if ($#possibilities==0) {
10706: # ----------------------------------------------- There is only one possibility
10707: 		     my ($mapid,$resid)=split(/\./,$ids);
10708: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
10709: 						    $resid,$thisfn);
10710:                  } elsif (!$donotrecurse) {
10711: # ------------------------------------------ There is more than one possibility
10712:                      my $realpossible=0;
10713:                      foreach my $id (@possibilities) {
10714: 			 my $file=$bighash{'src_'.$id};
10715:                          if (&allowed('bre',$file)) {
10716:          		    my ($mapid,$resid)=split(/\./,$id);
10717:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
10718: 				$realpossible++;
10719:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
10720: 						    $resid,$thisfn);
10721:                             }
10722: 			 }
10723:                      }
10724: 		     if ($realpossible!=1) { $syval=''; }
10725:                  } else {
10726:                      $syval='';
10727:                  }
10728: 	      }
10729:               untie(%bighash)
10730:            }
10731:         }
10732:         if ($syval) {
10733: 	    return $env{$cache_str}=$syval;
10734:         }
10735:     }
10736:     &appenv({'request.ambiguous' => $thisfn});
10737:     return $env{$cache_str}='';
10738: }
10739: 
10740: # ---------------------------------------------------------- Return random seed
10741: 
10742: sub numval {
10743:     my $txt=shift;
10744:     $txt=~tr/A-J/0-9/;
10745:     $txt=~tr/a-j/0-9/;
10746:     $txt=~tr/K-T/0-9/;
10747:     $txt=~tr/k-t/0-9/;
10748:     $txt=~tr/U-Z/0-5/;
10749:     $txt=~tr/u-z/0-5/;
10750:     $txt=~s/\D//g;
10751:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
10752:     return int($txt);
10753: }
10754: 
10755: sub numval2 {
10756:     my $txt=shift;
10757:     $txt=~tr/A-J/0-9/;
10758:     $txt=~tr/a-j/0-9/;
10759:     $txt=~tr/K-T/0-9/;
10760:     $txt=~tr/k-t/0-9/;
10761:     $txt=~tr/U-Z/0-5/;
10762:     $txt=~tr/u-z/0-5/;
10763:     $txt=~s/\D//g;
10764:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10765:     my $total;
10766:     foreach my $val (@txts) { $total+=$val; }
10767:     if ($_64bit) { if ($total > 2**32) { return -1; } }
10768:     return int($total);
10769: }
10770: 
10771: sub numval3 {
10772:     use integer;
10773:     my $txt=shift;
10774:     $txt=~tr/A-J/0-9/;
10775:     $txt=~tr/a-j/0-9/;
10776:     $txt=~tr/K-T/0-9/;
10777:     $txt=~tr/k-t/0-9/;
10778:     $txt=~tr/U-Z/0-5/;
10779:     $txt=~tr/u-z/0-5/;
10780:     $txt=~s/\D//g;
10781:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10782:     my $total;
10783:     foreach my $val (@txts) { $total+=$val; }
10784:     if ($_64bit) { $total=(($total<<32)>>32); }
10785:     return $total;
10786: }
10787: 
10788: sub digest {
10789:     my ($data)=@_;
10790:     my $digest=&Digest::MD5::md5($data);
10791:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
10792:     my ($e,$f);
10793:     {
10794:         use integer;
10795:         $e=($a+$b);
10796:         $f=($c+$d);
10797:         if ($_64bit) {
10798:             $e=(($e<<32)>>32);
10799:             $f=(($f<<32)>>32);
10800:         }
10801:     }
10802:     if (wantarray) {
10803: 	return ($e,$f);
10804:     } else {
10805: 	my $g;
10806: 	{
10807: 	    use integer;
10808: 	    $g=($e+$f);
10809: 	    if ($_64bit) {
10810: 		$g=(($g<<32)>>32);
10811: 	    }
10812: 	}
10813: 	return $g;
10814:     }
10815: }
10816: 
10817: sub latest_rnd_algorithm_id {
10818:     return '64bit5';
10819: }
10820: 
10821: sub get_rand_alg {
10822:     my ($courseid)=@_;
10823:     if (!$courseid) { $courseid=(&whichuser())[1]; }
10824:     if ($courseid) {
10825: 	return $env{"course.$courseid.rndseed"};
10826:     }
10827:     return &latest_rnd_algorithm_id();
10828: }
10829: 
10830: sub validCODE {
10831:     my ($CODE)=@_;
10832:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
10833:     return 0;
10834: }
10835: 
10836: sub getCODE {
10837:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
10838:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
10839: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
10840: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
10841: 	return $Apache::lonhomework::history{'resource.CODE'};
10842:     }
10843:     return undef;
10844: }
10845: #
10846: #  Determines the random seed for a specific context:
10847: #
10848: # parameters:
10849: #   symb      - in course context the symb for the seed.
10850: #   course_id - The course id of the form domain_coursenum.
10851: #   domain    - Domain for the user.
10852: #   course    - Course for the user.
10853: #   cenv      - environment of the course.
10854: #
10855: # NOTE:
10856: #   All parameters are picked out of the environment if missing
10857: #   or not defined.
10858: #   If a symb cannot be determined the current time is used instead.
10859: #
10860: #  For a given well defined symb, courside, domain, username,
10861: #  and course environment, the seed is reproducible.
10862: #
10863: sub rndseed {
10864:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
10865:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
10866:     if (!defined($symb)) {
10867: 	unless ($symb=$wsymb) { return time; }
10868:     }
10869:     if (!defined $courseid) { 
10870: 	$courseid=$wcourseid; 
10871:     }
10872:     if (!defined $domain) { $domain=$wdomain; }
10873:     if (!defined $username) { $username=$wusername }
10874: 
10875:     my $which;
10876:     if (defined($cenv->{'rndseed'})) {
10877: 	$which = $cenv->{'rndseed'};
10878:     } else {
10879: 	$which =&get_rand_alg($courseid);
10880:     }
10881:     if (defined(&getCODE())) {
10882: 
10883: 	if ($which eq '64bit5') {
10884: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
10885: 	} elsif ($which eq '64bit4') {
10886: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
10887: 	} else {
10888: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
10889: 	}
10890:     } elsif ($which eq '64bit5') {
10891: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
10892:     } elsif ($which eq '64bit4') {
10893: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
10894:     } elsif ($which eq '64bit3') {
10895: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
10896:     } elsif ($which eq '64bit2') {
10897: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
10898:     } elsif ($which eq '64bit') {
10899: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
10900:     }
10901:     return &rndseed_32bit($symb,$courseid,$domain,$username);
10902: }
10903: 
10904: sub rndseed_32bit {
10905:     my ($symb,$courseid,$domain,$username)=@_;
10906:     {
10907: 	use integer;
10908: 	my $symbchck=unpack("%32C*",$symb) << 27;
10909: 	my $symbseed=numval($symb) << 22;
10910: 	my $namechck=unpack("%32C*",$username) << 17;
10911: 	my $nameseed=numval($username) << 12;
10912: 	my $domainseed=unpack("%32C*",$domain) << 7;
10913: 	my $courseseed=unpack("%32C*",$courseid);
10914: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
10915: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10916: 	#&logthis("rndseed :$num:$symb");
10917: 	if ($_64bit) { $num=(($num<<32)>>32); }
10918: 	return $num;
10919:     }
10920: }
10921: 
10922: sub rndseed_64bit {
10923:     my ($symb,$courseid,$domain,$username)=@_;
10924:     {
10925: 	use integer;
10926: 	my $symbchck=unpack("%32S*",$symb) << 21;
10927: 	my $symbseed=numval($symb) << 10;
10928: 	my $namechck=unpack("%32S*",$username);
10929: 	
10930: 	my $nameseed=numval($username) << 21;
10931: 	my $domainseed=unpack("%32S*",$domain) << 10;
10932: 	my $courseseed=unpack("%32S*",$courseid);
10933: 	
10934: 	my $num1=$symbchck+$symbseed+$namechck;
10935: 	my $num2=$nameseed+$domainseed+$courseseed;
10936: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10937: 	#&logthis("rndseed :$num:$symb");
10938: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10939: 	return "$num1,$num2";
10940:     }
10941: }
10942: 
10943: sub rndseed_64bit2 {
10944:     my ($symb,$courseid,$domain,$username)=@_;
10945:     {
10946: 	use integer;
10947: 	# strings need to be an even # of cahracters long, it it is odd the
10948:         # last characters gets thrown away
10949: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
10950: 	my $symbseed=numval($symb) << 10;
10951: 	my $namechck=unpack("%32S*",$username.' ');
10952: 	
10953: 	my $nameseed=numval($username) << 21;
10954: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
10955: 	my $courseseed=unpack("%32S*",$courseid.' ');
10956: 	
10957: 	my $num1=$symbchck+$symbseed+$namechck;
10958: 	my $num2=$nameseed+$domainseed+$courseseed;
10959: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10960: 	#&logthis("rndseed :$num:$symb");
10961: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10962: 	return "$num1,$num2";
10963:     }
10964: }
10965: 
10966: sub rndseed_64bit3 {
10967:     my ($symb,$courseid,$domain,$username)=@_;
10968:     {
10969: 	use integer;
10970: 	# strings need to be an even # of cahracters long, it it is odd the
10971:         # last characters gets thrown away
10972: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
10973: 	my $symbseed=numval2($symb) << 10;
10974: 	my $namechck=unpack("%32S*",$username.' ');
10975: 	
10976: 	my $nameseed=numval2($username) << 21;
10977: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
10978: 	my $courseseed=unpack("%32S*",$courseid.' ');
10979: 	
10980: 	my $num1=$symbchck+$symbseed+$namechck;
10981: 	my $num2=$nameseed+$domainseed+$courseseed;
10982: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10983: 	#&logthis("rndseed :$num1:$num2:$_64bit");
10984: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10985: 	
10986: 	return "$num1:$num2";
10987:     }
10988: }
10989: 
10990: sub rndseed_64bit4 {
10991:     my ($symb,$courseid,$domain,$username)=@_;
10992:     {
10993: 	use integer;
10994: 	# strings need to be an even # of cahracters long, it it is odd the
10995:         # last characters gets thrown away
10996: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
10997: 	my $symbseed=numval3($symb) << 10;
10998: 	my $namechck=unpack("%32S*",$username.' ');
10999: 	
11000: 	my $nameseed=numval3($username) << 21;
11001: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
11002: 	my $courseseed=unpack("%32S*",$courseid.' ');
11003: 	
11004: 	my $num1=$symbchck+$symbseed+$namechck;
11005: 	my $num2=$nameseed+$domainseed+$courseseed;
11006: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11007: 	#&logthis("rndseed :$num1:$num2:$_64bit");
11008: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11009: 	
11010: 	return "$num1:$num2";
11011:     }
11012: }
11013: 
11014: sub rndseed_64bit5 {
11015:     my ($symb,$courseid,$domain,$username)=@_;
11016:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
11017:     return "$num1:$num2";
11018: }
11019: 
11020: sub rndseed_CODE_64bit {
11021:     my ($symb,$courseid,$domain,$username)=@_;
11022:     {
11023: 	use integer;
11024: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
11025: 	my $symbseed=numval2($symb);
11026: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11027: 	my $CODEseed=numval(&getCODE());
11028: 	my $courseseed=unpack("%32S*",$courseid.' ');
11029: 	my $num1=$symbseed+$CODEchck;
11030: 	my $num2=$CODEseed+$courseseed+$symbchck;
11031: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11032: 	#&logthis("rndseed :$num1:$num2:$symb");
11033: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
11034: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
11035: 	return "$num1:$num2";
11036:     }
11037: }
11038: 
11039: sub rndseed_CODE_64bit4 {
11040:     my ($symb,$courseid,$domain,$username)=@_;
11041:     {
11042: 	use integer;
11043: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
11044: 	my $symbseed=numval3($symb);
11045: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11046: 	my $CODEseed=numval3(&getCODE());
11047: 	my $courseseed=unpack("%32S*",$courseid.' ');
11048: 	my $num1=$symbseed+$CODEchck;
11049: 	my $num2=$CODEseed+$courseseed+$symbchck;
11050: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11051: 	#&logthis("rndseed :$num1:$num2:$symb");
11052: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
11053: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
11054: 	return "$num1:$num2";
11055:     }
11056: }
11057: 
11058: sub rndseed_CODE_64bit5 {
11059:     my ($symb,$courseid,$domain,$username)=@_;
11060:     my $code = &getCODE();
11061:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
11062:     return "$num1:$num2";
11063: }
11064: 
11065: sub setup_random_from_rndseed {
11066:     my ($rndseed)=@_;
11067:     if ($rndseed =~/([,:])/) {
11068: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
11069: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
11070:     } else {
11071: 	&Math::Random::random_set_seed_from_phrase($rndseed);
11072:     }
11073: }
11074: 
11075: sub latest_receipt_algorithm_id {
11076:     return 'receipt3';
11077: }
11078: 
11079: sub recunique {
11080:     my $fucourseid=shift;
11081:     my $unique;
11082:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
11083: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
11084: 	$unique=$env{"course.$fucourseid.internal.encseed"};
11085:     } else {
11086: 	$unique=$perlvar{'lonReceipt'};
11087:     }
11088:     return unpack("%32C*",$unique);
11089: }
11090: 
11091: sub recprefix {
11092:     my $fucourseid=shift;
11093:     my $prefix;
11094:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
11095: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
11096: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
11097:     } else {
11098: 	$prefix=$perlvar{'lonHostID'};
11099:     }
11100:     return unpack("%32C*",$prefix);
11101: }
11102: 
11103: sub ireceipt {
11104:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
11105: 
11106:     my $return =&recprefix($fucourseid).'-';
11107: 
11108:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
11109: 	$env{'request.state'} eq 'construct') {
11110: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
11111: 	return $return;
11112:     }
11113: 
11114:     my $cuname=unpack("%32C*",$funame);
11115:     my $cudom=unpack("%32C*",$fudom);
11116:     my $cucourseid=unpack("%32C*",$fucourseid);
11117:     my $cusymb=unpack("%32C*",$fusymb);
11118:     my $cunique=&recunique($fucourseid);
11119:     my $cpart=unpack("%32S*",$part);
11120:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
11121: 
11122: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
11123: 			       
11124: 	$return.= ($cunique%$cuname+
11125: 		   $cunique%$cudom+
11126: 		   $cusymb%$cuname+
11127: 		   $cusymb%$cudom+
11128: 		   $cucourseid%$cuname+
11129: 		   $cucourseid%$cudom+
11130: 		   $cpart%$cuname+
11131: 		   $cpart%$cudom);
11132:     } else {
11133: 	$return.= ($cunique%$cuname+
11134: 		   $cunique%$cudom+
11135: 		   $cusymb%$cuname+
11136: 		   $cusymb%$cudom+
11137: 		   $cucourseid%$cuname+
11138: 		   $cucourseid%$cudom);
11139:     }
11140:     return $return;
11141: }
11142: 
11143: sub receipt {
11144:     my ($part)=@_;
11145:     my ($symb,$courseid,$domain,$name) = &whichuser();
11146:     return &ireceipt($name,$domain,$courseid,$symb,$part);
11147: }
11148: 
11149: sub whichuser {
11150:     my ($passedsymb)=@_;
11151:     my ($symb,$courseid,$domain,$name,$publicuser);
11152:     if (defined($env{'form.grade_symb'})) {
11153: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
11154: 	my $allowed=&allowed('vgr',$tmp_courseid);
11155: 	if (!$allowed &&
11156: 	    exists($env{'request.course.sec'}) &&
11157: 	    $env{'request.course.sec'} !~ /^\s*$/) {
11158: 	    $allowed=&allowed('vgr',$tmp_courseid.
11159: 			      '/'.$env{'request.course.sec'});
11160: 	}
11161: 	if ($allowed) {
11162: 	    ($symb)=&get_env_multiple('form.grade_symb');
11163: 	    $courseid=$tmp_courseid;
11164: 	    ($domain)=&get_env_multiple('form.grade_domain');
11165: 	    ($name)=&get_env_multiple('form.grade_username');
11166: 	    return ($symb,$courseid,$domain,$name,$publicuser);
11167: 	}
11168:     }
11169:     if (!$passedsymb) {
11170: 	$symb=&symbread();
11171:     } else {
11172: 	$symb=$passedsymb;
11173:     }
11174:     $courseid=$env{'request.course.id'};
11175:     $domain=$env{'user.domain'};
11176:     $name=$env{'user.name'};
11177:     if ($name eq 'public' && $domain eq 'public') {
11178: 	if (!defined($env{'form.username'})) {
11179: 	    $env{'form.username'}.=time.rand(10000000);
11180: 	}
11181: 	$name.=$env{'form.username'};
11182:     }
11183:     return ($symb,$courseid,$domain,$name,$publicuser);
11184: 
11185: }
11186: 
11187: # ------------------------------------------------------------ Serves up a file
11188: # returns either the contents of the file or 
11189: # -1 if the file doesn't exist
11190: #
11191: # if the target is a file that was uploaded via DOCS, 
11192: # a check will be made to see if a current copy exists on the local server,
11193: # if it does this will be served, otherwise a copy will be retrieved from
11194: # the home server for the course and stored in /home/httpd/html/userfiles on
11195: # the local server.   
11196: 
11197: sub getfile {
11198:     my ($file) = @_;
11199:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
11200:     &repcopy($file);
11201:     return &readfile($file);
11202: }
11203: 
11204: sub repcopy_userfile {
11205:     my ($file)=@_;
11206:     my $londocroot = $perlvar{'lonDocRoot'};
11207:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
11208:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
11209:     my ($cdom,$cnum,$filename) = 
11210: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
11211:     my $uri="/uploaded/$cdom/$cnum/$filename";
11212:     if (-e "$file") {
11213: # we already have a local copy, check it out
11214: 	my @fileinfo = stat($file);
11215: 	my $rtncode;
11216: 	my $info;
11217: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
11218: 	if ($lwpresp ne 'ok') {
11219: # there is no such file anymore, even though we had a local copy
11220: 	    if ($rtncode eq '404') {
11221: 		unlink($file);
11222: 	    }
11223: 	    return -1;
11224: 	}
11225: 	if ($info < $fileinfo[9]) {
11226: # nice, the file we have is up-to-date, just say okay
11227: 	    return 'ok';
11228: 	} else {
11229: # the file is outdated, get rid of it
11230: 	    unlink($file);
11231: 	}
11232:     }
11233: # one way or the other, at this point, we don't have the file
11234: # construct the correct path for the file
11235:     my @parts = ($cdom,$cnum); 
11236:     if ($filename =~ m|^(.+)/[^/]+$|) {
11237: 	push @parts, split(/\//,$1);
11238:     }
11239:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
11240:     foreach my $part (@parts) {
11241: 	$path .= '/'.$part;
11242: 	if (!-e $path) {
11243: 	    mkdir($path,0770);
11244: 	}
11245:     }
11246: # now the path exists for sure
11247: # get a user agent
11248:     my $ua=new LWP::UserAgent;
11249:     my $transferfile=$file.'.in.transfer';
11250: # FIXME: this should flock
11251:     if (-e $transferfile) { return 'ok'; }
11252:     my $request;
11253:     $uri=~s/^\///;
11254:     my $homeserver = &homeserver($cnum,$cdom);
11255:     my $protocol = $protocol{$homeserver};
11256:     $protocol = 'http' if ($protocol ne 'https');
11257:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
11258:     my $response=$ua->request($request,$transferfile);
11259: # did it work?
11260:     if ($response->is_error()) {
11261: 	unlink($transferfile);
11262: 	&logthis("Userfile repcopy failed for $uri");
11263: 	return -1;
11264:     }
11265: # worked, rename the transfer file
11266:     rename($transferfile,$file);
11267:     return 'ok';
11268: }
11269: 
11270: sub tokenwrapper {
11271:     my $uri=shift;
11272:     $uri=~s|^https?\://([^/]+)||;
11273:     $uri=~s|^/||;
11274:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
11275:     my $token=$1;
11276:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
11277:     if ($udom && $uname && $file) {
11278: 	$file=~s|(\?\.*)*$||;
11279:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
11280:         my $homeserver = &homeserver($uname,$udom);
11281:         my $protocol = $protocol{$homeserver};
11282:         $protocol = 'http' if ($protocol ne 'https');
11283:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
11284:                (($uri=~/\?/)?'&':'?').'token='.$token.
11285:                                '&tokenissued='.$perlvar{'lonHostID'};
11286:     } else {
11287:         return '/adm/notfound.html';
11288:     }
11289: }
11290: 
11291: # call with reqtype HEAD: get last modification time
11292: # call with reqtype GET: get the file contents
11293: # Do not call this with reqtype GET for large files! It loads everything into memory
11294: #
11295: sub getuploaded {
11296:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
11297:     $uri=~s/^\///;
11298:     my $homeserver = &homeserver($cnum,$cdom);
11299:     my $protocol = $protocol{$homeserver};
11300:     $protocol = 'http' if ($protocol ne 'https');
11301:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
11302:     my $ua=new LWP::UserAgent;
11303:     my $request=new HTTP::Request($reqtype,$uri);
11304:     my $response=$ua->request($request);
11305:     $$rtncode = $response->code;
11306:     if (! $response->is_success()) {
11307: 	return 'failed';
11308:     }      
11309:     if ($reqtype eq 'HEAD') {
11310: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
11311:     } elsif ($reqtype eq 'GET') {
11312: 	$$info = $response->content;
11313:     }
11314:     return 'ok';
11315: }
11316: 
11317: sub readfile {
11318:     my $file = shift;
11319:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
11320:     my $fh;
11321:     open($fh,"<$file");
11322:     my $a='';
11323:     while (my $line = <$fh>) { $a .= $line; }
11324:     return $a;
11325: }
11326: 
11327: sub filelocation {
11328:     my ($dir,$file) = @_;
11329:     my $location;
11330:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
11331: 
11332:     if ($file =~ m-^/adm/-) {
11333: 	$file=~s-^/adm/wrapper/-/-;
11334: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
11335:     }
11336: 
11337:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
11338:         $location = $file;
11339:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
11340:         my ($udom,$uname,$filename)=
11341:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
11342:         my $home=&homeserver($uname,$udom);
11343:         my $is_me=0;
11344:         my @ids=&current_machine_ids();
11345:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
11346:         if ($is_me) {
11347:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
11348:         } else {
11349:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
11350:   	      $udom.'/'.$uname.'/'.$filename;
11351:         }
11352:     } elsif ($file =~ m-^/adm/-) {
11353: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
11354:     } else {
11355:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
11356:         $file=~s:^/(res|priv)/:/:;
11357:         my $space=$1;
11358:         if ( !( $file =~ m:^/:) ) {
11359:             $location = $dir. '/'.$file;
11360:         } else {
11361:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
11362:         }
11363:     }
11364:     $location=~s://+:/:g; # remove duplicate /
11365:     while ($location=~m{/\.\./}) {
11366: 	if ($location =~ m{/[^/]+/\.\./}) {
11367: 	    $location=~ s{/[^/]+/\.\./}{/}g;
11368: 	} else {
11369: 	    $location=~ s{/\.\./}{/}g;
11370: 	}
11371:     } #remove dir/..
11372:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
11373:     return $location;
11374: }
11375: 
11376: sub hreflocation {
11377:     my ($dir,$file)=@_;
11378:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
11379: 	$file=filelocation($dir,$file);
11380:     } elsif ($file=~m-^/adm/-) {
11381: 	$file=~s-^/adm/wrapper/-/-;
11382: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
11383:     }
11384:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
11385: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
11386:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
11387: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
11388: 	        {/uploaded/$1/$2/}x;
11389:     }
11390:     if ($file=~ m{^/userfiles/}) {
11391: 	$file =~ s{^/userfiles/}{/uploaded/};
11392:     }
11393:     return $file;
11394: }
11395: 
11396: 
11397: 
11398: 
11399: 
11400: sub current_machine_domains {
11401:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
11402: }
11403: 
11404: sub machine_domains {
11405:     my ($hostname) = @_;
11406:     my @domains;
11407:     my %hostname = &all_hostnames();
11408:     while( my($id, $name) = each(%hostname)) {
11409: #	&logthis("-$id-$name-$hostname-");
11410: 	if ($hostname eq $name) {
11411: 	    push(@domains,&host_domain($id));
11412: 	}
11413:     }
11414:     return @domains;
11415: }
11416: 
11417: sub current_machine_ids {
11418:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
11419: }
11420: 
11421: sub machine_ids {
11422:     my ($hostname) = @_;
11423:     $hostname ||= &hostname($perlvar{'lonHostID'});
11424:     my @ids;
11425:     my %name_to_host = &all_names();
11426:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
11427: 	return @{ $name_to_host{$hostname} };
11428:     }
11429:     return;
11430: }
11431: 
11432: sub additional_machine_domains {
11433:     my @domains;
11434:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
11435:     while( my $line = <$fh>) {
11436:         $line =~ s/\s//g;
11437:         push(@domains,$line);
11438:     }
11439:     return @domains;
11440: }
11441: 
11442: sub default_login_domain {
11443:     my $domain = $perlvar{'lonDefDomain'};
11444:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
11445:     foreach my $posdom (&current_machine_domains(),
11446:                         &additional_machine_domains()) {
11447:         if (lc($posdom) eq lc($testdomain)) {
11448:             $domain=$posdom;
11449:             last;
11450:         }
11451:     }
11452:     return $domain;
11453: }
11454: 
11455: # ------------------------------------------------------------- Declutters URLs
11456: 
11457: sub declutter {
11458:     my $thisfn=shift;
11459:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
11460:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
11461:     $thisfn=~s/^\///;
11462:     $thisfn=~s|^adm/wrapper/||;
11463:     $thisfn=~s|^adm/coursedocs/showdoc/||;
11464:     $thisfn=~s/^res\///;
11465:     $thisfn=~s/^priv\///;
11466:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
11467:         $thisfn=~s/\?.+$//;
11468:     }
11469:     return $thisfn;
11470: }
11471: 
11472: # ------------------------------------------------------------- Clutter up URLs
11473: 
11474: sub clutter {
11475:     my $thisfn='/'.&declutter(shift);
11476:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
11477: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
11478:        $thisfn='/res'.$thisfn; 
11479:     }
11480:     if ($thisfn !~m|^/adm|) {
11481: 	if ($thisfn =~ m|^/ext/|) {
11482: 	    $thisfn='/adm/wrapper'.$thisfn;
11483: 	} else {
11484: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
11485: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
11486: 	    if ($embstyle eq 'ssi'
11487: 		|| ($embstyle eq 'hdn')
11488: 		|| ($embstyle eq 'rat')
11489: 		|| ($embstyle eq 'prv')
11490: 		|| ($embstyle eq 'ign')) {
11491: 		#do nothing with these
11492: 	    } elsif (($embstyle eq 'img') 
11493: 		|| ($embstyle eq 'emb')
11494: 		|| ($embstyle eq 'wrp')) {
11495: 		$thisfn='/adm/wrapper'.$thisfn;
11496: 	    } elsif ($embstyle eq 'unk'
11497: 		     && $thisfn!~/\.(sequence|page)$/) {
11498: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
11499: 	    } else {
11500: #		&logthis("Got a blank emb style");
11501: 	    }
11502: 	}
11503:     }
11504:     return $thisfn;
11505: }
11506: 
11507: sub clutter_with_no_wrapper {
11508:     my $uri = &clutter(shift);
11509:     if ($uri =~ m-^/adm/-) {
11510: 	$uri =~ s-^/adm/wrapper/-/-;
11511: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
11512:     }
11513:     return $uri;
11514: }
11515: 
11516: sub freeze_escape {
11517:     my ($value)=@_;
11518:     if (ref($value)) {
11519: 	$value=&nfreeze($value);
11520: 	return '__FROZEN__'.&escape($value);
11521:     }
11522:     return &escape($value);
11523: }
11524: 
11525: 
11526: sub thaw_unescape {
11527:     my ($value)=@_;
11528:     if ($value =~ /^__FROZEN__/) {
11529: 	substr($value,0,10,undef);
11530: 	$value=&unescape($value);
11531: 	return &thaw($value);
11532:     }
11533:     return &unescape($value);
11534: }
11535: 
11536: sub correct_line_ends {
11537:     my ($result)=@_;
11538:     $$result =~s/\r\n/\n/mg;
11539:     $$result =~s/\r/\n/mg;
11540: }
11541: # ================================================================ Main Program
11542: 
11543: sub goodbye {
11544:    &logthis("Starting Shut down");
11545: #not converted to using infrastruture and probably shouldn't be
11546:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
11547: #converted
11548: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
11549:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
11550: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
11551: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
11552: #1.1 only
11553: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
11554: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
11555: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
11556: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
11557:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
11558:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
11559:    &logthis(sprintf("%-20s is %s",'hits',$hits));
11560:    &flushcourselogs();
11561:    &logthis("Shutting down");
11562: }
11563: 
11564: sub get_dns {
11565:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
11566:     if (!$ignore_cache) {
11567: 	my ($content,$cached)=
11568: 	    &Apache::lonnet::is_cached_new('dns',$url);
11569: 	if ($cached) {
11570: 	    &$func($content,$hashref);
11571: 	    return;
11572: 	}
11573:     }
11574: 
11575:     my %alldns;
11576:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11577:     foreach my $dns (<$config>) {
11578: 	next if ($dns !~ /^\^(\S*)/x);
11579:         my $line = $1;
11580:         my ($host,$protocol) = split(/:/,$line);
11581:         if ($protocol ne 'https') {
11582:             $protocol = 'http';
11583:         }
11584: 	$alldns{$host} = $protocol;
11585:     }
11586:     while (%alldns) {
11587: 	my ($dns) = keys(%alldns);
11588: 	my $ua=new LWP::UserAgent;
11589:         $ua->timeout(30);
11590: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
11591: 	my $response=$ua->request($request);
11592:         delete($alldns{$dns});
11593: 	next if ($response->is_error());
11594: 	my @content = split("\n",$response->content);
11595: 	unless ($nocache) {
11596: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
11597: 	}
11598: 	&$func(\@content,$hashref);
11599: 	return;
11600:     }
11601:     close($config);
11602:     my $which = (split('/',$url))[3];
11603:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
11604:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
11605:     my @content = <$config>;
11606:     &$func(\@content,$hashref);
11607:     return;
11608: }
11609: 
11610: # ------------------------------------------------------Get DNS checksums file
11611: sub parse_dns_checksums_tab {
11612:     my ($lines,$hashref) = @_;
11613:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
11614:     my $loncaparev = &get_server_loncaparev($machine_dom);
11615:     my ($release,$timestamp) = split(/\-/,$loncaparev);
11616:     my (%chksum,%revnum);
11617:     if (ref($lines) eq 'ARRAY') {
11618:         chomp(@{$lines});
11619:         my $versions = shift(@{$lines});
11620:         my %supported;
11621:         if ($versions =~ /^VERSIONS\:([\w\.\,]+)$/) {
11622:             my $releaseslist = $1;
11623:             if ($releaseslist =~ /,/) {
11624:                 map { $supported{$_} = 1; } split(/,/,$releaseslist);
11625:             } elsif ($releaseslist) {
11626:                 $supported{$releaseslist} = 1;
11627:             }
11628:         }
11629:         if ($supported{$release}) {  
11630:             my $matchthis = 0;
11631:             foreach my $line (@{$lines}) {
11632:                 if ($line =~ /^(\d[\w\.]+)$/) {
11633:                     if ($matchthis) {
11634:                         last;
11635:                     } elsif ($1 eq $release) {
11636:                         $matchthis = 1;
11637:                     }
11638:                 } elsif ($matchthis) {
11639:                     my ($file,$version,$shasum) = split(/,/,$line);
11640:                     $chksum{$file} = $shasum;
11641:                     $revnum{$file} = $version;
11642:                 }
11643:             }
11644:             if (ref($hashref) eq 'HASH') {
11645:                 %{$hashref} = (
11646:                                 sums     => \%chksum,
11647:                                 versions => \%revnum,
11648:                               );
11649:             }
11650:         }
11651:     }
11652:     return;
11653: }
11654: 
11655: sub fetch_dns_checksums {
11656:     my %checksums; 
11657:     &get_dns('/adm/dns/checksums',\&parse_dns_checksums_tab,1,1,
11658:              \%checksums);
11659:     return \%checksums;
11660: }
11661: 
11662: # ------------------------------------------------------------ Read domain file
11663: {
11664:     my $loaded;
11665:     my %domain;
11666: 
11667:     sub parse_domain_tab {
11668: 	my ($lines) = @_;
11669: 	foreach my $line (@$lines) {
11670: 	    next if ($line =~ /^(\#|\s*$ )/x);
11671: 
11672: 	    chomp($line);
11673: 	    my ($name,@elements) = split(/:/,$line,9);
11674: 	    my %this_domain;
11675: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
11676: 			       'lang_def', 'city', 'longi', 'lati',
11677: 			       'primary') {
11678: 		$this_domain{$field} = shift(@elements);
11679: 	    }
11680: 	    $domain{$name} = \%this_domain;
11681: 	}
11682:     }
11683: 
11684:     sub reset_domain_info {
11685: 	undef($loaded);
11686: 	undef(%domain);
11687:     }
11688: 
11689:     sub load_domain_tab {
11690: 	my ($ignore_cache) = @_;
11691: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
11692: 	my $fh;
11693: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
11694: 	    my @lines = <$fh>;
11695: 	    &parse_domain_tab(\@lines);
11696: 	}
11697: 	close($fh);
11698: 	$loaded = 1;
11699:     }
11700: 
11701:     sub domain {
11702: 	&load_domain_tab() if (!$loaded);
11703: 
11704: 	my ($name,$what) = @_;
11705: 	return if ( !exists($domain{$name}) );
11706: 
11707: 	if (!$what) {
11708: 	    return $domain{$name}{'description'};
11709: 	}
11710: 	return $domain{$name}{$what};
11711:     }
11712: 
11713:     sub domain_info {
11714:         &load_domain_tab() if (!$loaded);
11715:         return %domain;
11716:     }
11717: 
11718: }
11719: 
11720: 
11721: # ------------------------------------------------------------- Read hosts file
11722: {
11723:     my %hostname;
11724:     my %hostdom;
11725:     my %libserv;
11726:     my $loaded;
11727:     my %name_to_host;
11728:     my %internetdom;
11729:     my %LC_dns_serv;
11730: 
11731:     sub parse_hosts_tab {
11732: 	my ($file) = @_;
11733: 	foreach my $configline (@$file) {
11734: 	    next if ($configline =~ /^(\#|\s*$ )/x);
11735:             chomp($configline);
11736: 	    if ($configline =~ /^\^/) {
11737:                 if ($configline =~ /^\^([\w.\-]+)/) {
11738:                     $LC_dns_serv{$1} = 1;
11739:                 }
11740:                 next;
11741:             }
11742: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
11743: 	    $name=~s/\s//g;
11744: 	    if ($id && $domain && $role && $name) {
11745: 		$hostname{$id}=$name;
11746: 		push(@{$name_to_host{$name}}, $id);
11747: 		$hostdom{$id}=$domain;
11748: 		if ($role eq 'library') { $libserv{$id}=$name; }
11749:                 if (defined($protocol)) {
11750:                     if ($protocol eq 'https') {
11751:                         $protocol{$id} = $protocol;
11752:                     } else {
11753:                         $protocol{$id} = 'http'; 
11754:                     }
11755:                 } else {
11756:                     $protocol{$id} = 'http';
11757:                 }
11758:                 if (defined($intdom)) {
11759:                     $internetdom{$id} = $intdom;
11760:                 }
11761: 	    }
11762: 	}
11763:     }
11764:     
11765:     sub reset_hosts_info {
11766: 	&purge_remembered();
11767: 	&reset_domain_info();
11768: 	&reset_hosts_ip_info();
11769: 	undef(%name_to_host);
11770: 	undef(%hostname);
11771: 	undef(%hostdom);
11772: 	undef(%libserv);
11773: 	undef($loaded);
11774:     }
11775: 
11776:     sub load_hosts_tab {
11777: 	my ($ignore_cache) = @_;
11778: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
11779: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11780: 	my @config = <$config>;
11781: 	&parse_hosts_tab(\@config);
11782: 	close($config);
11783: 	$loaded=1;
11784:     }
11785: 
11786:     sub hostname {
11787: 	&load_hosts_tab() if (!$loaded);
11788: 
11789: 	my ($lonid) = @_;
11790: 	return $hostname{$lonid};
11791:     }
11792: 
11793:     sub all_hostnames {
11794: 	&load_hosts_tab() if (!$loaded);
11795: 
11796: 	return %hostname;
11797:     }
11798: 
11799:     sub all_names {
11800: 	&load_hosts_tab() if (!$loaded);
11801: 
11802: 	return %name_to_host;
11803:     }
11804: 
11805:     sub all_host_domain {
11806:         &load_hosts_tab() if (!$loaded);
11807:         return %hostdom;
11808:     }
11809: 
11810:     sub is_library {
11811: 	&load_hosts_tab() if (!$loaded);
11812: 
11813: 	return exists($libserv{$_[0]});
11814:     }
11815: 
11816:     sub all_library {
11817: 	&load_hosts_tab() if (!$loaded);
11818: 
11819: 	return %libserv;
11820:     }
11821: 
11822:     sub unique_library {
11823: 	#2x reverse removes all hostnames that appear more than once
11824:         my %unique = reverse &all_library();
11825:         return reverse %unique;
11826:     }
11827: 
11828:     sub get_servers {
11829: 	&load_hosts_tab() if (!$loaded);
11830: 
11831: 	my ($domain,$type) = @_;
11832: 	my %possible_hosts = ($type eq 'library') ? %libserv
11833: 	                                          : %hostname;
11834: 	my %result;
11835: 	if (ref($domain) eq 'ARRAY') {
11836: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
11837: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
11838: 		    $result{$host} = $hostname;
11839: 		}
11840: 	    }
11841: 	} else {
11842: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
11843: 		if ($hostdom{$host} eq $domain) {
11844: 		    $result{$host} = $hostname;
11845: 		}
11846: 	    }
11847: 	}
11848: 	return %result;
11849:     }
11850: 
11851:     sub get_unique_servers {
11852:         my %unique = reverse &get_servers(@_);
11853: 	return reverse %unique;
11854:     }
11855: 
11856:     sub host_domain {
11857: 	&load_hosts_tab() if (!$loaded);
11858: 
11859: 	my ($lonid) = @_;
11860: 	return $hostdom{$lonid};
11861:     }
11862: 
11863:     sub all_domains {
11864: 	&load_hosts_tab() if (!$loaded);
11865: 
11866: 	my %seen;
11867: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
11868: 	return @uniq;
11869:     }
11870: 
11871:     sub internet_dom {
11872:         &load_hosts_tab() if (!$loaded);
11873: 
11874:         my ($lonid) = @_;
11875:         return $internetdom{$lonid};
11876:     }
11877: 
11878:     sub is_LC_dns {
11879:         &load_hosts_tab() if (!$loaded);
11880: 
11881:         my ($hostname) = @_;
11882:         return exists($LC_dns_serv{$hostname});
11883:     }
11884: 
11885: }
11886: 
11887: { 
11888:     my %iphost;
11889:     my %name_to_ip;
11890:     my %lonid_to_ip;
11891: 
11892:     sub get_hosts_from_ip {
11893: 	my ($ip) = @_;
11894: 	my %iphosts = &get_iphost();
11895: 	if (ref($iphosts{$ip})) {
11896: 	    return @{$iphosts{$ip}};
11897: 	}
11898: 	return;
11899:     }
11900:     
11901:     sub reset_hosts_ip_info {
11902: 	undef(%iphost);
11903: 	undef(%name_to_ip);
11904: 	undef(%lonid_to_ip);
11905:     }
11906: 
11907:     sub get_host_ip {
11908: 	my ($lonid) = @_;
11909: 	if (exists($lonid_to_ip{$lonid})) {
11910: 	    return $lonid_to_ip{$lonid};
11911: 	}
11912: 	my $name=&hostname($lonid);
11913:    	my $ip = gethostbyname($name);
11914: 	return if (!$ip || length($ip) ne 4);
11915: 	$ip=inet_ntoa($ip);
11916: 	$name_to_ip{$name}   = $ip;
11917: 	$lonid_to_ip{$lonid} = $ip;
11918: 	return $ip;
11919:     }
11920:     
11921:     sub get_iphost {
11922: 	my ($ignore_cache) = @_;
11923: 
11924: 	if (!$ignore_cache) {
11925: 	    if (%iphost) {
11926: 		return %iphost;
11927: 	    }
11928: 	    my ($ip_info,$cached)=
11929: 		&Apache::lonnet::is_cached_new('iphost','iphost');
11930: 	    if ($cached) {
11931: 		%iphost      = %{$ip_info->[0]};
11932: 		%name_to_ip  = %{$ip_info->[1]};
11933: 		%lonid_to_ip = %{$ip_info->[2]};
11934: 		return %iphost;
11935: 	    }
11936: 	}
11937: 
11938: 	# get yesterday's info for fallback
11939: 	my %old_name_to_ip;
11940: 	my ($ip_info,$cached)=
11941: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
11942: 	if ($cached) {
11943: 	    %old_name_to_ip = %{$ip_info->[1]};
11944: 	}
11945: 
11946: 	my %name_to_host = &all_names();
11947: 	foreach my $name (keys(%name_to_host)) {
11948: 	    my $ip;
11949: 	    if (!exists($name_to_ip{$name})) {
11950: 		$ip = gethostbyname($name);
11951: 		if (!$ip || length($ip) ne 4) {
11952: 		    if (defined($old_name_to_ip{$name})) {
11953: 			$ip = $old_name_to_ip{$name};
11954: 			&logthis("Can't find $name defaulting to old $ip");
11955: 		    } else {
11956: 			&logthis("Name $name no IP found");
11957: 			next;
11958: 		    }
11959: 		} else {
11960: 		    $ip=inet_ntoa($ip);
11961: 		}
11962: 		$name_to_ip{$name} = $ip;
11963: 	    } else {
11964: 		$ip = $name_to_ip{$name};
11965: 	    }
11966: 	    foreach my $id (@{ $name_to_host{$name} }) {
11967: 		$lonid_to_ip{$id} = $ip;
11968: 	    }
11969: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
11970: 	}
11971: 	&do_cache_new('iphost','iphost',
11972: 		      [\%iphost,\%name_to_ip,\%lonid_to_ip],
11973: 		      48*60*60);
11974: 
11975: 	return %iphost;
11976:     }
11977: 
11978:     #
11979:     #  Given a DNS returns the loncapa host name for that DNS 
11980:     # 
11981:     sub host_from_dns {
11982:         my ($dns) = @_;
11983:         my @hosts;
11984:         my $ip;
11985: 
11986:         if (exists($name_to_ip{$dns})) {
11987:             $ip = $name_to_ip{$dns};
11988:         }
11989:         if (!$ip) {
11990:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
11991:             if (length($ip) == 4) { 
11992: 	        $ip   = &IO::Socket::inet_ntoa($ip);
11993:             }
11994:         }
11995:         if ($ip) {
11996: 	    @hosts = get_hosts_from_ip($ip);
11997: 	    return $hosts[0];
11998:         }
11999:         return undef;
12000:     }
12001: 
12002:     sub get_internet_names {
12003:         my ($lonid) = @_;
12004:         return if ($lonid eq '');
12005:         my ($idnref,$cached)=
12006:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
12007:         if ($cached) {
12008:             return $idnref;
12009:         }
12010:         my $ip = &get_host_ip($lonid);
12011:         my @hosts = &get_hosts_from_ip($ip);
12012:         my %iphost = &get_iphost();
12013:         my (@idns,%seen);
12014:         foreach my $id (@hosts) {
12015:             my $dom = &host_domain($id);
12016:             my $prim_id = &domain($dom,'primary');
12017:             my $prim_ip = &get_host_ip($prim_id);
12018:             next if ($seen{$prim_ip});
12019:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
12020:                 foreach my $id (@{$iphost{$prim_ip}}) {
12021:                     my $intdom = &internet_dom($id);
12022:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
12023:                         push(@idns,$intdom);
12024:                     }
12025:                 }
12026:             }
12027:             $seen{$prim_ip} = 1;
12028:         }
12029:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
12030:     }
12031: 
12032: }
12033: 
12034: sub all_loncaparevs {
12035:     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);
12036: }
12037: 
12038: BEGIN {
12039: 
12040: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
12041:     unless ($readit) {
12042: {
12043:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
12044:     %perlvar = (%perlvar,%{$configvars});
12045: }
12046: 
12047: 
12048: # ------------------------------------------------------ Read spare server file
12049: {
12050:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
12051: 
12052:     while (my $configline=<$config>) {
12053:        chomp($configline);
12054:        if ($configline) {
12055: 	   my ($host,$type) = split(':',$configline,2);
12056: 	   if (!defined($type) || $type eq '') { $type = 'default' };
12057: 	   push(@{ $spareid{$type} }, $host);
12058:        }
12059:     }
12060:     close($config);
12061: }
12062: # ------------------------------------------------------------ Read permissions
12063: {
12064:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
12065: 
12066:     while (my $configline=<$config>) {
12067: 	chomp($configline);
12068: 	if ($configline) {
12069: 	    my ($role,$perm)=split(/ /,$configline);
12070: 	    if ($perm ne '') { $pr{$role}=$perm; }
12071: 	}
12072:     }
12073:     close($config);
12074: }
12075: 
12076: # -------------------------------------------- Read plain texts for permissions
12077: {
12078:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
12079: 
12080:     while (my $configline=<$config>) {
12081: 	chomp($configline);
12082: 	if ($configline) {
12083: 	    my ($short,@plain)=split(/:/,$configline);
12084:             %{$prp{$short}} = ();
12085: 	    if (@plain > 0) {
12086:                 $prp{$short}{'std'} = $plain[0];
12087:                 for (my $i=1; $i<@plain; $i++) {
12088:                     $prp{$short}{'alt'.$i} = $plain[$i];  
12089:                 }
12090:             }
12091: 	}
12092:     }
12093:     close($config);
12094: }
12095: 
12096: # ---------------------------------------------------------- Read package table
12097: {
12098:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
12099: 
12100:     while (my $configline=<$config>) {
12101: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
12102: 	chomp($configline);
12103: 	my ($short,$plain)=split(/:/,$configline);
12104: 	my ($pack,$name)=split(/\&/,$short);
12105: 	if ($plain ne '') {
12106: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
12107: 	    $packagetab{$short}=$plain; 
12108: 	}
12109:     }
12110:     close($config);
12111: }
12112: 
12113: # ---------------------------------------------------------- Read loncaparev table
12114: {
12115:     if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
12116:         if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
12117:             while (my $configline=<$config>) {
12118:                 chomp($configline);
12119:                 my ($hostid,$loncaparev)=split(/:/,$configline);
12120:                 $loncaparevs{$hostid}=$loncaparev;
12121:             }
12122:             close($config);
12123:         }
12124:     }
12125: }
12126: 
12127: # ---------------------------------------------------------- Read serverhostID table
12128: {
12129:     if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
12130:         if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
12131:             while (my $configline=<$config>) {
12132:                 chomp($configline);
12133:                 my ($name,$id)=split(/:/,$configline);
12134:                 $serverhomeIDs{$name}=$id;
12135:             }
12136:             close($config);
12137:         }
12138:     }
12139: }
12140: 
12141: {
12142:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
12143:     if (-e $file) {
12144:         my $parser = HTML::LCParser->new($file);
12145:         while (my $token = $parser->get_token()) {
12146:             if ($token->[0] eq 'S') {
12147:                 my $item = $token->[1];
12148:                 my $name = $token->[2]{'name'};
12149:                 my $value = $token->[2]{'value'};
12150:                 if ($item ne '' && $name ne '' && $value ne '') {
12151:                     my $release = $parser->get_text();
12152:                     $release =~ s/(^\s*|\s*$ )//gx;
12153:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
12154:                 }
12155:             }
12156:         }
12157:     }
12158: }
12159: 
12160: # ---------------------------------------------------------- Read managers table
12161: {
12162:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
12163:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
12164:             while (my $configline=<$config>) {
12165:                 chomp($configline);
12166:                 next if ($configline =~ /^\#/);
12167:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
12168:                     $managerstab{$configline} = 1;
12169:                 }
12170:             }
12171:             close($config);
12172:         }
12173:     }
12174: }
12175: 
12176: # ------------- set up temporary directory
12177: {
12178:     $tmpdir = LONCAPA::tempdir();
12179: 
12180: }
12181: 
12182: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
12183: 				'compress_threshold'=> 20_000,
12184:  			        });
12185: 
12186: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
12187: $dumpcount=0;
12188: $locknum=0;
12189: 
12190: &logtouch();
12191: &logthis('<font color="yellow">INFO: Read configuration</font>');
12192: $readit=1;
12193:     {
12194: 	use integer;
12195: 	my $test=(2**32)+1;
12196: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
12197: 	&logthis(" Detected 64bit platform ($_64bit)");
12198:     }
12199: 
12200:     {
12201:         eval {
12202:             ($apache) =
12203:                 (Apache2::ServerUtil::get_server_version() =~ m{Apache/(\d+\.\d+)});
12204:         };
12205:         if ($@) {
12206:            $apache = 1.3;
12207:         }
12208:     }
12209: 
12210: }
12211: }
12212: 
12213: 1;
12214: __END__
12215: 
12216: =pod
12217: 
12218: =head1 NAME
12219: 
12220: Apache::lonnet - Subroutines to ask questions about things in the network.
12221: 
12222: =head1 SYNOPSIS
12223: 
12224: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
12225: 
12226:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
12227: 
12228: Common parameters:
12229: 
12230: =over 4
12231: 
12232: =item *
12233: 
12234: $uname : an internal username (if $cname expecting a course Id specifically)
12235: 
12236: =item *
12237: 
12238: $udom : a domain (if $cdom expecting a course's domain specifically)
12239: 
12240: =item *
12241: 
12242: $symb : a resource instance identifier
12243: 
12244: =item *
12245: 
12246: $namespace : the name of a .db file that contains the data needed or
12247: being set.
12248: 
12249: =back
12250: 
12251: =head1 OVERVIEW
12252: 
12253: lonnet provides subroutines which interact with the
12254: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
12255: about classes, users, and resources.
12256: 
12257: For many of these objects you can also use this to store data about
12258: them or modify them in various ways.
12259: 
12260: =head2 Symbs
12261: 
12262: To identify a specific instance of a resource, LON-CAPA uses symbols
12263: or "symbs"X<symb>. These identifiers are built from the URL of the
12264: map, the resource number of the resource in the map, and the URL of
12265: the resource itself. The latter is somewhat redundant, but might help
12266: if maps change.
12267: 
12268: An example is
12269: 
12270:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
12271: 
12272: The respective map entry is
12273: 
12274:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
12275:   title="Problem 2">
12276:  </resource>
12277: 
12278: Symbs are used by the random number generator, as well as to store and
12279: restore data specific to a certain instance of for example a problem.
12280: 
12281: =head2 Storing And Retrieving Data
12282: 
12283: X<store()>X<cstore()>X<restore()>Three of the most important functions
12284: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
12285: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
12286: is is the non-critical message twin of cstore. These functions are for
12287: handlers to store a perl hash to a user's permanent data space in an
12288: easy manner, and to retrieve it again on another call. It is expected
12289: that a handler would use this once at the beginning to retrieve data,
12290: and then again once at the end to send only the new data back.
12291: 
12292: The data is stored in the user's data directory on the user's
12293: homeserver under the ID of the course.
12294: 
12295: The hash that is returned by restore will have all of the previous
12296: value for all of the elements of the hash.
12297: 
12298: Example:
12299: 
12300:  #creating a hash
12301:  my %hash;
12302:  $hash{'foo'}='bar';
12303: 
12304:  #storing it
12305:  &Apache::lonnet::cstore(\%hash);
12306: 
12307:  #changing a value
12308:  $hash{'foo'}='notbar';
12309: 
12310:  #adding a new value
12311:  $hash{'bar'}='foo';
12312:  &Apache::lonnet::cstore(\%hash);
12313: 
12314:  #retrieving the hash
12315:  my %history=&Apache::lonnet::restore();
12316: 
12317:  #print the hash
12318:  foreach my $key (sort(keys(%history))) {
12319:    print("\%history{$key} = $history{$key}");
12320:  }
12321: 
12322: Will print out:
12323: 
12324:  %history{1:foo} = bar
12325:  %history{1:keys} = foo:timestamp
12326:  %history{1:timestamp} = 990455579
12327:  %history{2:bar} = foo
12328:  %history{2:foo} = notbar
12329:  %history{2:keys} = foo:bar:timestamp
12330:  %history{2:timestamp} = 990455580
12331:  %history{bar} = foo
12332:  %history{foo} = notbar
12333:  %history{timestamp} = 990455580
12334:  %history{version} = 2
12335: 
12336: Note that the special hash entries C<keys>, C<version> and
12337: C<timestamp> were added to the hash. C<version> will be equal to the
12338: total number of versions of the data that have been stored. The
12339: C<timestamp> attribute will be the UNIX time the hash was
12340: stored. C<keys> is available in every historical section to list which
12341: keys were added or changed at a specific historical revision of a
12342: hash.
12343: 
12344: B<Warning>: do not store the hash that restore returns directly. This
12345: will cause a mess since it will restore the historical keys as if the
12346: were new keys. I.E. 1:foo will become 1:1:foo etc.
12347: 
12348: Calling convention:
12349: 
12350:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
12351:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname);
12352: 
12353: For more detailed information, see lonnet specific documentation.
12354: 
12355: =head1 RETURN MESSAGES
12356: 
12357: =over 4
12358: 
12359: =item * B<con_lost>: unable to contact remote host
12360: 
12361: =item * B<con_delayed>: unable to contact remote host, message will be delivered
12362: when the connection is brought back up
12363: 
12364: =item * B<con_failed>: unable to contact remote host and unable to save message
12365: for later delivery
12366: 
12367: =item * B<error:>: an error a occurred, a description of the error follows the :
12368: 
12369: =item * B<no_such_host>: unable to fund a host associated with the user/domain
12370: that was requested
12371: 
12372: =back
12373: 
12374: =head1 PUBLIC SUBROUTINES
12375: 
12376: =head2 Session Environment Functions
12377: 
12378: =over 4
12379: 
12380: =item * 
12381: X<appenv()>
12382: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
12383: the user envirnoment file, and will be restored for each access this
12384: user makes during this session, also modifies the %env for the current
12385: process. Optional rolesarrayref - if defined contains a reference to an array
12386: of roles which are exempt from the restriction on modifying user.role entries 
12387: in the user's environment.db and in %env.    
12388: 
12389: =item *
12390: X<delenv()>
12391: B<delenv($delthis,$regexp)>: removes all items from the session
12392: environment file that begin with $delthis. If the 
12393: optional second arg - $regexp - is true, $delthis is treated as a 
12394: regular expression, otherwise \Q$delthis\E is used. 
12395: The values are also deleted from the current processes %env.
12396: 
12397: =item * get_env_multiple($name) 
12398: 
12399: gets $name from the %env hash, it seemlessly handles the cases where multiple
12400: values may be defined and end up as an array ref.
12401: 
12402: returns an array of values
12403: 
12404: =back
12405: 
12406: =head2 User Information
12407: 
12408: =over 4
12409: 
12410: =item *
12411: X<queryauthenticate()>
12412: B<queryauthenticate($uname,$udom)>: try to determine user's current 
12413: authentication scheme
12414: 
12415: =item *
12416: X<authenticate()>
12417: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
12418: authenticate user from domain's lib servers (first use the current
12419: one). C<$upass> should be the users password.
12420: $checkdefauth is optional (value is 1 if a check should be made to
12421:    authenticate user using default authentication method, and allow
12422:    account creation if username does not have account in the domain).
12423: $clientcancheckhost is optional (value is 1 if checking whether the
12424:    server can host will occur on the client side in lonauth.pm).   
12425: 
12426: =item *
12427: X<homeserver()>
12428: B<homeserver($uname,$udom)>: find the server which has
12429: the user's directory and files (there must be only one), this caches
12430: the answer, and also caches if there is a borken connection.
12431: 
12432: =item *
12433: X<idget()>
12434: B<idget($udom,@ids)>: find the usernames behind a list of IDs
12435: (IDs are a unique resource in a domain, there must be only 1 ID per
12436: username, and only 1 username per ID in a specific domain) (returns
12437: hash: id=>name,id=>name)
12438: 
12439: =item *
12440: X<idrget()>
12441: B<idrget($udom,@unames)>: find the IDs behind a list of
12442: usernames (returns hash: name=>id,name=>id)
12443: 
12444: =item *
12445: X<idput()>
12446: B<idput($udom,%ids)>: store away a list of names and associated IDs
12447: 
12448: =item *
12449: X<rolesinit()>
12450: B<rolesinit($udom,$username)>: get user privileges.
12451: returns user role, first access and timer interval hashes
12452: 
12453: =item *
12454: X<privileged()>
12455: B<privileged($username,$domain)>: returns a true if user has a
12456: privileged and active role (i.e. su or dc), false otherwise.
12457: 
12458: =item *
12459: X<getsection()>
12460: B<getsection($udom,$uname,$cname)>: finds the section of student in the
12461: course $cname, return section name/number or '' for "not in course"
12462: and '-1' for "no section"
12463: 
12464: =item *
12465: X<userenvironment()>
12466: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
12467: passed in @what from the requested user's environment, returns a hash
12468: 
12469: =item * 
12470: X<userlog_query()>
12471: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
12472: activity.log file. %filters defines filters applied when parsing the
12473: log file. These can be start or end timestamps, or the type of action
12474: - log to look for Login or Logout events, check for Checkin or
12475: Checkout, role for role selection. The response is in the form
12476: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
12477: escaped strings of the action recorded in the activity.log file.
12478: 
12479: =back
12480: 
12481: =head2 User Roles
12482: 
12483: =over 4
12484: 
12485: =item *
12486: 
12487: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
12488:  F: full access
12489:  U,I,K: authentication modes (cxx only)
12490:  '': forbidden
12491:  1: user needs to choose course
12492:  2: browse allowed
12493:  A: passphrase authentication needed
12494: 
12495: =item *
12496: 
12497: constructaccess($url,$setpriv) : check for access to construction space URL
12498: 
12499: See if the owner domain and name in the URL match those in the
12500: expected environment.  If so, return three element list
12501: ($ownername,$ownerdomain,$ownerhome).
12502: 
12503: Otherwise return the null string.
12504: 
12505: If second argument 'setpriv' is true, it assigns the privileges,
12506: and returns the same three element list, unless the owner has
12507: blocked "ad hoc" Domain Coordinator access to the Author Space,
12508: in which case the null string is returned.
12509: 
12510: =item *
12511: 
12512: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
12513: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
12514: and course level
12515: 
12516: =item *
12517: 
12518: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
12519: (rolesplain.tab); plain text explanation of a user role term.
12520: $type is Course (default) or Community.
12521: If $forcedefault evaluates to true, text returned will be default 
12522: text for $type. Otherwise, if this is a course, the text returned 
12523: will be a custom name for the role (if defined in the course's 
12524: environment).  If no custom name is defined the default is returned.
12525:    
12526: =item *
12527: 
12528: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
12529: All arguments are optional. Returns a hash of a roles, either for
12530: co-author/assistant author roles for a user's Construction Space
12531: (default), or if $context is 'userroles', roles for the user himself,
12532: In the hash, keys are set to colon-separated $uname,$udom,$role, and
12533: (optionally) if $withsec is true, a fourth colon-separated item - $section.
12534: For each key, value is set to colon-separated start and end times for
12535: the role.  If no username and domain are specified, will default to
12536: current user/domain. Types, roles, and roledoms are references to arrays
12537: of role statuses (active, future or previous), roles 
12538: (e.g., cc,in, st etc.) and domains of the roles which can be used
12539: to restrict the list of roles reported. If no array ref is 
12540: provided for types, will default to return only active roles.
12541: 
12542: =item *
12543: 
12544: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
12545: user: $uname:$udom has a role in the course: $cdom_$cnum. 
12546: 
12547: Additional optional arguments are: $type (if role checking is to be restricted 
12548: to certain user status types -- previous (expired roles), active (currently
12549: available roles) or future (roles available in the future), and
12550: $hideprivileged -- if true will not report course roles for users who
12551: have active Domain Coordinator role in course's domain or in additional
12552: domains (specified in 'Domains to check for privileged users' in course
12553: environment -- set via:  Course Settings -> Classlists and staff listing).
12554: 
12555: =item *
12556: 
12557: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
12558: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
12559: $possdomains and $possroles are optional array refs -- to domains to check and
12560: roles to check.  If $possdomains is not specified, a dump will be done of the
12561: users' roles.db to check for a dc or su role in any domain. This can be
12562: time consuming if &privileged is called repeatedly (e.g., when displaying a
12563: classlist), so in such cases, supplying a $possdomains array is preferred, as
12564: this then allows &privileged_by_domain() to be used, which caches the identity
12565: of privileged users, eliminating the need for repeated calls to &dump().
12566: 
12567: =item *
12568: 
12569: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
12570: where the outer hash keys are domains specified in the $possdomains array ref,
12571: next inner hash keys are privileged roles specified in the $roles array ref,
12572: and the innermost hash contains key = value pairs for username:domain = end:start
12573: for active or future "privileged" users with that role in that domain. To avoid
12574: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
12575: innerhash are cached using priv_$role and $dom as the identifiers.
12576: 
12577: =back
12578: 
12579: =head2 User Modification
12580: 
12581: =over 4
12582: 
12583: =item *
12584: 
12585: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
12586: user for the level given by URL.  Optional start and end dates (leave empty
12587: string or zero for "no date")
12588: 
12589: =item *
12590: 
12591: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
12592: change a users, password, possible return values are: ok,
12593: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
12594: refused
12595: 
12596: =item *
12597: 
12598: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
12599: 
12600: =item *
12601: 
12602: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
12603:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
12604: 
12605: will update user information (firstname,middlename,lastname,generation,
12606: permanentemail), and if forceid is true, student/employee ID also.
12607: A user's institutional affiliation(s) can also be updated.
12608: User information fields will not be overwritten with empty entries 
12609: unless the field is included in the $candelete array reference.
12610: This array is included when a single user is modified via "Manage Users",
12611: or when Autoupdate.pl is run by cron in a domain.
12612: 
12613: =item *
12614: 
12615: modifystudent
12616: 
12617: modify a student's enrollment and identification information.
12618: The course id is resolved based on the current users environment.  
12619: This means the envoking user must be a course coordinator or otherwise
12620: associated with a course.
12621: 
12622: This call is essentially a wrapper for lonnet::modifyuser and
12623: lonnet::modify_student_enrollment
12624: 
12625: Inputs: 
12626: 
12627: =over 4
12628: 
12629: =item B<$udom> Student's loncapa domain
12630: 
12631: =item B<$uname> Student's loncapa login name
12632: 
12633: =item B<$uid> Student/Employee ID
12634: 
12635: =item B<$umode> Student's authentication mode
12636: 
12637: =item B<$upass> Student's password
12638: 
12639: =item B<$first> Student's first name
12640: 
12641: =item B<$middle> Student's middle name
12642: 
12643: =item B<$last> Student's last name
12644: 
12645: =item B<$gene> Student's generation
12646: 
12647: =item B<$usec> Student's section in course
12648: 
12649: =item B<$end> Unix time of the roles expiration
12650: 
12651: =item B<$start> Unix time of the roles start date
12652: 
12653: =item B<$forceid> If defined, allow $uid to be changed
12654: 
12655: =item B<$desiredhome> server to use as home server for student
12656: 
12657: =item B<$email> Student's permanent e-mail address
12658: 
12659: =item B<$type> Type of enrollment (auto or manual)
12660: 
12661: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
12662: 
12663: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
12664: 
12665: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
12666: 
12667: =item B<$context> role change context (shown in User Management Logs display in a course)
12668: 
12669: =item B<$inststatus> institutional status of user - : separated string of escaped status types
12670: 
12671: =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.
12672: 
12673: =back
12674: 
12675: =item *
12676: 
12677: modify_student_enrollment
12678: 
12679: Change a students enrollment status in a class.  The environment variable
12680: 'role.request.course' must be defined for this function to proceed.
12681: 
12682: Inputs:
12683: 
12684: =over 4
12685: 
12686: =item $udom, students domain
12687: 
12688: =item $uname, students name
12689: 
12690: =item $uid, students user id
12691: 
12692: =item $first, students first name
12693: 
12694: =item $middle
12695: 
12696: =item $last
12697: 
12698: =item $gene
12699: 
12700: =item $usec
12701: 
12702: =item $end
12703: 
12704: =item $start
12705: 
12706: =item $type
12707: 
12708: =item $locktype
12709: 
12710: =item $cid
12711: 
12712: =item $selfenroll
12713: 
12714: =item $context
12715: 
12716: =item $credits, number of credits student will earn from this class
12717: 
12718: =back
12719: 
12720: 
12721: =item *
12722: 
12723: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
12724: custom role; give a custom role to a user for the level given by URL.  Specify
12725: name and domain of role author, and role name
12726: 
12727: =item *
12728: 
12729: revokerole($udom,$uname,$url,$role) : revoke a role for url
12730: 
12731: =item *
12732: 
12733: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
12734: 
12735: =back
12736: 
12737: =head2 Course Infomation
12738: 
12739: =over 4
12740: 
12741: =item *
12742: 
12743: coursedescription($courseid,$options) : returns a hash of information about the
12744: specified course id, including all environment settings for the
12745: course, the description of the course will be in the hash under the
12746: key 'description'
12747: 
12748: $options is an optional parameter that if supplied is a hash reference that controls
12749: what how this function works.  It has the following key/values:
12750: 
12751: =over 4
12752: 
12753: =item freshen_cache
12754: 
12755: If defined, and the environment cache for the course is valid, it is 
12756: returned in the returned hash.
12757: 
12758: =item one_time
12759: 
12760: If defined, the last cache time is set to _now_
12761: 
12762: =item user
12763: 
12764: If defined, the supplied username is used instead of the current user.
12765: 
12766: 
12767: =back
12768: 
12769: =item *
12770: 
12771: resdata($name,$domain,$type,@which) : request for current parameter
12772: setting for a specific $type, where $type is either 'course' or 'user',
12773: @what should be a list of parameters to ask about. This routine caches
12774: answers for 5 minutes.
12775: 
12776: =item *
12777: 
12778: get_courseresdata($courseid, $domain) : dump the entire course resource
12779: data base, returning a hash that is keyed by the resource name and has
12780: values that are the resource value.  I believe that the timestamps and
12781: versions are also returned.
12782: 
12783: =back
12784: 
12785: =head2 Course Modification
12786: 
12787: =over 4
12788: 
12789: =item *
12790: 
12791: writecoursepref($courseid,%prefs) : write preferences (environment
12792: database) for a course
12793: 
12794: =item *
12795: 
12796: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
12797: 
12798: =item *
12799: 
12800: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
12801: 
12802: =item *
12803: 
12804: is_course($courseid), is_course($cdom, $cnum)
12805: 
12806: Accepts either a combined $courseid (in the form of domain_courseid) or the
12807: two component version $cdom, $cnum. It checks if the specified course exists.
12808: 
12809: Returns:
12810:     undef if the course doesn't exist, otherwise
12811:     in scalar context the combined courseid.
12812:     in list context the two components of the course identifier, domain and 
12813:     courseid.    
12814: 
12815: =back
12816: 
12817: =head2 Resource Subroutines
12818: 
12819: =over 4
12820: 
12821: =item *
12822: 
12823: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
12824: 
12825: =item *
12826: 
12827: repcopy($filename) : subscribes to the requested file, and attempts to
12828: replicate from the owning library server, Might return
12829: 'unavailable', 'not_found', 'forbidden', 'ok', or
12830: 'bad_request', also attempts to grab the metadata for the
12831: resource. Expects the local filesystem pathname
12832: (/home/httpd/html/res/....)
12833: 
12834: =back
12835: 
12836: =head2 Resource Information
12837: 
12838: =over 4
12839: 
12840: =item *
12841: 
12842: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
12843: a vairety of different possible values, $varname should be a request
12844: string, and the other parameters can be used to specify who and what
12845: one is asking about.
12846: 
12847: Possible values for $varname are environment.lastname (or other item
12848: from the envirnment hash), user.name (or someother aspect about the
12849: user), resource.0.maxtries (or some other part and parameter of a
12850: resource)
12851: 
12852: =item *
12853: 
12854: directcondval($number) : get current value of a condition; reads from a state
12855: string
12856: 
12857: =item *
12858: 
12859: condval($condidx) : value of condition index based on state
12860: 
12861: =item *
12862: 
12863: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
12864: resource's metadata, $what should be either a specific key, or either
12865: 'keys' (to get a list of possible keys) or 'packages' to get a list of
12866: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
12867: 
12868: this function automatically caches all requests
12869: 
12870: =item *
12871: 
12872: metadata_query($query,$custom,$customshow) : make a metadata query against the
12873: network of library servers; returns file handle of where SQL and regex results
12874: will be stored for query
12875: 
12876: =item *
12877: 
12878: symbread($filename) : return symbolic list entry (filename argument optional);
12879: returns the data handle
12880: 
12881: =item *
12882: 
12883: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
12884: and is a possible symb for the URL in $thisfn, and if is an encrypted
12885: resource that the user accessed using /enc/ returns a 1 on success, 0
12886: on failure, user must be in a course, as it assumes the existence of
12887: the course initial hash, and uses $env('request.course.id'}.  The third
12888: arg is an optional reference to a scalar.  If this arg is passed in the 
12889: call to symbverify, it will be set to 1 if the symb has been set to be 
12890: encrypted; otherwise it will be null.  
12891: 
12892: =item *
12893: 
12894: symbclean($symb) : removes versions numbers from a symb, returns the
12895: cleaned symb
12896: 
12897: =item *
12898: 
12899: is_on_map($uri) : checks if the $uri is somewhere on the current
12900: course map, user must be in a course for it to work.
12901: 
12902: =item *
12903: 
12904: numval($salt) : return random seed value (addend for rndseed)
12905: 
12906: =item *
12907: 
12908: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
12909: a random seed, all arguments are optional, if they aren't sent it uses the
12910: environment to derive them. Note: if symb isn't sent and it can't get one
12911: from &symbread it will use the current time as its return value
12912: 
12913: =item *
12914: 
12915: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
12916: unfakeable, receipt
12917: 
12918: =item *
12919: 
12920: receipt() : API to ireceipt working off of env values; given out to users
12921: 
12922: =item *
12923: 
12924: countacc($url) : count the number of accesses to a given URL
12925: 
12926: =item *
12927: 
12928: 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
12929: 
12930: =item *
12931: 
12932: 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)
12933: 
12934: =item *
12935: 
12936: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
12937: 
12938: =item *
12939: 
12940: devalidate($symb) : devalidate temporary spreadsheet calculations,
12941: forcing spreadsheet to reevaluate the resource scores next time.
12942: 
12943: =item * 
12944: 
12945: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
12946: when viewing in course context.
12947: 
12948:  input: six args -- filename (decluttered), course number, course domain,
12949:                     url, symb (if registered) and group (if this is a 
12950:                     group item -- e.g., bulletin board, group page etc.).
12951: 
12952:  output: array of five scalars --
12953:          $cfile -- url for file editing if editable on current server
12954:          $home -- homeserver of resource (i.e., for author if published,
12955:                                           or course if uploaded.).
12956:          $switchserver --  1 if server switch will be needed.
12957:          $forceedit -- 1 if icon/link should be to go to edit mode 
12958:          $forceview -- 1 if icon/link should be to go to view mode
12959: 
12960: =item *
12961: 
12962: is_course_upload($file,$cnum,$cdom)
12963: 
12964: Used in course context to determine if current file was uploaded to 
12965: the course (i.e., would be found in /userfiles/docs on the course's 
12966: homeserver.
12967: 
12968:   input: 3 args -- filename (decluttered), course number and course domain.
12969:   output: boolean -- 1 if file was uploaded.
12970: 
12971: =back
12972: 
12973: =head2 Storing/Retreiving Data
12974: 
12975: =over 4
12976: 
12977: =item *
12978: 
12979: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
12980: for this url; hashref needs to be given and should be a \%hashname; the
12981: remaining args aren't required and if they aren't passed or are '' they will
12982: be derived from the env
12983: 
12984: =item *
12985: 
12986: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
12987: uses critical subroutine
12988: 
12989: =item *
12990: 
12991: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
12992: all args are optional
12993: 
12994: =item *
12995: 
12996: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
12997: dumps the complete (or key matching regexp) namespace into a hash
12998: ($udom, $uname, $regexp, $range are optional) for a namespace that is
12999: normally &store()ed into
13000: 
13001: $range should be either an integer '100' (give me the first 100
13002:                                            matching records)
13003:               or be  two integers sperated by a - with no spaces
13004:                  '30-50' (give me the 30th through the 50th matching
13005:                           records)
13006: 
13007: 
13008: =item *
13009: 
13010: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
13011: replaces a &store() version of data with a replacement set of data
13012: for a particular resource in a namespace passed in the $storehash hash 
13013: reference
13014: 
13015: =item *
13016: 
13017: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
13018: works very similar to store/cstore, but all data is stored in a
13019: temporary location and can be reset using tmpreset, $storehash should
13020: be a hash reference, returns nothing on success
13021: 
13022: =item *
13023: 
13024: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
13025: similar to restore, but all data is stored in a temporary location and
13026: can be reset using tmpreset. Returns a hash of values on success,
13027: error string otherwise.
13028: 
13029: =item *
13030: 
13031: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
13032: deltes all keys for $symb form the temporary storage hash.
13033: 
13034: =item *
13035: 
13036: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13037: reference filled in from namesp ($udom and $uname are optional)
13038: 
13039: =item *
13040: 
13041: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
13042: namesp ($udom and $uname are optional)
13043: 
13044: =item *
13045: 
13046: dump($namespace,$udom,$uname,$regexp,$range) : 
13047: dumps the complete (or key matching regexp) namespace into a hash
13048: ($udom, $uname, $regexp, $range are optional)
13049: 
13050: $range should be either an integer '100' (give me the first 100
13051:                                            matching records)
13052:               or be  two integers sperated by a - with no spaces
13053:                  '30-50' (give me the 30th through the 50th matching
13054:                           records)
13055: =item *
13056: 
13057: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
13058: $store can be a scalar, an array reference, or if the amount to be 
13059: incremented is > 1, a hash reference.
13060: 
13061: ($udom and $uname are optional)
13062: 
13063: =item *
13064: 
13065: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
13066: ($udom and $uname are optional)
13067: 
13068: =item *
13069: 
13070: cput($namespace,$storehash,$udom,$uname) : critical put
13071: ($udom and $uname are optional)
13072: 
13073: =item *
13074: 
13075: newput($namespace,$storehash,$udom,$uname) :
13076: 
13077: Attempts to store the items in the $storehash, but only if they don't
13078: currently exist, if this succeeds you can be certain that you have 
13079: successfully created a new key value pair in the $namespace db.
13080: 
13081: 
13082: Args:
13083:  $namespace: name of database to store values to
13084:  $storehash: hashref to store to the db
13085:  $udom: (optional) domain of user containing the db
13086:  $uname: (optional) name of user caontaining the db
13087: 
13088: Returns:
13089:  'ok' -> succeeded in storing all keys of $storehash
13090:  'key_exists: <key>' -> failed to anything out of $storehash, as at
13091:                         least <key> already existed in the db (other
13092:                         requested keys may also already exist)
13093:  'error: <msg>' -> unable to tie the DB or other error occurred
13094:  'con_lost' -> unable to contact request server
13095:  'refused' -> action was not allowed by remote machine
13096: 
13097: 
13098: =item *
13099: 
13100: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13101: reference filled in from namesp (encrypts the return communication)
13102: ($udom and $uname are optional)
13103: 
13104: =item *
13105: 
13106: log($udom,$name,$home,$message) : write to permanent log for user; use
13107: critical subroutine
13108: 
13109: =item *
13110: 
13111: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
13112: array reference filled in from namespace found in domain level on either
13113: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
13114: 
13115: =item *
13116: 
13117: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
13118: domain level either on specified domain server ($uhome) or primary domain 
13119: server ($udom and $uhome are optional)
13120: 
13121: =item * 
13122: 
13123: get_domain_defaults($target_domain) : returns hash with defaults for
13124: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
13125: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
13126: or localauth), initial password or a kerberos realm, language (e.g., en-us).
13127: Values are retrieved from cache (if current), or from domain's configuration.db
13128: (if available), or lastly from values in lonTabs/dns_domain,tab, 
13129: or lonTabs/domain.tab. 
13130: 
13131: %domdefaults = &get_auth_defaults($target_domain);
13132: 
13133: =back
13134: 
13135: =head2 Network Status Functions
13136: 
13137: =over 4
13138: 
13139: =item *
13140: 
13141: dirlist() : return directory list based on URI (first arg).
13142: 
13143: Inputs: 1 required, 5 optional.
13144: 
13145: =over
13146: 
13147: =item 
13148: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
13149: 
13150: =item
13151: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
13152: 
13153: =item
13154: $username -  username of user/course to be listed. Extracted from $uri if absent. 
13155: 
13156: =item
13157: $getpropath - boolean: 1 if prepend path using &propath(). 
13158: 
13159: =item
13160: $getuserdir - boolean: 1 if prepend path for "userfiles".
13161: 
13162: =item 
13163: $alternateRoot - path to prepend in place of path from $uri.
13164: 
13165: =back
13166: 
13167: Returns: Array of up to two items.
13168: 
13169: =over
13170: 
13171: a reference to an array of files/subdirectories
13172: 
13173: =over
13174: 
13175: Each element in the array of files/subdirectories is a & separated list of
13176: item name and the result of running stat on the item.  If dirlist was requested
13177: for a file instead of a directory, the item name will be ''. For a directory 
13178: listing, if the item is a metadata file, the element will end &N&M 
13179: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
13180: default copyright set (1).  
13181: 
13182: =back
13183: 
13184: a scalar containing error condition (if encountered).
13185: 
13186: =over
13187: 
13188: =item 
13189: no_host (no homeserver identified for $username:$domain).
13190: 
13191: =item 
13192: no_such_host (server contacted for listing not identified as valid host).
13193: 
13194: =item 
13195: con_lost (connection to remote server failed).
13196: 
13197: =item 
13198: refused (invalid $username:$domain received on lond side).
13199: 
13200: =item 
13201: no_such_dir (directory at specified path on lond side does not exist). 
13202: 
13203: =item 
13204: empty (directory at specified path on lond side is empty).
13205: 
13206: =over
13207: 
13208: This is currently not encountered because the &ls3, &ls2, 
13209: &ls (_handler) routines on the lond side do not filter out
13210: . and .. from a directory listing. 
13211: 
13212: =back
13213: 
13214: =back
13215: 
13216: =back
13217: 
13218: =item *
13219: 
13220: spareserver() : find server with least workload from spare.tab
13221: 
13222: 
13223: =item *
13224: 
13225: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
13226: if there is no corresponding loncapa host.
13227: 
13228: =back
13229: 
13230: 
13231: =head2 Apache Request
13232: 
13233: =over 4
13234: 
13235: =item *
13236: 
13237: ssi($url,%hash) : server side include, does a complete request cycle on url to
13238: localhost, posts hash
13239: 
13240: =back
13241: 
13242: =head2 Data to String to Data
13243: 
13244: =over 4
13245: 
13246: =item *
13247: 
13248: hash2str(%hash) : convert a hash into a string complete with escaping and '='
13249: and '&' separators, supports elements that are arrayrefs and hashrefs
13250: 
13251: =item *
13252: 
13253: hashref2str($hashref) : convert a hashref into a string complete with
13254: escaping and '=' and '&' separators, supports elements that are
13255: arrayrefs and hashrefs
13256: 
13257: =item *
13258: 
13259: arrayref2str($arrayref) : convert an arrayref into a string complete
13260: with escaping and '&' separators, supports elements that are arrayrefs
13261: and hashrefs
13262: 
13263: =item *
13264: 
13265: str2hash($string) : convert string to hash using unescaping and
13266: splitting on '=' and '&', supports elements that are arrayrefs and
13267: hashrefs
13268: 
13269: =item *
13270: 
13271: str2array($string) : convert string to hash using unescaping and
13272: splitting on '&', supports elements that are arrayrefs and hashrefs
13273: 
13274: =back
13275: 
13276: =head2 Logging Routines
13277: 
13278: 
13279: These routines allow one to make log messages in the lonnet.log and
13280: lonnet.perm logfiles.
13281: 
13282: =over 4
13283: 
13284: =item *
13285: 
13286: logtouch() : make sure the logfile, lonnet.log, exists
13287: 
13288: =item *
13289: 
13290: logthis() : append message to the normal lonnet.log file, it gets
13291: preiodically rolled over and deleted.
13292: 
13293: =item *
13294: 
13295: logperm() : append a permanent message to lonnet.perm.log, this log
13296: file never gets deleted by any automated portion of the system, only
13297: messages of critical importance should go in here.
13298: 
13299: 
13300: =back
13301: 
13302: =head2 General File Helper Routines
13303: 
13304: =over 4
13305: 
13306: =item *
13307: 
13308: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
13309: (a) files in /uploaded
13310:   (i) If a local copy of the file exists - 
13311:       compares modification date of local copy with last-modified date for 
13312:       definitive version stored on home server for course. If local copy is 
13313:       stale, requests a new version from the home server and stores it. 
13314:       If the original has been removed from the home server, then local copy 
13315:       is unlinked.
13316:   (ii) If local copy does not exist -
13317:       requests the file from the home server and stores it. 
13318:   
13319:   If $caller is 'uploadrep':  
13320:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
13321:     for request for files originally uploaded via DOCS. 
13322:      - returns 'ok' if fresh local copy now available, -1 otherwise.
13323:   
13324:   Otherwise:
13325:      This indicates a call from the content generation phase of the request.
13326:      -  returns the entire contents of the file or -1.
13327:      
13328: (b) files in /res
13329:    - returns the entire contents of a file or -1; 
13330:    it properly subscribes to and replicates the file if neccessary.
13331: 
13332: 
13333: =item *
13334: 
13335: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
13336:                   reference
13337: 
13338: returns either a stat() list of data about the file or an empty list
13339: if the file doesn't exist or couldn't find out about it (connection
13340: problems or user unknown)
13341: 
13342: =item *
13343: 
13344: filelocation($dir,$file) : returns file system location of a file
13345: based on URI; meant to be "fairly clean" absolute reference, $dir is a
13346: directory that relative $file lookups are to looked in ($dir of /a/dir
13347: and a file of ../bob will become /a/bob)
13348: 
13349: =item *
13350: 
13351: hreflocation($dir,$file) : returns file system location or a URL; same as
13352: filelocation except for hrefs
13353: 
13354: =item *
13355: 
13356: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
13357: 
13358: =back
13359: 
13360: =head2 Usererfile file routines (/uploaded*)
13361: 
13362: =over 4
13363: 
13364: =item *
13365: 
13366: userfileupload(): main rotine for putting a file in a user or course's
13367:                   filespace, arguments are,
13368: 
13369:  formname - required - this is the name of the element in $env where the
13370:            filename, and the contents of the file to create/modifed exist
13371:            the filename is in $env{'form.'.$formname.'.filename'} and the
13372:            contents of the file is located in $env{'form.'.$formname}
13373:  context - if coursedoc, store the file in the course of the active role
13374:              of the current user; 
13375:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
13376:            if 'canceloverwrite': delete file in tmp/overwrites directory
13377:  subdir - required - subdirectory to put the file in under ../userfiles/
13378:          if undefined, it will be placed in "unknown"
13379: 
13380:  (This routine calls clean_filename() to remove any dangerous
13381:  characters from the filename, and then calls finuserfileupload() to
13382:  complete the transaction)
13383: 
13384:  returns either the url of the uploaded file (/uploaded/....) if successful
13385:  and /adm/notfound.html if unsuccessful
13386: 
13387: =item *
13388: 
13389: clean_filename(): routine for cleaing a filename up for storage in
13390:                  userfile space, argument is:
13391: 
13392:  filename - proposed filename
13393: 
13394: returns: the new clean filename
13395: 
13396: =item *
13397: 
13398: finishuserfileupload(): routine that creates and sends the file to
13399: userspace, probably shouldn't be called directly
13400: 
13401:   docuname: username or courseid of destination for the file
13402:   docudom: domain of user/course of destination for the file
13403:   formname: same as for userfileupload()
13404:   fname: filename (including subdirectories) for the file
13405:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
13406:   allfiles: reference to hash used to store objects found by parser
13407:   codebase: reference to hash used for codebases of java objects found by parser
13408:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
13409:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
13410:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
13411:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
13412:   context: if 'overwrite', will move the uploaded file from its temporary location to
13413:             userfiles to facilitate overwriting a previously uploaded file with same name.
13414:   mimetype: reference to scalar to accommodate mime type determined
13415:             from File::MMagic if $parser = parse.
13416: 
13417:  returns either the url of the uploaded file (/uploaded/....) if successful
13418:  and /adm/notfound.html if unsuccessful (or an error message if context 
13419:  was 'overwrite').
13420:  
13421: 
13422: =item *
13423: 
13424: renameuserfile(): renames an existing userfile to a new name
13425: 
13426:   Args:
13427:    docuname: username or courseid of destination for the file
13428:    docudom: domain of user/course of destination for the file
13429:    old: current file name (including any subdirs under userfiles)
13430:    new: desired file name (including any subdirs under userfiles)
13431: 
13432: =item *
13433: 
13434: mkdiruserfile(): creates a directory is a userfiles dir
13435: 
13436:   Args:
13437:    docuname: username or courseid of destination for the file
13438:    docudom: domain of user/course of destination for the file
13439:    dir: dir to create (including any subdirs under userfiles)
13440: 
13441: =item *
13442: 
13443: removeuserfile(): removes a file that exists in userfiles
13444: 
13445:   Args:
13446:    docuname: username or courseid of destination for the file
13447:    docudom: domain of user/course of destination for the file
13448:    fname: filname to delete (including any subdirs under userfiles)
13449: 
13450: =item *
13451: 
13452: removeuploadedurl(): convience function for removeuserfile()
13453: 
13454:   Args:
13455:    url:  a full /uploaded/... url to delete
13456: 
13457: =item * 
13458: 
13459: get_portfile_permissions():
13460:   Args:
13461:     domain: domain of user or course contain the portfolio files
13462:     user: name of user or num of course contain the portfolio files
13463:   Returns:
13464:     hashref of a dump of the proper file_permissions.db
13465:    
13466: 
13467: =item * 
13468: 
13469: get_access_controls():
13470: 
13471: Args:
13472:   current_permissions: the hash ref returned from get_portfile_permissions()
13473:   group: (optional) the group you want the files associated with
13474:   file: (optional) the file you want access info on
13475: 
13476: Returns:
13477:     a hash (keys are file names) of hashes containing
13478:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
13479:         values are XML containing access control settings (see below) 
13480: 
13481: Internal notes:
13482: 
13483:  access controls are stored in file_permissions.db as key=value pairs.
13484:     key -> path to file/file_name\0uniqueID:scope_end_start
13485:         where scope -> public,guest,course,group,domains or users.
13486:               end -> UNIX time for end of access (0 -> no end date)
13487:               start -> UNIX time for start of access
13488: 
13489:     value -> XML description of access control
13490:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
13491:             <start></start>
13492:             <end></end>
13493: 
13494:             <password></password>  for scope type = guest
13495: 
13496:             <domain></domain>     for scope type = course or group
13497:             <number></number>
13498:             <roles id="">
13499:              <role></role>
13500:              <access></access>
13501:              <section></section>
13502:              <group></group>
13503:             </roles>
13504: 
13505:             <dom></dom>         for scope type = domains
13506: 
13507:             <users>             for scope type = users
13508:              <user>
13509:               <uname></uname>
13510:               <udom></udom>
13511:              </user>
13512:             </users>
13513:            </scope> 
13514:               
13515:  Access data is also aggregated for each file in an additional key=value pair:
13516:  key -> path to file/file_name\0accesscontrol 
13517:  value -> reference to hash
13518:           hash contains key = value pairs
13519:           where key = uniqueID:scope_end_start
13520:                 value = UNIX time record was last updated
13521: 
13522:           Used to improve speed of look-ups of access controls for each file.  
13523:  
13524:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
13525: 
13526: =item *
13527: 
13528: modify_access_controls():
13529: 
13530: Modifies access controls for a portfolio file
13531: Args
13532: 1. file name
13533: 2. reference to hash of required changes,
13534: 3. domain
13535: 4. username
13536:   where domain,username are the domain of the portfolio owner 
13537:   (either a user or a course) 
13538: 
13539: Returns:
13540: 1. result of additions or updates ('ok' or 'error', with error message). 
13541: 2. result of deletions ('ok' or 'error', with error message).
13542: 3. reference to hash of any new or updated access controls.
13543: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
13544:    key = integer (inbound ID)
13545:    value = uniqueID
13546: 
13547: =item *
13548: 
13549: get_timebased_id():
13550: 
13551: Attempts to get a unique timestamp-based suffix for use with items added to a 
13552: course via the Course Editor (e.g., folders, composite pages, 
13553: group bulletin boards).
13554: 
13555: Args: (first three required; six others optional)
13556: 
13557: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
13558:    docssequence, or name of group
13559: 
13560: 2. keyid (alphanumeric): name of temporary locking key in hash,
13561:    e.g., num, boardids
13562: 
13563: 3. namespace: name of gdbm file used to store suffixes already assigned;  
13564:    file will be named nohist_namespace.db
13565: 
13566: 4. cdom: domain of course; default is current course domain from %env
13567: 
13568: 5. cnum: course number; default is current course number from %env
13569: 
13570: 6. idtype: set to concat if an additional digit is to be appended to the 
13571:    unix timestamp to form the suffix, if the plain timestamp is already
13572:    in use.  Default is to not do this, but simply increment the unix 
13573:    timestamp by 1 until a unique key is obtained.
13574: 
13575: 7. who: holder of locking key; defaults to user:domain for user.
13576: 
13577: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
13578:    retrying); default is 3.
13579: 
13580: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
13581: 
13582: Returns:
13583: 
13584: 1. suffix obtained (numeric)
13585: 
13586: 2. result of deleting locking key (ok if deleted, or lock never obtained)
13587: 
13588: 3. error: contains (localized) error message if an error occurred.
13589: 
13590: 
13591: =back
13592: 
13593: =head2 HTTP Helper Routines
13594: 
13595: =over 4
13596: 
13597: =item *
13598: 
13599: escape() : unpack non-word characters into CGI-compatible hex codes
13600: 
13601: =item *
13602: 
13603: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
13604: 
13605: =back
13606: 
13607: =head1 PRIVATE SUBROUTINES
13608: 
13609: =head2 Underlying communication routines (Shouldn't call)
13610: 
13611: =over 4
13612: 
13613: =item *
13614: 
13615: subreply() : tries to pass a message to lonc, returns con_lost if incapable
13616: 
13617: =item *
13618: 
13619: reply() : uses subreply to send a message to remote machine, logs all failures
13620: 
13621: =item *
13622: 
13623: critical() : passes a critical message to another server; if cannot
13624: get through then place message in connection buffer directory and
13625: returns con_delayed, if incapable of saving message, returns
13626: con_failed
13627: 
13628: =item *
13629: 
13630: reconlonc() : tries to reconnect lonc client processes.
13631: 
13632: =back
13633: 
13634: =head2 Resource Access Logging
13635: 
13636: =over 4
13637: 
13638: =item *
13639: 
13640: flushcourselogs() : flush (save) buffer logs and access logs
13641: 
13642: =item *
13643: 
13644: courselog($what) : save message for course in hash
13645: 
13646: =item *
13647: 
13648: courseacclog($what) : save message for course using &courselog().  Perform
13649: special processing for specific resource types (problems, exams, quizzes, etc).
13650: 
13651: =item *
13652: 
13653: goodbye() : flush course logs and log shutting down; it is called in srm.conf
13654: as a PerlChildExitHandler
13655: 
13656: =back
13657: 
13658: =head2 Other
13659: 
13660: =over 4
13661: 
13662: =item *
13663: 
13664: symblist($mapname,%newhash) : update symbolic storage links
13665: 
13666: =back
13667: 
13668: =cut
13669: 

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