File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1188: download - view: text, annotated - select for diffs
Mon Aug 27 14:33:24 2012 UTC (11 years, 10 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Add the new first arg ($context) to places where &lonnet::write_log() is
  called.
- Reverse order of username and domain args in write_log() and
  callers in lonnet.pm for consistency with original calls in londocs.pm,
  lonparmset.pm, slotrequest.pm.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1188 2012/08/27 14:33:24 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
   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:     return $handle;
  638: }
  639: 
  640: sub timed_flock {
  641:     my ($file,$lock_type) = @_;
  642:     my $failed=0;
  643:     eval {
  644: 	local $SIG{__DIE__}='DEFAULT';
  645: 	local $SIG{ALRM}=sub {
  646: 	    $failed=1;
  647: 	    die("failed lock");
  648: 	};
  649: 	alarm(13);
  650: 	flock($file,$lock_type);
  651: 	alarm(0);
  652:     };
  653:     if ($failed) {
  654: 	return undef;
  655:     } else {
  656: 	return 1;
  657:     }
  658: }
  659: 
  660: # ---------------------------------------------------------- Append Environment
  661: 
  662: sub appenv {
  663:     my ($newenv,$roles) = @_;
  664:     if (ref($newenv) eq 'HASH') {
  665:         foreach my $key (keys(%{$newenv})) {
  666:             my $refused = 0;
  667: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  668:                 $refused = 1;
  669:                 if (ref($roles) eq 'ARRAY') {
  670:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
  671:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  672:                         $refused = 0;
  673:                     }
  674:                 }
  675:             }
  676:             if ($refused) {
  677:                 &logthis("<font color=\"blue\">WARNING: ".
  678:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  679:                          .'</font>');
  680: 	        delete($newenv->{$key});
  681:             } else {
  682:                 $env{$key}=$newenv->{$key};
  683:             }
  684:         }
  685:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
  686:         if ($opened
  687: 	    && &timed_flock($env_file,LOCK_EX)
  688: 	    &&
  689: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  690: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  691: 	    while (my ($key,$value) = each(%{$newenv})) {
  692: 	        $disk_env{$key} = $value;
  693: 	    }
  694: 	    untie(%disk_env);
  695:         }
  696:     }
  697:     return 'ok';
  698: }
  699: # ----------------------------------------------------- Delete from Environment
  700: 
  701: sub delenv {
  702:     my ($delthis,$regexp,$roles) = @_;
  703:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
  704:         my $refused = 1;
  705:         if (ref($roles) eq 'ARRAY') {
  706:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
  707:             if (grep(/^\Q$role\E$/,@{$roles})) {
  708:                 $refused = 0;
  709:             }
  710:         }
  711:         if ($refused) {
  712:             &logthis("<font color=\"blue\">WARNING: ".
  713:                      "Attempt to delete from environment ".$delthis);
  714:             return 'error';
  715:         }
  716:     }
  717:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  718:     if ($opened
  719: 	&& &timed_flock($env_file,LOCK_EX)
  720: 	&&
  721: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  722: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  723: 	foreach my $key (keys(%disk_env)) {
  724: 	    if ($regexp) {
  725:                 if ($key=~/^$delthis/) {
  726:                     delete($env{$key});
  727:                     delete($disk_env{$key});
  728:                 } 
  729:             } else {
  730:                 if ($key=~/^\Q$delthis\E/) {
  731: 		    delete($env{$key});
  732: 		    delete($disk_env{$key});
  733: 	        }
  734:             }
  735: 	}
  736: 	untie(%disk_env);
  737:     }
  738:     return 'ok';
  739: }
  740: 
  741: sub get_env_multiple {
  742:     my ($name) = @_;
  743:     my @values;
  744:     if (defined($env{$name})) {
  745:         # exists is it an array
  746:         if (ref($env{$name})) {
  747:             @values=@{ $env{$name} };
  748:         } else {
  749:             $values[0]=$env{$name};
  750:         }
  751:     }
  752:     return(@values);
  753: }
  754: 
  755: # ------------------------------------------------------------------- Locking
  756: 
  757: sub set_lock {
  758:     my ($text)=@_;
  759:     $locknum++;
  760:     my $id=$$.'-'.$locknum;
  761:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  762:              'session.lock.'.$id => $text});
  763:     return $id;
  764: }
  765: 
  766: sub get_locks {
  767:     my $num=0;
  768:     my %texts=();
  769:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  770:        if ($lock=~/\w/) {
  771:           $num++;
  772:           $texts{$lock}=$env{'session.lock.'.$lock};
  773:        }
  774:    }
  775:    return ($num,%texts);
  776: }
  777: 
  778: sub remove_lock {
  779:     my ($id)=@_;
  780:     my $newlocks='';
  781:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  782:        if (($lock=~/\w/) && ($lock ne $id)) {
  783:           $newlocks.=','.$lock;
  784:        }
  785:     }
  786:     &appenv({'session.locks' => $newlocks});
  787:     &delenv('session.lock.'.$id);
  788: }
  789: 
  790: sub remove_all_locks {
  791:     my $activelocks=$env{'session.locks'};
  792:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  793:        if ($lock=~/\w/) {
  794:           &remove_lock($lock);
  795:        }
  796:     }
  797: }
  798: 
  799: 
  800: # ------------------------------------------ Find out current server userload
  801: sub userload {
  802:     my $numusers=0;
  803:     {
  804: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  805: 	my $filename;
  806: 	my $curtime=time;
  807: 	while ($filename=readdir(LONIDS)) {
  808: 	    next if ($filename eq '.' || $filename eq '..');
  809: 	    next if ($filename =~ /publicuser_\d+\.id/);
  810: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  811: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  812: 	}
  813: 	closedir(LONIDS);
  814:     }
  815:     my $userloadpercent=0;
  816:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  817:     if ($maxuserload) {
  818: 	$userloadpercent=100*$numusers/$maxuserload;
  819:     }
  820:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  821:     return $userloadpercent;
  822: }
  823: 
  824: # ------------------------------ Find server with least workload from spare.tab
  825: 
  826: sub spareserver {
  827:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
  828:     my $spare_server;
  829:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  830:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  831:                                                      :  $userloadpercent;
  832:     my ($uint_dom,$remotesessions);
  833:     if (($udom ne '') && (&domain($udom) ne '')) {
  834:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
  835:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
  836:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
  837:         $remotesessions = $udomdefaults{'remotesessions'};
  838:     }
  839:     my $spareshash = &this_host_spares($udom);
  840:     if (ref($spareshash) eq 'HASH') {
  841:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  842:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  843:                 if ($uint_dom) {
  844:                     next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
  845:                                                  $try_server));
  846:                 }
  847: 	        ($spare_server, $lowest_load) =
  848: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
  849:             }
  850:         }
  851: 
  852:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
  853: 
  854:         if (!$found_server) {
  855:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
  856: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
  857:                     if ($uint_dom) {
  858:                         next unless (&spare_can_host($udom,$uint_dom,
  859:                                                      $remotesessions,$try_server));
  860:                     }
  861: 	            ($spare_server, $lowest_load) =
  862: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
  863:                 }
  864: 	    }
  865:         }
  866:     }
  867: 
  868:     if (!$want_server_name) {
  869:         my $protocol = 'http';
  870:         if ($protocol{$spare_server} eq 'https') {
  871:             $protocol = $protocol{$spare_server};
  872:         }
  873:         if (defined($spare_server)) {
  874:             my $hostname = &hostname($spare_server);
  875:             if (defined($hostname)) {
  876: 	        $spare_server = $protocol.'://'.$hostname;
  877:             }
  878:         }
  879:     }
  880:     return $spare_server;
  881: }
  882: 
  883: sub compare_server_load {
  884:     my ($try_server, $spare_server, $lowest_load) = @_;
  885: 
  886:     my $loadans     = &reply('load',    $try_server);
  887:     my $userloadans = &reply('userload',$try_server);
  888: 
  889:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  890: 	return ($spare_server, $lowest_load); #didn't get a number from the server
  891:     }
  892: 
  893:     my $load;
  894:     if ($loadans =~ /\d/) {
  895: 	if ($userloadans =~ /\d/) {
  896: 	    #both are numbers, pick the bigger one
  897: 	    $load = ($loadans > $userloadans) ? $loadans 
  898: 		                              : $userloadans;
  899: 	} else {
  900: 	    $load = $loadans;
  901: 	}
  902:     } else {
  903: 	$load = $userloadans;
  904:     }
  905: 
  906:     if (($load =~ /\d/) && ($load < $lowest_load)) {
  907: 	$spare_server = $try_server;
  908: 	$lowest_load  = $load;
  909:     }
  910:     return ($spare_server,$lowest_load);
  911: }
  912: 
  913: # --------------------------- ask offload servers if user already has a session
  914: sub find_existing_session {
  915:     my ($udom,$uname) = @_;
  916:     my $spareshash = &this_host_spares($udom);
  917:     if (ref($spareshash) eq 'HASH') {
  918:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  919:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  920:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
  921:             }
  922:         }
  923:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
  924:             foreach my $try_server (@{ $spareshash->{'default'} }) {
  925:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
  926:             }
  927:         }
  928:     }
  929:     return;
  930: }
  931: 
  932: # -------------------------------- ask if server already has a session for user
  933: sub has_user_session {
  934:     my ($lonid,$udom,$uname) = @_;
  935:     my $result = &reply(join(':','userhassession',
  936: 			     map {&escape($_)} ($udom,$uname)),$lonid);
  937:     return 1 if ($result eq 'ok');
  938: 
  939:     return 0;
  940: }
  941: 
  942: # --------- determine least loaded server in a user's domain which allows login
  943: 
  944: sub choose_server {
  945:     my ($udom,$checkloginvia) = @_;
  946:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
  947:     my %servers = &get_servers($udom);
  948:     my $lowest_load = 30000;
  949:     my ($login_host,$hostname,$portal_path,$isredirect);
  950:     foreach my $lonhost (keys(%servers)) {
  951:         my $loginvia;
  952:         if ($checkloginvia) {
  953:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
  954:             if ($loginvia) {
  955:                 my ($server,$path) = split(/:/,$loginvia);
  956:                 ($login_host, $lowest_load) =
  957:                     &compare_server_load($server, $login_host, $lowest_load);
  958:                 if ($login_host eq $server) {
  959:                     $portal_path = $path;
  960:                     $isredirect = 1;
  961:                 }
  962:             } else {
  963:                 ($login_host, $lowest_load) =
  964:                     &compare_server_load($lonhost, $login_host, $lowest_load);
  965:                 if ($login_host eq $lonhost) {
  966:                     $portal_path = '';
  967:                     $isredirect = ''; 
  968:                 }
  969:             }
  970:         } else {
  971:             ($login_host, $lowest_load) =
  972:                 &compare_server_load($lonhost, $login_host, $lowest_load);
  973:         }
  974:     }
  975:     if ($login_host ne '') {
  976:         $hostname = &hostname($login_host);
  977:     }
  978:     return ($login_host,$hostname,$portal_path,$isredirect);
  979: }
  980: 
  981: # --------------------------------------------- Try to change a user's password
  982: 
  983: sub changepass {
  984:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
  985:     $currentpass = &escape($currentpass);
  986:     $newpass     = &escape($newpass);
  987:     my $lonhost = $perlvar{'lonHostID'};
  988:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
  989: 		       $server);
  990:     if (! $answer) {
  991: 	&logthis("No reply on password change request to $server ".
  992: 		 "by $uname in domain $udom.");
  993:     } elsif ($answer =~ "^ok") {
  994:         &logthis("$uname in $udom successfully changed their password ".
  995: 		 "on $server.");
  996:     } elsif ($answer =~ "^pwchange_failure") {
  997: 	&logthis("$uname in $udom was unable to change their password ".
  998: 		 "on $server.  The action was blocked by either lcpasswd ".
  999: 		 "or pwchange");
 1000:     } elsif ($answer =~ "^non_authorized") {
 1001:         &logthis("$uname in $udom did not get their password correct when ".
 1002: 		 "attempting to change it on $server.");
 1003:     } elsif ($answer =~ "^auth_mode_error") {
 1004:         &logthis("$uname in $udom attempted to change their password despite ".
 1005: 		 "not being locally or internally authenticated on $server.");
 1006:     } elsif ($answer =~ "^unknown_user") {
 1007:         &logthis("$uname in $udom attempted to change their password ".
 1008: 		 "on $server but were unable to because $server is not ".
 1009: 		 "their home server.");
 1010:     } elsif ($answer =~ "^refused") {
 1011: 	&logthis("$server refused to change $uname in $udom password because ".
 1012: 		 "it was sent an unencrypted request to change the password.");
 1013:     } elsif ($answer =~ "invalid_client") {
 1014:         &logthis("$server refused to change $uname in $udom password because ".
 1015:                  "it was a reset by e-mail originating from an invalid server.");
 1016:     }
 1017:     return $answer;
 1018: }
 1019: 
 1020: # ----------------------- Try to determine user's current authentication scheme
 1021: 
 1022: sub queryauthenticate {
 1023:     my ($uname,$udom)=@_;
 1024:     my $uhome=&homeserver($uname,$udom);
 1025:     if (!$uhome) {
 1026: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
 1027: 	return 'no_host';
 1028:     }
 1029:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
 1030:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
 1031: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1032:     }
 1033:     return $answer;
 1034: }
 1035: 
 1036: # --------- Try to authenticate user from domain's lib servers (first this one)
 1037: 
 1038: sub authenticate {
 1039:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
 1040:     $upass=&escape($upass);
 1041:     $uname= &LONCAPA::clean_username($uname);
 1042:     my $uhome=&homeserver($uname,$udom,1);
 1043:     my $newhome;
 1044:     if ((!$uhome) || ($uhome eq 'no_host')) {
 1045: # Maybe the machine was offline and only re-appeared again recently?
 1046:         &reconlonc();
 1047: # One more
 1048: 	$uhome=&homeserver($uname,$udom,1);
 1049:         if (($uhome eq 'no_host') && $checkdefauth) {
 1050:             if (defined(&domain($udom,'primary'))) {
 1051:                 $newhome=&domain($udom,'primary');
 1052:             }
 1053:             if ($newhome ne '') {
 1054:                 $uhome = $newhome;
 1055:             }
 1056:         }
 1057: 	if ((!$uhome) || ($uhome eq 'no_host')) {
 1058: 	    &logthis("User $uname at $udom is unknown in authenticate");
 1059: 	    return 'no_host';
 1060:         }
 1061:     }
 1062:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
 1063:     if ($answer eq 'authorized') {
 1064:         if ($newhome) {
 1065:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
 1066:             return 'no_account_on_host'; 
 1067:         } else {
 1068:             &logthis("User $uname at $udom authorized by $uhome");
 1069:             return $uhome;
 1070:         }
 1071:     }
 1072:     if ($answer eq 'non_authorized') {
 1073: 	&logthis("User $uname at $udom rejected by $uhome");
 1074: 	return 'no_host'; 
 1075:     }
 1076:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1077:     return 'no_host';
 1078: }
 1079: 
 1080: sub can_host_session {
 1081:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
 1082:     my $canhost = 1;
 1083:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
 1084:     if (ref($remotesessions) eq 'HASH') {
 1085:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
 1086:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
 1087:                 $canhost = 0;
 1088:             } else {
 1089:                 $canhost = 1;
 1090:             }
 1091:         }
 1092:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
 1093:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
 1094:                 $canhost = 1;
 1095:             } else {
 1096:                 $canhost = 0;
 1097:             }
 1098:         }
 1099:         if ($canhost) {
 1100:             if ($remotesessions->{'version'} ne '') {
 1101:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
 1102:                 if ($reqmajor ne '' && $reqminor ne '') {
 1103:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
 1104:                         my $major = $1;
 1105:                         my $minor = $2;
 1106:                         if (($major < $reqmajor ) ||
 1107:                             (($major == $reqmajor) && ($minor < $reqminor))) {
 1108:                             $canhost = 0;
 1109:                         }
 1110:                     } else {
 1111:                         $canhost = 0;
 1112:                     }
 1113:                 }
 1114:             }
 1115:         }
 1116:     }
 1117:     if ($canhost) {
 1118:         if (ref($hostedsessions) eq 'HASH') {
 1119:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1120:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 1121:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
 1122:                 if (($uint_dom ne '') && 
 1123:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
 1124:                     $canhost = 0;
 1125:                 } else {
 1126:                     $canhost = 1;
 1127:                 }
 1128:             }
 1129:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
 1130:                 if (($uint_dom ne '') && 
 1131:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
 1132:                     $canhost = 1;
 1133:                 } else {
 1134:                     $canhost = 0;
 1135:                 }
 1136:             }
 1137:         }
 1138:     }
 1139:     return $canhost;
 1140: }
 1141: 
 1142: sub spare_can_host {
 1143:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
 1144:     my $canhost=1;
 1145:     my @intdoms;
 1146:     my $internet_names = &Apache::lonnet::get_internet_names($try_server);
 1147:     if (ref($internet_names) eq 'ARRAY') {
 1148:         @intdoms = @{$internet_names};
 1149:     }
 1150:     unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1151:         my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
 1152:         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
 1153:         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
 1154:         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
 1155:         $canhost = &can_host_session($udom,$try_server,$remoterev,
 1156:                                      $remotesessions,
 1157:                                      $defdomdefaults{'hostedsessions'});
 1158:     }
 1159:     return $canhost;
 1160: }
 1161: 
 1162: sub this_host_spares {
 1163:     my ($dom) = @_;
 1164:     my ($dom_in_use,$lonhost_in_use,$result);
 1165:     my @hosts = &current_machine_ids();
 1166:     foreach my $lonhost (@hosts) {
 1167:         if (&host_domain($lonhost) eq $dom) {
 1168:             $dom_in_use = $dom;
 1169:             $lonhost_in_use = $lonhost;
 1170:             last;
 1171:         }
 1172:     }
 1173:     if ($dom_in_use ne '') {
 1174:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1175:     }
 1176:     if (ref($result) ne 'HASH') {
 1177:         $lonhost_in_use = $perlvar{'lonHostID'};
 1178:         $dom_in_use = &host_domain($lonhost_in_use);
 1179:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1180:         if (ref($result) ne 'HASH') {
 1181:             $result = \%spareid;
 1182:         }
 1183:     }
 1184:     return $result;
 1185: }
 1186: 
 1187: sub spares_for_offload  {
 1188:     my ($dom_in_use,$lonhost_in_use) = @_;
 1189:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
 1190:     if (defined($cached)) {
 1191:         return $result;
 1192:     } else {
 1193:         my $cachetime = 60*60*24;
 1194:         my %domconfig =
 1195:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
 1196:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1197:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
 1198:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
 1199:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
 1200:                 }
 1201:             }
 1202:         }
 1203:     }
 1204:     return;
 1205: }
 1206: 
 1207: sub get_lonbalancer_config {
 1208:     my ($servers) = @_;
 1209:     my ($currbalancer,$currtargets);
 1210:     if (ref($servers) eq 'HASH') {
 1211:         foreach my $server (keys(%{$servers})) {
 1212:             my %what = (
 1213:                          spareid => 1,
 1214:                          perlvar => 1,
 1215:                        );
 1216:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
 1217:             if ($result eq 'ok') {
 1218:                 if (ref($returnhash) eq 'HASH') {
 1219:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
 1220:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
 1221:                             $currbalancer = $server;
 1222:                             $currtargets = {};
 1223:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
 1224:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
 1225:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
 1226:                                 }
 1227:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
 1228:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
 1229:                                 }
 1230:                             }
 1231:                             last;
 1232:                         }
 1233:                     }
 1234:                 }
 1235:             }
 1236:         }
 1237:     }
 1238:     return ($currbalancer,$currtargets);
 1239: }
 1240: 
 1241: sub check_loadbalancing {
 1242:     my ($uname,$udom) = @_;
 1243:     my ($is_balancer,$dom_in_use,$homeintdom,$rule_in_effect,
 1244:         $offloadto,$otherserver);
 1245:     my $lonhost = $perlvar{'lonHostID'};
 1246:     my @hosts = &current_machine_ids();
 1247:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1248:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
 1249:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
 1250:     my $serverhomedom = &host_domain($lonhost);
 1251: 
 1252:     my $cachetime = 60*60*24;
 1253: 
 1254:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1255:         $dom_in_use = $udom;
 1256:         $homeintdom = 1;
 1257:     } else {
 1258:         $dom_in_use = $serverhomedom;
 1259:     }
 1260:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
 1261:     unless (defined($cached)) {
 1262:         my %domconfig =
 1263:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
 1264:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1265:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1266:         }
 1267:     }
 1268:     if (ref($result) eq 'HASH') {
 1269:         my $currbalancer = $result->{'lonhost'};
 1270:         my $currtargets = $result->{'targets'};
 1271:         my $currrules = $result->{'rules'};
 1272:         if ($currbalancer ne '') {
 1273:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
 1274:                 $is_balancer = 1;
 1275:             }
 1276:         }
 1277:         if ($is_balancer) {
 1278:             if (ref($currrules) eq 'HASH') {
 1279:                 if ($homeintdom) {
 1280:                     if ($uname ne '') {
 1281:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
 1282:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
 1283:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
 1284:                                 $rule_in_effect = $currrules->{'_LC_author'};
 1285:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
 1286:                                 $rule_in_effect = $currrules->{'_LC_adv'}
 1287:                             }
 1288:                         }
 1289:                         if ($rule_in_effect eq '') {
 1290:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
 1291:                             if ($userenv{'inststatus'} ne '') {
 1292:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
 1293:                                 my ($othertitle,$usertypes,$types) =
 1294:                                     &Apache::loncommon::sorted_inst_types($udom);
 1295:                                 if (ref($types) eq 'ARRAY') {
 1296:                                     foreach my $type (@{$types}) {
 1297:                                         if (grep(/^\Q$type\E$/,@statuses)) {
 1298:                                             if (exists($currrules->{$type})) {
 1299:                                                 $rule_in_effect = $currrules->{$type};
 1300:                                             }
 1301:                                         }
 1302:                                     }
 1303:                                 }
 1304:                             } else {
 1305:                                 if (exists($currrules->{'default'})) {
 1306:                                     $rule_in_effect = $currrules->{'default'};
 1307:                                 }
 1308:                             }
 1309:                         }
 1310:                     } else {
 1311:                         if (exists($currrules->{'default'})) {
 1312:                             $rule_in_effect = $currrules->{'default'};
 1313:                         }
 1314:                     }
 1315:                 } else {
 1316:                     if ($currrules->{'_LC_external'} ne '') {
 1317:                         $rule_in_effect = $currrules->{'_LC_external'};
 1318:                     }
 1319:                 }
 1320:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1321:                                                        $uname,$udom);
 1322:             }
 1323:         }
 1324:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
 1325:         my ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
 1326:         unless (defined($cached)) {
 1327:             my %domconfig =
 1328:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
 1329:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1330:                 $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1331:             }
 1332:         }
 1333:         if (ref($result) eq 'HASH') {
 1334:             my $currbalancer = $result->{'lonhost'};
 1335:             my $currtargets = $result->{'targets'};
 1336:             my $currrules = $result->{'rules'};
 1337: 
 1338:             if ($currbalancer eq $lonhost) {
 1339:                 $is_balancer = 1;
 1340:                 if (ref($currrules) eq 'HASH') {
 1341:                     if ($currrules->{'_LC_internetdom'} ne '') {
 1342:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
 1343:                     }
 1344:                 }
 1345:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1346:                                                        $uname,$udom);
 1347:             }
 1348:         } else {
 1349:             if ($perlvar{'lonBalancer'} eq 'yes') {
 1350:                 $is_balancer = 1;
 1351:                 $offloadto = &this_host_spares($dom_in_use);
 1352:             }
 1353:         }
 1354:     } else {
 1355:         if ($perlvar{'lonBalancer'} eq 'yes') {
 1356:             $is_balancer = 1;
 1357:             $offloadto = &this_host_spares($dom_in_use);
 1358:         }
 1359:     }
 1360:     if ($is_balancer) {
 1361:         my $lowest_load = 30000;
 1362:         if (ref($offloadto) eq 'HASH') {
 1363:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
 1364:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
 1365:                     ($otherserver,$lowest_load) =
 1366:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1367:                 }
 1368:             }
 1369:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
 1370: 
 1371:             if (!$found_server) {
 1372:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
 1373:                     foreach my $try_server (@{$offloadto->{'default'}}) {
 1374:                         ($otherserver,$lowest_load) =
 1375:                             &compare_server_load($try_server,$otherserver,$lowest_load);
 1376:                     }
 1377:                 }
 1378:             }
 1379:         } elsif (ref($offloadto) eq 'ARRAY') {
 1380:             if (@{$offloadto} == 1) {
 1381:                 $otherserver = $offloadto->[0];
 1382:             } elsif (@{$offloadto} > 1) {
 1383:                 foreach my $try_server (@{$offloadto}) {
 1384:                     ($otherserver,$lowest_load) =
 1385:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1386:                 }
 1387:             }
 1388:         }
 1389:         if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
 1390:             $is_balancer = 0;
 1391:             if ($uname ne '' && $udom ne '') {
 1392:                 if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
 1393:                     
 1394:                     &appenv({'user.loadbalexempt'     => $lonhost,  
 1395:                              'user.loadbalcheck.time' => time});
 1396:                 }
 1397:             }
 1398:         }
 1399:     }
 1400:     return ($is_balancer,$otherserver);
 1401: }
 1402: 
 1403: sub get_loadbalancer_targets {
 1404:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
 1405:     my $offloadto;
 1406:     if ($rule_in_effect eq 'none') {
 1407:         return [$perlvar{'lonHostID'}];
 1408:     } elsif ($rule_in_effect eq '') {
 1409:         $offloadto = $currtargets;
 1410:     } else {
 1411:         if ($rule_in_effect eq 'homeserver') {
 1412:             my $homeserver = &homeserver($uname,$udom);
 1413:             if ($homeserver ne 'no_host') {
 1414:                 $offloadto = [$homeserver];
 1415:             }
 1416:         } elsif ($rule_in_effect eq 'externalbalancer') {
 1417:             my %domconfig =
 1418:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1419:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1420:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
 1421:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
 1422:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
 1423:                     }
 1424:                 }
 1425:             } else {
 1426:                 my %servers = &internet_dom_servers($udom);
 1427:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
 1428:                 if (&hostname($remotebalancer) ne '') {
 1429:                     $offloadto = [$remotebalancer];
 1430:                 }
 1431:             }
 1432:         } elsif (&hostname($rule_in_effect) ne '') {
 1433:             $offloadto = [$rule_in_effect];
 1434:         }
 1435:     }
 1436:     return $offloadto;
 1437: }
 1438: 
 1439: sub internet_dom_servers {
 1440:     my ($dom) = @_;
 1441:     my (%uniqservers,%servers);
 1442:     my $primaryserver = &hostname(&domain($dom,'primary'));
 1443:     my @machinedoms = &machine_domains($primaryserver);
 1444:     foreach my $mdom (@machinedoms) {
 1445:         my %currservers = %servers;
 1446:         my %server = &get_servers($mdom);
 1447:         %servers = (%currservers,%server);
 1448:     }
 1449:     my %by_hostname;
 1450:     foreach my $id (keys(%servers)) {
 1451:         push(@{$by_hostname{$servers{$id}}},$id);
 1452:     }
 1453:     foreach my $hostname (sort(keys(%by_hostname))) {
 1454:         if (@{$by_hostname{$hostname}} > 1) {
 1455:             my $match = 0;
 1456:             foreach my $id (@{$by_hostname{$hostname}}) {
 1457:                 if (&host_domain($id) eq $dom) {
 1458:                     $uniqservers{$id} = $hostname;
 1459:                     $match = 1;
 1460:                 }
 1461:             }
 1462:             unless ($match) {
 1463:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1464:             }
 1465:         } else {
 1466:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1467:         }
 1468:     }
 1469:     return %uniqservers;
 1470: }
 1471: 
 1472: # ---------------------- Find the homebase for a user from domain's lib servers
 1473: 
 1474: my %homecache;
 1475: sub homeserver {
 1476:     my ($uname,$udom,$ignoreBadCache)=@_;
 1477:     my $index="$uname:$udom";
 1478: 
 1479:     if (exists($homecache{$index})) { return $homecache{$index}; }
 1480: 
 1481:     my %servers = &get_servers($udom,'library');
 1482:     foreach my $tryserver (keys(%servers)) {
 1483:         next if ($ignoreBadCache ne 'true' && 
 1484: 		 exists($badServerCache{$tryserver}));
 1485: 
 1486: 	my $answer=reply("home:$udom:$uname",$tryserver);
 1487: 	if ($answer eq 'found') {
 1488: 	    delete($badServerCache{$tryserver}); 
 1489: 	    return $homecache{$index}=$tryserver;
 1490: 	} elsif ($answer eq 'no_host') {
 1491: 	    $badServerCache{$tryserver}=1;
 1492: 	}
 1493:     }    
 1494:     return 'no_host';
 1495: }
 1496: 
 1497: # ------------------------------------- Find the usernames behind a list of IDs
 1498: 
 1499: sub idget {
 1500:     my ($udom,@ids)=@_;
 1501:     my %returnhash=();
 1502:     
 1503:     my %servers = &get_servers($udom,'library');
 1504:     foreach my $tryserver (keys(%servers)) {
 1505: 	my $idlist=join('&',@ids);
 1506: 	$idlist=~tr/A-Z/a-z/; 
 1507: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
 1508: 	my @answer=();
 1509: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
 1510: 	    @answer=split(/\&/,$reply);
 1511: 	}                    ;
 1512: 	my $i;
 1513: 	for ($i=0;$i<=$#ids;$i++) {
 1514: 	    if ($answer[$i]) {
 1515: 		$returnhash{$ids[$i]}=$answer[$i];
 1516: 	    } 
 1517: 	}
 1518:     } 
 1519:     return %returnhash;
 1520: }
 1521: 
 1522: # ------------------------------------- Find the IDs behind a list of usernames
 1523: 
 1524: sub idrget {
 1525:     my ($udom,@unames)=@_;
 1526:     my %returnhash=();
 1527:     foreach my $uname (@unames) {
 1528:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
 1529:     }
 1530:     return %returnhash;
 1531: }
 1532: 
 1533: # ------------------------------- Store away a list of names and associated IDs
 1534: 
 1535: sub idput {
 1536:     my ($udom,%ids)=@_;
 1537:     my %servers=();
 1538:     foreach my $uname (keys(%ids)) {
 1539: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
 1540:         my $uhom=&homeserver($uname,$udom);
 1541:         if ($uhom ne 'no_host') {
 1542:             my $id=&escape($ids{$uname});
 1543:             $id=~tr/A-Z/a-z/;
 1544:             my $esc_unam=&escape($uname);
 1545: 	    if ($servers{$uhom}) {
 1546: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
 1547:             } else {
 1548:                 $servers{$uhom}=$id.'='.$esc_unam;
 1549:             }
 1550:         }
 1551:     }
 1552:     foreach my $server (keys(%servers)) {
 1553:         &critical('idput:'.$udom.':'.$servers{$server},$server);
 1554:     }
 1555: }
 1556: 
 1557: # ------------------------------dump from db file owned by domainconfig user
 1558: sub dump_dom {
 1559:     my ($namespace, $udom, $regexp) = @_;
 1560: 
 1561:     $udom ||= $env{'user.domain'};
 1562: 
 1563:     return () unless $udom;
 1564: 
 1565:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
 1566: }
 1567: 
 1568: # ------------------------------------------ get items from domain db files   
 1569: 
 1570: sub get_dom {
 1571:     my ($namespace,$storearr,$udom,$uhome)=@_;
 1572:     my $items='';
 1573:     foreach my $item (@$storearr) {
 1574:         $items.=&escape($item).'&';
 1575:     }
 1576:     $items=~s/\&$//;
 1577:     if (!$udom) {
 1578:         $udom=$env{'user.domain'};
 1579:         if (defined(&domain($udom,'primary'))) {
 1580:             $uhome=&domain($udom,'primary');
 1581:         } else {
 1582:             undef($uhome);
 1583:         }
 1584:     } else {
 1585:         if (!$uhome) {
 1586:             if (defined(&domain($udom,'primary'))) {
 1587:                 $uhome=&domain($udom,'primary');
 1588:             }
 1589:         }
 1590:     }
 1591:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1592:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 1593:         my %returnhash;
 1594:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 1595:             return %returnhash;
 1596:         }
 1597:         my @pairs=split(/\&/,$rep);
 1598:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 1599:             return @pairs;
 1600:         }
 1601:         my $i=0;
 1602:         foreach my $item (@$storearr) {
 1603:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 1604:             $i++;
 1605:         }
 1606:         return %returnhash;
 1607:     } else {
 1608:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 1609:     }
 1610: }
 1611: 
 1612: # -------------------------------------------- put items in domain db files 
 1613: 
 1614: sub put_dom {
 1615:     my ($namespace,$storehash,$udom,$uhome)=@_;
 1616:     if (!$udom) {
 1617:         $udom=$env{'user.domain'};
 1618:         if (defined(&domain($udom,'primary'))) {
 1619:             $uhome=&domain($udom,'primary');
 1620:         } else {
 1621:             undef($uhome);
 1622:         }
 1623:     } else {
 1624:         if (!$uhome) {
 1625:             if (defined(&domain($udom,'primary'))) {
 1626:                 $uhome=&domain($udom,'primary');
 1627:             }
 1628:         }
 1629:     } 
 1630:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1631:         my $items='';
 1632:         foreach my $item (keys(%$storehash)) {
 1633:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 1634:         }
 1635:         $items=~s/\&$//;
 1636:         return &reply("putdom:$udom:$namespace:$items",$uhome);
 1637:     } else {
 1638:         &logthis("put_dom failed - no homeserver and/or domain");
 1639:     }
 1640: }
 1641: 
 1642: # --------------------- newput for items in db file owned by domainconfig user
 1643: sub newput_dom {
 1644:     my ($namespace,$storehash,$udom) = @_;
 1645:     my $result;
 1646:     if (!$udom) {
 1647:         $udom=$env{'user.domain'};
 1648:     }
 1649:     if ($udom) {
 1650:         my $uname = &get_domainconfiguser($udom);
 1651:         $result = &newput($namespace,$storehash,$udom,$uname);
 1652:     }
 1653:     return $result;
 1654: }
 1655: 
 1656: # --------------------- delete for items in db file owned by domainconfig user
 1657: sub del_dom {
 1658:     my ($namespace,$storearr,$udom)=@_;
 1659:     if (ref($storearr) eq 'ARRAY') {
 1660:         if (!$udom) {
 1661:             $udom=$env{'user.domain'};
 1662:         }
 1663:         if ($udom) {
 1664:             my $uname = &get_domainconfiguser($udom); 
 1665:             return &del($namespace,$storearr,$udom,$uname);
 1666:         }
 1667:     }
 1668: }
 1669: 
 1670: # ----------------------------------construct domainconfig user for a domain 
 1671: sub get_domainconfiguser {
 1672:     my ($udom) = @_;
 1673:     return $udom.'-domainconfig';
 1674: }
 1675: 
 1676: sub retrieve_inst_usertypes {
 1677:     my ($udom) = @_;
 1678:     my (%returnhash,@order);
 1679:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 1680:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 1681:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 1682:         %returnhash = %{$domdefs{'inststatustypes'}};
 1683:         @order = @{$domdefs{'inststatusorder'}};
 1684:     } else {
 1685:         if (defined(&domain($udom,'primary'))) {
 1686:             my $uhome=&domain($udom,'primary');
 1687:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 1688:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 1689:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
 1690:                 return (\%returnhash,\@order);
 1691:             }
 1692:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 1693:             my @pairs=split(/\&/,$hashitems);
 1694:             foreach my $item (@pairs) {
 1695:                 my ($key,$value)=split(/=/,$item,2);
 1696:                 $key = &unescape($key);
 1697:                 next if ($key =~ /^error: 2 /);
 1698:                 $returnhash{$key}=&thaw_unescape($value);
 1699:             }
 1700:             my @esc_order = split(/\&/,$orderitems);
 1701:             foreach my $item (@esc_order) {
 1702:                 push(@order,&unescape($item));
 1703:             }
 1704:         } else {
 1705:             &logthis("get_dom failed - no primary domain server for $udom");
 1706:         }
 1707:     }
 1708:     return (\%returnhash,\@order);
 1709: }
 1710: 
 1711: sub is_domainimage {
 1712:     my ($url) = @_;
 1713:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
 1714:         if (&domain($1) ne '') {
 1715:             return '1';
 1716:         }
 1717:     }
 1718:     return;
 1719: }
 1720: 
 1721: sub inst_directory_query {
 1722:     my ($srch) = @_;
 1723:     my $udom = $srch->{'srchdomain'};
 1724:     my %results;
 1725:     my $homeserver = &domain($udom,'primary');
 1726:     my $outcome;
 1727:     if ($homeserver ne '') {
 1728: 	my $queryid=&reply("querysend:instdirsearch:".
 1729: 			   &escape($srch->{'srchby'}).':'.
 1730: 			   &escape($srch->{'srchterm'}).':'.
 1731: 			   &escape($srch->{'srchtype'}),$homeserver);
 1732: 	my $host=&hostname($homeserver);
 1733: 	if ($queryid !~/^\Q$host\E\_/) {
 1734: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1735: 	    return;
 1736: 	}
 1737: 	my $response = &get_query_reply($queryid);
 1738: 	my $maxtries = 5;
 1739: 	my $tries = 1;
 1740: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1741: 	    $response = &get_query_reply($queryid);
 1742: 	    $tries ++;
 1743: 	}
 1744: 
 1745:         if (!&error($response) && $response ne 'refused') {
 1746:             if ($response eq 'unavailable') {
 1747:                 $outcome = $response;
 1748:             } else {
 1749:                 $outcome = 'ok';
 1750:                 my @matches = split(/\n/,$response);
 1751:                 foreach my $match (@matches) {
 1752:                     my ($key,$value) = split(/=/,$match);
 1753:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 1754:                 }
 1755:             }
 1756:         }
 1757:     }
 1758:     return ($outcome,%results);
 1759: }
 1760: 
 1761: sub usersearch {
 1762:     my ($srch) = @_;
 1763:     my $dom = $srch->{'srchdomain'};
 1764:     my %results;
 1765:     my %libserv = &all_library();
 1766:     my $query = 'usersearch';
 1767:     foreach my $tryserver (keys(%libserv)) {
 1768:         if (&host_domain($tryserver) eq $dom) {
 1769:             my $host=&hostname($tryserver);
 1770:             my $queryid=
 1771:                 &reply("querysend:".&escape($query).':'.
 1772:                        &escape($srch->{'srchby'}).':'.
 1773:                        &escape($srch->{'srchtype'}).':'.
 1774:                        &escape($srch->{'srchterm'}),$tryserver);
 1775:             if ($queryid !~/^\Q$host\E\_/) {
 1776:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 1777:                 next;
 1778:             }
 1779:             my $reply = &get_query_reply($queryid);
 1780:             my $maxtries = 1;
 1781:             my $tries = 1;
 1782:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 1783:                 $reply = &get_query_reply($queryid);
 1784:                 $tries ++;
 1785:             }
 1786:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 1787:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 1788:             } else {
 1789:                 my @matches;
 1790:                 if ($reply =~ /\n/) {
 1791:                     @matches = split(/\n/,$reply);
 1792:                 } else {
 1793:                     @matches = split(/\&/,$reply);
 1794:                 }
 1795:                 foreach my $match (@matches) {
 1796:                     my ($uname,$udom,%userhash);
 1797:                     foreach my $entry (split(/:/,$match)) {
 1798:                         my ($key,$value) =
 1799:                             map {&unescape($_);} split(/=/,$entry);
 1800:                         $userhash{$key} = $value;
 1801:                         if ($key eq 'username') {
 1802:                             $uname = $value;
 1803:                         } elsif ($key eq 'domain') {
 1804:                             $udom = $value;
 1805:                         }
 1806:                     }
 1807:                     $results{$uname.':'.$udom} = \%userhash;
 1808:                 }
 1809:             }
 1810:         }
 1811:     }
 1812:     return %results;
 1813: }
 1814: 
 1815: sub get_instuser {
 1816:     my ($udom,$uname,$id) = @_;
 1817:     my $homeserver = &domain($udom,'primary');
 1818:     my ($outcome,%results);
 1819:     if ($homeserver ne '') {
 1820:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 1821:                            &escape($id).':'.&escape($udom),$homeserver);
 1822:         my $host=&hostname($homeserver);
 1823:         if ($queryid !~/^\Q$host\E\_/) {
 1824:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1825:             return;
 1826:         }
 1827:         my $response = &get_query_reply($queryid);
 1828:         my $maxtries = 5;
 1829:         my $tries = 1;
 1830:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1831:             $response = &get_query_reply($queryid);
 1832:             $tries ++;
 1833:         }
 1834:         if (!&error($response) && $response ne 'refused') {
 1835:             if ($response eq 'unavailable') {
 1836:                 $outcome = $response;
 1837:             } else {
 1838:                 $outcome = 'ok';
 1839:                 my @matches = split(/\n/,$response);
 1840:                 foreach my $match (@matches) {
 1841:                     my ($key,$value) = split(/=/,$match);
 1842:                     $results{&unescape($key)} = &thaw_unescape($value);
 1843:                 }
 1844:             }
 1845:         }
 1846:     }
 1847:     my %userinfo;
 1848:     if (ref($results{$uname}) eq 'HASH') {
 1849:         %userinfo = %{$results{$uname}};
 1850:     } 
 1851:     return ($outcome,%userinfo);
 1852: }
 1853: 
 1854: sub inst_rulecheck {
 1855:     my ($udom,$uname,$id,$item,$rules) = @_;
 1856:     my %returnhash;
 1857:     if ($udom ne '') {
 1858:         if (ref($rules) eq 'ARRAY') {
 1859:             @{$rules} = map {&escape($_);} (@{$rules});
 1860:             my $rulestr = join(':',@{$rules});
 1861:             my $homeserver=&domain($udom,'primary');
 1862:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1863:                 my $response;
 1864:                 if ($item eq 'username') {                
 1865:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 1866:                                               ':'.&escape($uname).':'.$rulestr,
 1867:                                               $homeserver));
 1868:                 } elsif ($item eq 'id') {
 1869:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 1870:                                               ':'.&escape($id).':'.$rulestr,
 1871:                                               $homeserver));
 1872:                 } elsif ($item eq 'selfcreate') {
 1873:                     $response=&unescape(&reply('instselfcreatecheck:'.
 1874:                                                &escape($udom).':'.&escape($uname).
 1875:                                               ':'.$rulestr,$homeserver));
 1876:                 }
 1877:                 if ($response ne 'refused') {
 1878:                     my @pairs=split(/\&/,$response);
 1879:                     foreach my $item (@pairs) {
 1880:                         my ($key,$value)=split(/=/,$item,2);
 1881:                         $key = &unescape($key);
 1882:                         next if ($key =~ /^error: 2 /);
 1883:                         $returnhash{$key}=&thaw_unescape($value);
 1884:                     }
 1885:                 }
 1886:             }
 1887:         }
 1888:     }
 1889:     return %returnhash;
 1890: }
 1891: 
 1892: sub inst_userrules {
 1893:     my ($udom,$check) = @_;
 1894:     my (%ruleshash,@ruleorder);
 1895:     if ($udom ne '') {
 1896:         my $homeserver=&domain($udom,'primary');
 1897:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1898:             my $response;
 1899:             if ($check eq 'id') {
 1900:                 $response=&reply('instidrules:'.&escape($udom),
 1901:                                  $homeserver);
 1902:             } elsif ($check eq 'email') {
 1903:                 $response=&reply('instemailrules:'.&escape($udom),
 1904:                                  $homeserver);
 1905:             } else {
 1906:                 $response=&reply('instuserrules:'.&escape($udom),
 1907:                                  $homeserver);
 1908:             }
 1909:             if (($response ne 'refused') && ($response ne 'error') && 
 1910:                 ($response ne 'unknown_cmd') && 
 1911:                 ($response ne 'no_such_host')) {
 1912:                 my ($hashitems,$orderitems) = split(/:/,$response);
 1913:                 my @pairs=split(/\&/,$hashitems);
 1914:                 foreach my $item (@pairs) {
 1915:                     my ($key,$value)=split(/=/,$item,2);
 1916:                     $key = &unescape($key);
 1917:                     next if ($key =~ /^error: 2 /);
 1918:                     $ruleshash{$key}=&thaw_unescape($value);
 1919:                 }
 1920:                 my @esc_order = split(/\&/,$orderitems);
 1921:                 foreach my $item (@esc_order) {
 1922:                     push(@ruleorder,&unescape($item));
 1923:                 }
 1924:             }
 1925:         }
 1926:     }
 1927:     return (\%ruleshash,\@ruleorder);
 1928: }
 1929: 
 1930: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 1931: 
 1932: sub get_domain_defaults {
 1933:     my ($domain) = @_;
 1934:     my $cachetime = 60*60*24;
 1935:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 1936:     if (defined($cached)) {
 1937:         if (ref($result) eq 'HASH') {
 1938:             return %{$result};
 1939:         }
 1940:     }
 1941:     my %domdefaults;
 1942:     my %domconfig =
 1943:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 1944:                                   'requestcourses','inststatus',
 1945:                                   'coursedefaults','usersessions',
 1946:                                   'requestauthor'],$domain);
 1947:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 1948:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 1949:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 1950:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 1951:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 1952:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 1953:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
 1954:     } else {
 1955:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 1956:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 1957:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 1958:     }
 1959:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 1960:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 1961:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 1962:         } else {
 1963:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 1964:         } 
 1965:         my @usertools = ('aboutme','blog','webdav','portfolio');
 1966:         foreach my $item (@usertools) {
 1967:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 1968:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 1969:             }
 1970:         }
 1971:     }
 1972:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 1973:         foreach my $item ('official','unofficial','community') {
 1974:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 1975:         }
 1976:     }
 1977:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
 1978:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
 1979:     }
 1980:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 1981:         foreach my $item ('inststatustypes','inststatusorder') {
 1982:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 1983:         }
 1984:     }
 1985:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 1986:         foreach my $item ('canuse_pdfforms') {
 1987:             $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
 1988:         }
 1989:     }
 1990:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1991:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 1992:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 1993:         }
 1994:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 1995:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 1996:         }
 1997:     }
 1998:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
 1999:                                   $cachetime);
 2000:     return %domdefaults;
 2001: }
 2002: 
 2003: # --------------------------------------------------- Assign a key to a student
 2004: 
 2005: sub assign_access_key {
 2006: #
 2007: # a valid key looks like uname:udom#comments
 2008: # comments are being appended
 2009: #
 2010:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 2011:     $kdom=
 2012:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 2013:     $knum=
 2014:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 2015:     $cdom=
 2016:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2017:     $cnum=
 2018:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2019:     $udom=$env{'user.name'} unless (defined($udom));
 2020:     $uname=$env{'user.domain'} unless (defined($uname));
 2021:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 2022:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 2023:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 2024:                                                   # assigned to this person
 2025:                                                   # - this should not happen,
 2026:                                                   # unless something went wrong
 2027:                                                   # the first time around
 2028: # ready to assign
 2029:         $logentry=$1.'; '.$logentry;
 2030:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 2031:                                                  $kdom,$knum) eq 'ok') {
 2032: # key now belongs to user
 2033: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 2034:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 2035:                 &appenv({'environment.'.$envkey => $ckey});
 2036:                 return 'ok';
 2037:             } else {
 2038:                 return 
 2039:   'error: Count not permanently assign key, will need to be re-entered later.';
 2040: 	    }
 2041:         } else {
 2042:             return 'error: Could not assign key, try again later.';
 2043:         }
 2044:     } elsif (!$existing{$ckey}) {
 2045: # the key does not exist
 2046: 	return 'error: The key does not exist';
 2047:     } else {
 2048: # the key is somebody else's
 2049: 	return 'error: The key is already in use';
 2050:     }
 2051: }
 2052: 
 2053: # ------------------------------------------ put an additional comment on a key
 2054: 
 2055: sub comment_access_key {
 2056: #
 2057: # a valid key looks like uname:udom#comments
 2058: # comments are being appended
 2059: #
 2060:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 2061:     $cdom=
 2062:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2063:     $cnum=
 2064:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2065:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2066:     if ($existing{$ckey}) {
 2067:         $existing{$ckey}.='; '.$logentry;
 2068: # ready to assign
 2069:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 2070:                                                  $cdom,$cnum) eq 'ok') {
 2071: 	    return 'ok';
 2072:         } else {
 2073: 	    return 'error: Count not store comment.';
 2074:         }
 2075:     } else {
 2076: # the key does not exist
 2077: 	return 'error: The key does not exist';
 2078:     }
 2079: }
 2080: 
 2081: # ------------------------------------------------------ Generate a set of keys
 2082: 
 2083: sub generate_access_keys {
 2084:     my ($number,$cdom,$cnum,$logentry)=@_;
 2085:     $cdom=
 2086:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2087:     $cnum=
 2088:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2089:     unless (&allowed('mky',$cdom)) { return 0; }
 2090:     unless (($cdom) && ($cnum)) { return 0; }
 2091:     if ($number>10000) { return 0; }
 2092:     sleep(2); # make sure don't get same seed twice
 2093:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 2094:     my $total=0;
 2095:     for (my $i=1;$i<=$number;$i++) {
 2096:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 2097:                   sprintf("%lx",int(100000*rand)).'-'.
 2098:                   sprintf("%lx",int(100000*rand));
 2099:        $newkey=~s/1/g/g; # folks mix up 1 and l
 2100:        $newkey=~s/0/h/g; # and also 0 and O
 2101:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 2102:        if ($existing{$newkey}) {
 2103:            $i--;
 2104:        } else {
 2105: 	  if (&put('accesskeys',
 2106:               { $newkey => '# generated '.localtime().
 2107:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 2108:                            '; '.$logentry },
 2109: 		   $cdom,$cnum) eq 'ok') {
 2110:               $total++;
 2111: 	  }
 2112:        }
 2113:     }
 2114:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 2115:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 2116:     return $total;
 2117: }
 2118: 
 2119: # ------------------------------------------------------- Validate an accesskey
 2120: 
 2121: sub validate_access_key {
 2122:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 2123:     $cdom=
 2124:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2125:     $cnum=
 2126:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2127:     $udom=$env{'user.domain'} unless (defined($udom));
 2128:     $uname=$env{'user.name'} unless (defined($uname));
 2129:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2130:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 2131: }
 2132: 
 2133: # ------------------------------------- Find the section of student in a course
 2134: sub devalidate_getsection_cache {
 2135:     my ($udom,$unam,$courseid)=@_;
 2136:     my $hashid="$udom:$unam:$courseid";
 2137:     &devalidate_cache_new('getsection',$hashid);
 2138: }
 2139: 
 2140: sub courseid_to_courseurl {
 2141:     my ($courseid) = @_;
 2142:     #already url style courseid
 2143:     return $courseid if ($courseid =~ m{^/});
 2144: 
 2145:     if (exists($env{'course.'.$courseid.'.num'})) {
 2146: 	my $cnum = $env{'course.'.$courseid.'.num'};
 2147: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 2148: 	return "/$cdom/$cnum";
 2149:     }
 2150: 
 2151:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 2152:     if (exists($courseinfo{'num'})) {
 2153: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 2154:     }
 2155: 
 2156:     return undef;
 2157: }
 2158: 
 2159: sub getsection {
 2160:     my ($udom,$unam,$courseid)=@_;
 2161:     my $cachetime=1800;
 2162: 
 2163:     my $hashid="$udom:$unam:$courseid";
 2164:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 2165:     if (defined($cached)) { return $result; }
 2166: 
 2167:     my %Pending; 
 2168:     my %Expired;
 2169:     #
 2170:     # Each role can either have not started yet (pending), be active, 
 2171:     #    or have expired.
 2172:     #
 2173:     # If there is an active role, we are done.
 2174:     #
 2175:     # If there is more than one role which has not started yet, 
 2176:     #     choose the one which will start sooner
 2177:     # If there is one role which has not started yet, return it.
 2178:     #
 2179:     # If there is more than one expired role, choose the one which ended last.
 2180:     # If there is a role which has expired, return it.
 2181:     #
 2182:     $courseid = &courseid_to_courseurl($courseid);
 2183:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 2184:     foreach my $key (keys(%roleshash)) {
 2185:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 2186:         my $section=$1;
 2187:         if ($key eq $courseid.'_st') { $section=''; }
 2188:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 2189:         my $now=time;
 2190:         if (defined($end) && $end && ($now > $end)) {
 2191:             $Expired{$end}=$section;
 2192:             next;
 2193:         }
 2194:         if (defined($start) && $start && ($now < $start)) {
 2195:             $Pending{$start}=$section;
 2196:             next;
 2197:         }
 2198:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 2199:     }
 2200:     #
 2201:     # Presumedly there will be few matching roles from the above
 2202:     # loop and the sorting time will be negligible.
 2203:     if (scalar(keys(%Pending))) {
 2204:         my ($time) = sort {$a <=> $b} keys(%Pending);
 2205:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 2206:     } 
 2207:     if (scalar(keys(%Expired))) {
 2208:         my @sorted = sort {$a <=> $b} keys(%Expired);
 2209:         my $time = pop(@sorted);
 2210:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 2211:     }
 2212:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 2213: }
 2214: 
 2215: sub save_cache {
 2216:     &purge_remembered();
 2217:     #&Apache::loncommon::validate_page();
 2218:     undef(%env);
 2219:     undef($env_loaded);
 2220: }
 2221: 
 2222: my $to_remember=-1;
 2223: my %remembered;
 2224: my %accessed;
 2225: my $kicks=0;
 2226: my $hits=0;
 2227: sub make_key {
 2228:     my ($name,$id) = @_;
 2229:     if (length($id) > 65 
 2230: 	&& length(&escape($id)) > 200) {
 2231: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 2232:     }
 2233:     return &escape($name.':'.$id);
 2234: }
 2235: 
 2236: sub devalidate_cache_new {
 2237:     my ($name,$id,$debug) = @_;
 2238:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 2239:     $id=&make_key($name,$id);
 2240:     $memcache->delete($id);
 2241:     delete($remembered{$id});
 2242:     delete($accessed{$id});
 2243: }
 2244: 
 2245: sub is_cached_new {
 2246:     my ($name,$id,$debug) = @_;
 2247:     $id=&make_key($name,$id);
 2248:     if (exists($remembered{$id})) {
 2249: 	if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
 2250: 	$accessed{$id}=[&gettimeofday()];
 2251: 	$hits++;
 2252: 	return ($remembered{$id},1);
 2253:     }
 2254:     my $value = $memcache->get($id);
 2255:     if (!(defined($value))) {
 2256: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 2257: 	return (undef,undef);
 2258:     }
 2259:     if ($value eq '__undef__') {
 2260: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 2261: 	$value=undef;
 2262:     }
 2263:     &make_room($id,$value,$debug);
 2264:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 2265:     return ($value,1);
 2266: }
 2267: 
 2268: sub do_cache_new {
 2269:     my ($name,$id,$value,$time,$debug) = @_;
 2270:     $id=&make_key($name,$id);
 2271:     my $setvalue=$value;
 2272:     if (!defined($setvalue)) {
 2273: 	$setvalue='__undef__';
 2274:     }
 2275:     if (!defined($time) ) {
 2276: 	$time=600;
 2277:     }
 2278:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 2279:     my $result = $memcache->set($id,$setvalue,$time);
 2280:     if (! $result) {
 2281: 	&logthis("caching of id -> $id  failed");
 2282: 	$memcache->disconnect_all();
 2283:     }
 2284:     # need to make a copy of $value
 2285:     &make_room($id,$value,$debug);
 2286:     return $value;
 2287: }
 2288: 
 2289: sub make_room {
 2290:     my ($id,$value,$debug)=@_;
 2291: 
 2292:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
 2293:                                     : $value;
 2294:     if ($to_remember<0) { return; }
 2295:     $accessed{$id}=[&gettimeofday()];
 2296:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 2297:     my $to_kick;
 2298:     my $max_time=0;
 2299:     foreach my $other (keys(%accessed)) {
 2300: 	if (&tv_interval($accessed{$other}) > $max_time) {
 2301: 	    $to_kick=$other;
 2302: 	    $max_time=&tv_interval($accessed{$other});
 2303: 	}
 2304:     }
 2305:     delete($remembered{$to_kick});
 2306:     delete($accessed{$to_kick});
 2307:     $kicks++;
 2308:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 2309:     return;
 2310: }
 2311: 
 2312: sub purge_remembered {
 2313:     #&logthis("Tossing ".scalar(keys(%remembered)));
 2314:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 2315:     undef(%remembered);
 2316:     undef(%accessed);
 2317: }
 2318: # ------------------------------------- Read an entry from a user's environment
 2319: 
 2320: sub userenvironment {
 2321:     my ($udom,$unam,@what)=@_;
 2322:     my $items;
 2323:     foreach my $item (@what) {
 2324:         $items.=&escape($item).'&';
 2325:     }
 2326:     $items=~s/\&$//;
 2327:     my %returnhash=();
 2328:     my $uhome = &homeserver($unam,$udom);
 2329:     unless ($uhome eq 'no_host') {
 2330:         my @answer=split(/\&/, 
 2331:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 2332:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 2333:             return %returnhash;
 2334:         }
 2335:         my $i;
 2336:         for ($i=0;$i<=$#what;$i++) {
 2337: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 2338:         }
 2339:     }
 2340:     return %returnhash;
 2341: }
 2342: 
 2343: # ---------------------------------------------------------- Get a studentphoto
 2344: sub studentphoto {
 2345:     my ($udom,$unam,$ext) = @_;
 2346:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2347:     if (defined($env{'request.course.id'})) {
 2348:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 2349:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 2350:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 2351:             } else {
 2352:                 my ($result,$perm_reqd)=
 2353: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2354:                 if ($result eq 'ok') {
 2355:                     if (!($perm_reqd eq 'yes')) {
 2356:                         return(&retrievestudentphoto($udom,$unam,$ext));
 2357:                     }
 2358:                 }
 2359:             }
 2360:         }
 2361:     } else {
 2362:         my ($result,$perm_reqd) = 
 2363: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2364:         if ($result eq 'ok') {
 2365:             if (!($perm_reqd eq 'yes')) {
 2366:                 return(&retrievestudentphoto($udom,$unam,$ext));
 2367:             }
 2368:         }
 2369:     }
 2370:     return '/adm/lonKaputt/lonlogo_broken.gif';
 2371: }
 2372: 
 2373: sub retrievestudentphoto {
 2374:     my ($udom,$unam,$ext,$type) = @_;
 2375:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2376:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 2377:     if ($ret eq 'ok') {
 2378:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 2379:         if ($type eq 'thumbnail') {
 2380:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 2381:         }
 2382:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 2383:         return $tokenurl;
 2384:     } else {
 2385:         if ($type eq 'thumbnail') {
 2386:             return '/adm/lonKaputt/genericstudent_tn.gif';
 2387:         } else { 
 2388:             return '/adm/lonKaputt/lonlogo_broken.gif';
 2389:         }
 2390:     }
 2391: }
 2392: 
 2393: # -------------------------------------------------------------------- New chat
 2394: 
 2395: sub chatsend {
 2396:     my ($newentry,$anon,$group)=@_;
 2397:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 2398:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2399:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 2400:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 2401: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 2402: 		   &escape($newentry)).':'.$group,$chome);
 2403: }
 2404: 
 2405: # ------------------------------------------ Find current version of a resource
 2406: 
 2407: sub getversion {
 2408:     my $fname=&clutter(shift);
 2409:     unless ($fname=~/^\/res\//) { return -1; }
 2410:     return &currentversion(&filelocation('',$fname));
 2411: }
 2412: 
 2413: sub currentversion {
 2414:     my $fname=shift;
 2415:     my $author=$fname;
 2416:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2417:     my ($udom,$uname)=split(/\//,$author);
 2418:     my $home=&homeserver($uname,$udom);
 2419:     if ($home eq 'no_host') { 
 2420:         return -1; 
 2421:     }
 2422:     my $answer=&reply("currentversion:$fname",$home);
 2423:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 2424: 	return -1;
 2425:     }
 2426:     return $answer;
 2427: }
 2428: 
 2429: #
 2430: # Return special version number of resource if set by override, empty otherwise
 2431: #
 2432: sub usedversion {
 2433:     my $fname=shift;
 2434:     unless ($fname) { $fname=$env{'request.uri'}; }
 2435:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 2436:     if ($urlversion) { return $urlversion; }
 2437:     return '';
 2438: }
 2439: 
 2440: # ----------------------------- Subscribe to a resource, return URL if possible
 2441: 
 2442: sub subscribe {
 2443:     my $fname=shift;
 2444:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 2445:     $fname=~s/[\n\r]//g;
 2446:     my $author=$fname;
 2447:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2448:     my ($udom,$uname)=split(/\//,$author);
 2449:     my $home=homeserver($uname,$udom);
 2450:     if ($home eq 'no_host') {
 2451:         return 'not_found';
 2452:     }
 2453:     my $answer=reply("sub:$fname",$home);
 2454:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 2455: 	$answer.=' by '.$home;
 2456:     }
 2457:     return $answer;
 2458: }
 2459:     
 2460: # -------------------------------------------------------------- Replicate file
 2461: 
 2462: sub repcopy {
 2463:     my $filename=shift;
 2464:     $filename=~s/\/+/\//g;
 2465:     my $londocroot = $perlvar{'lonDocRoot'};
 2466:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 2467:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
 2468:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 2469: 	$filename=~m{^/*(uploaded|editupload)/}) {
 2470: 	return &repcopy_userfile($filename);
 2471:     }
 2472:     $filename=~s/[\n\r]//g;
 2473:     my $transname="$filename.in.transfer";
 2474: # FIXME: this should flock
 2475:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 2476:     my $remoteurl=subscribe($filename);
 2477:     if ($remoteurl =~ /^con_lost by/) {
 2478: 	   &logthis("Subscribe returned $remoteurl: $filename");
 2479:            return 'unavailable';
 2480:     } elsif ($remoteurl eq 'not_found') {
 2481: 	   #&logthis("Subscribe returned not_found: $filename");
 2482: 	   return 'not_found';
 2483:     } elsif ($remoteurl =~ /^rejected by/) {
 2484: 	   &logthis("Subscribe returned $remoteurl: $filename");
 2485:            return 'forbidden';
 2486:     } elsif ($remoteurl eq 'directory') {
 2487:            return 'ok';
 2488:     } else {
 2489:         my $author=$filename;
 2490:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2491:         my ($udom,$uname)=split(/\//,$author);
 2492:         my $home=homeserver($uname,$udom);
 2493:         unless ($home eq $perlvar{'lonHostID'}) {
 2494:            my @parts=split(/\//,$filename);
 2495:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 2496:            if ($path ne "$londocroot/res") {
 2497:                &logthis("Malconfiguration for replication: $filename");
 2498: 	       return 'bad_request';
 2499:            }
 2500:            my $count;
 2501:            for ($count=5;$count<$#parts;$count++) {
 2502:                $path.="/$parts[$count]";
 2503:                if ((-e $path)!=1) {
 2504: 		   mkdir($path,0777);
 2505:                }
 2506:            }
 2507:            my $ua=new LWP::UserAgent;
 2508:            my $request=new HTTP::Request('GET',"$remoteurl");
 2509:            my $response=$ua->request($request,$transname);
 2510:            if ($response->is_error()) {
 2511: 	       unlink($transname);
 2512:                my $message=$response->status_line;
 2513:                &logthis("<font color=\"blue\">WARNING:"
 2514:                        ." LWP get: $message: $filename</font>");
 2515:                return 'unavailable';
 2516:            } else {
 2517: 	       if ($remoteurl!~/\.meta$/) {
 2518:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 2519:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 2520:                   if ($mresponse->is_error()) {
 2521: 		      unlink($filename.'.meta');
 2522:                       &logthis(
 2523:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 2524:                   }
 2525: 	       }
 2526:                rename($transname,$filename);
 2527:                return 'ok';
 2528:            }
 2529:        }
 2530:     }
 2531: }
 2532: 
 2533: # ------------------------------------------------ Get server side include body
 2534: sub ssi_body {
 2535:     my ($filelink,%form)=@_;
 2536:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 2537:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 2538:     }
 2539:     my $output='';
 2540:     my $response;
 2541:     if ($filelink=~/^https?\:/) {
 2542:        ($output,$response)=&externalssi($filelink);
 2543:     } else {
 2544:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 2545:        $filelink .= 'inhibitmenu=yes';
 2546:        ($output,$response)=&ssi($filelink,%form);
 2547:     }
 2548:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 2549:     $output=~s/^.*?\<body[^\>]*\>//si;
 2550:     $output=~s/\<\/body\s*\>.*?$//si;
 2551:     if (wantarray) {
 2552:         return ($output, $response);
 2553:     } else {
 2554:         return $output;
 2555:     }
 2556: }
 2557: 
 2558: # --------------------------------------------------------- Server Side Include
 2559: 
 2560: sub absolute_url {
 2561:     my ($host_name) = @_;
 2562:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 2563:     if ($host_name eq '') {
 2564: 	$host_name = $ENV{'SERVER_NAME'};
 2565:     }
 2566:     return $protocol.$host_name;
 2567: }
 2568: 
 2569: #
 2570: #   Server side include.
 2571: # Parameters:
 2572: #  fn     Possibly encrypted resource name/id.
 2573: #  form   Hash that describes how the rendering should be done
 2574: #         and other things.
 2575: # Returns:
 2576: #   Scalar context: The content of the response.
 2577: #   Array context:  2 element list of the content and the full response object.
 2578: #     
 2579: sub ssi {
 2580: 
 2581:     my ($fn,%form)=@_;
 2582:     my $ua=new LWP::UserAgent;
 2583:     my $request;
 2584: 
 2585:     $form{'no_update_last_known'}=1;
 2586:     &Apache::lonenc::check_encrypt(\$fn);
 2587:     if (%form) {
 2588:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 2589:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
 2590:     } else {
 2591:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 2592:     }
 2593: 
 2594:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 2595:     my $response= $ua->request($request);
 2596:     my $content = $response->content;
 2597: 
 2598: 
 2599:     if (wantarray) {
 2600: 	return ($content, $response);
 2601:     } else {
 2602: 	return $content;
 2603:     }
 2604: }
 2605: 
 2606: sub externalssi {
 2607:     my ($url)=@_;
 2608:     my $ua=new LWP::UserAgent;
 2609:     my $request=new HTTP::Request('GET',$url);
 2610:     my $response=$ua->request($request);
 2611:     if (wantarray) {
 2612:         return ($response->content, $response);
 2613:     } else {
 2614:         return $response->content;
 2615:     }
 2616: }
 2617: 
 2618: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 2619: 
 2620: sub allowuploaded {
 2621:     my ($srcurl,$url)=@_;
 2622:     $url=&clutter(&declutter($url));
 2623:     my $dir=$url;
 2624:     $dir=~s/\/[^\/]+$//;
 2625:     my %httpref=();
 2626:     my $httpurl=&hreflocation('',$url);
 2627:     $httpref{'httpref.'.$httpurl}=$srcurl;
 2628:     &Apache::lonnet::appenv(\%httpref);
 2629: }
 2630: 
 2631: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 2632: # input: action, courseID, current domain, intended
 2633: #        path to file, source of file, instruction to parse file for objects,
 2634: #        ref to hash for embedded objects,
 2635: #        ref to hash for codebase of java objects.
 2636: #        reference to scalar to accommodate mime type determined
 2637: #          from File::MMagic if $parser = parse.
 2638: #
 2639: # output: url to file (if action was uploaddoc), 
 2640: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 2641: #
 2642: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 2643: # course.
 2644: #
 2645: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2646: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 2647: #          course's home server.
 2648: #
 2649: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 2650: #          be copied from $source (current location) to 
 2651: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2652: #         and will then be copied to
 2653: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 2654: #         course's home server.
 2655: #
 2656: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2657: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 2658: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2659: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 2660: #         in course's home server.
 2661: #
 2662: 
 2663: sub process_coursefile {
 2664:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 2665:         $mimetype)=@_;
 2666:     my $fetchresult;
 2667:     my $home=&homeserver($docuname,$docudom);
 2668:     if ($action eq 'propagate') {
 2669:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2670: 			     $home);
 2671:     } else {
 2672:         my $fpath = '';
 2673:         my $fname = $file;
 2674:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 2675:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 2676:         my $filepath = &build_filepath($fpath);
 2677:         if ($action eq 'copy') {
 2678:             if ($source eq '') {
 2679:                 $fetchresult = 'no source file';
 2680:                 return $fetchresult;
 2681:             } else {
 2682:                 my $destination = $filepath.'/'.$fname;
 2683:                 rename($source,$destination);
 2684:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2685:                                  $home);
 2686:             }
 2687:         } elsif ($action eq 'uploaddoc') {
 2688:             open(my $fh,'>'.$filepath.'/'.$fname);
 2689:             print $fh $env{'form.'.$source};
 2690:             close($fh);
 2691:             if ($parser eq 'parse') {
 2692:                 my $mm = new File::MMagic;
 2693:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 2694:                 if ($type eq 'text/html') {
 2695:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 2696:                     unless ($parse_result eq 'ok') {
 2697:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 2698:                     }
 2699:                 }
 2700:                 if (ref($mimetype)) {
 2701:                     $$mimetype = $type;
 2702:                 } 
 2703:             }
 2704:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2705:                                  $home);
 2706:             if ($fetchresult eq 'ok') {
 2707:                 return '/uploaded/'.$fpath.'/'.$fname;
 2708:             } else {
 2709:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2710:                         ' to host '.$home.': '.$fetchresult);
 2711:                 return '/adm/notfound.html';
 2712:             }
 2713:         }
 2714:     }
 2715:     unless ( $fetchresult eq 'ok') {
 2716:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2717:              ' to host '.$home.': '.$fetchresult);
 2718:     }
 2719:     return $fetchresult;
 2720: }
 2721: 
 2722: sub build_filepath {
 2723:     my ($fpath) = @_;
 2724:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 2725:     unless ($fpath eq '') {
 2726:         my @parts=split('/',$fpath);
 2727:         foreach my $part (@parts) {
 2728:             $filepath.= '/'.$part;
 2729:             if ((-e $filepath)!=1) {
 2730:                 mkdir($filepath,0777);
 2731:             }
 2732:         }
 2733:     }
 2734:     return $filepath;
 2735: }
 2736: 
 2737: sub store_edited_file {
 2738:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 2739:     my $file = $primary_url;
 2740:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 2741:     my $fpath = '';
 2742:     my $fname = $file;
 2743:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 2744:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 2745:     my $filepath = &build_filepath($fpath);
 2746:     open(my $fh,'>'.$filepath.'/'.$fname);
 2747:     print $fh $content;
 2748:     close($fh);
 2749:     my $home=&homeserver($docuname,$docudom);
 2750:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2751: 			  $home);
 2752:     if ($$fetchresult eq 'ok') {
 2753:         return '/uploaded/'.$fpath.'/'.$fname;
 2754:     } else {
 2755:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2756: 		 ' to host '.$home.': '.$$fetchresult);
 2757:         return '/adm/notfound.html';
 2758:     }
 2759: }
 2760: 
 2761: sub clean_filename {
 2762:     my ($fname,$args)=@_;
 2763: # Replace Windows backslashes by forward slashes
 2764:     $fname=~s/\\/\//g;
 2765:     if (!$args->{'keep_path'}) {
 2766:         # Get rid of everything but the actual filename
 2767: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 2768:     }
 2769: # Replace spaces by underscores
 2770:     $fname=~s/\s+/\_/g;
 2771: # Replace all other weird characters by nothing
 2772:     $fname=~s{[^/\w\.\-]}{}g;
 2773: # Replace all .\d. sequences with _\d. so they no longer look like version
 2774: # numbers
 2775:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 2776:     return $fname;
 2777: }
 2778: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 2779: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 2780: # image with the same aspect ratio as the original, but with dimensions which do 
 2781: # not exceed $resizewidth and $resizeheight.
 2782:  
 2783: sub resizeImage {
 2784:     my ($img_path,$resizewidth,$resizeheight) = @_;
 2785:     my $ima = Image::Magick->new;
 2786:     my $resized;
 2787:     if (-e $img_path) {
 2788:         $ima->Read($img_path);
 2789:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 2790:             my $width = $ima->Get('width');
 2791:             my $height = $ima->Get('height');
 2792:             if ($width > $resizewidth) {
 2793: 	        my $factor = $width/$resizewidth;
 2794:                 my $newheight = $height/$factor;
 2795:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 2796:                 $resized = 1;
 2797:             }
 2798:         }
 2799:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 2800:             my $width = $ima->Get('width');
 2801:             my $height = $ima->Get('height');
 2802:             if ($height > $resizeheight) {
 2803:                 my $factor = $height/$resizeheight;
 2804:                 my $newwidth = $width/$factor;
 2805:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 2806:                 $resized = 1;
 2807:             }
 2808:         }
 2809:         if ($resized) {
 2810:             $ima->Write($img_path);
 2811:         }
 2812:     }
 2813:     return;
 2814: }
 2815: 
 2816: # --------------- Take an uploaded file and put it into the userfiles directory
 2817: # input: $formname - the contents of the file are in $env{"form.$formname"}
 2818: #                    the desired filename is in $env{"form.$formname.filename"}
 2819: #        $context - possible values: coursedoc, existingfile, overwrite, 
 2820: #                                    canceloverwrite, or ''. 
 2821: #                   if 'coursedoc': upload to the current course
 2822: #                   if 'existingfile': write file to tmp/overwrites directory 
 2823: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 2824: #                   $context is passed as argument to &finishuserfileupload
 2825: #        $subdir - directory in userfile to store the file into
 2826: #        $parser - instruction to parse file for objects ($parser = parse)    
 2827: #        $allfiles - reference to hash for embedded objects
 2828: #        $codebase - reference to hash for codebase of java objects
 2829: #        $desuname - username for permanent storage of uploaded file
 2830: #        $dsetudom - domain for permanaent storage of uploaded file
 2831: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 2832: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 2833: #        $resizewidth - width (pixels) to which to resize uploaded image
 2834: #        $resizeheight - height (pixels) to which to resize uploaded image
 2835: #        $mimetype - reference to scalar to accommodate mime type determined
 2836: #                    from File::MMagic.
 2837: # 
 2838: # output: url of file in userspace, or error: <message> 
 2839: #             or /adm/notfound.html if failure to upload occurse
 2840: 
 2841: sub userfileupload {
 2842:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 2843:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 2844:     if (!defined($subdir)) { $subdir='unknown'; }
 2845:     my $fname=$env{'form.'.$formname.'.filename'};
 2846:     $fname=&clean_filename($fname);
 2847:     # See if there is anything left
 2848:     unless ($fname) { return 'error: no uploaded file'; }
 2849:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 2850:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 2851:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 2852:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 2853:         my $now = time;
 2854:         my $filepath;
 2855:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 2856:              $filepath = 'tmp/helprequests/'.$now;
 2857:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 2858:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 2859:                          '_'.$env{'user.domain'}.'/pending';
 2860:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 2861:             my ($docuname,$docudom);
 2862:             if ($destudom) {
 2863:                 $docudom = $destudom;
 2864:             } else {
 2865:                 $docudom = $env{'user.domain'};
 2866:             }
 2867:             if ($destuname) {
 2868:                 $docuname = $destuname;
 2869:             } else {
 2870:                 $docuname = $env{'user.name'};
 2871:             }
 2872:             if (exists($env{'form.group'})) {
 2873:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2874:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2875:             }
 2876:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 2877:             if ($context eq 'canceloverwrite') {
 2878:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 2879:                 if (-e  $tempfile) {
 2880:                     my @info = stat($tempfile);
 2881:                     if ($info[9] eq $env{'form.timestamp'}) {
 2882:                         unlink($tempfile);
 2883:                     }
 2884:                 }
 2885:                 return;
 2886:             }
 2887:         }
 2888:         # Create the directory if not present
 2889:         my @parts=split(/\//,$filepath);
 2890:         my $fullpath = $perlvar{'lonDaemons'};
 2891:         for (my $i=0;$i<@parts;$i++) {
 2892:             $fullpath .= '/'.$parts[$i];
 2893:             if ((-e $fullpath)!=1) {
 2894:                 mkdir($fullpath,0777);
 2895:             }
 2896:         }
 2897:         open(my $fh,'>'.$fullpath.'/'.$fname);
 2898:         print $fh $env{'form.'.$formname};
 2899:         close($fh);
 2900:         if ($context eq 'existingfile') {
 2901:             my @info = stat($fullpath.'/'.$fname);
 2902:             return ($fullpath.'/'.$fname,$info[9]);
 2903:         } else {
 2904:             return $fullpath.'/'.$fname;
 2905:         }
 2906:     }
 2907:     if ($subdir eq 'scantron') {
 2908:         $fname = 'scantron_orig_'.$fname;
 2909:     } else {
 2910:         $fname="$subdir/$fname";
 2911:     }
 2912:     if ($context eq 'coursedoc') {
 2913: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2914: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2915:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 2916:             return &finishuserfileupload($docuname,$docudom,
 2917: 					 $formname,$fname,$parser,$allfiles,
 2918: 					 $codebase,$thumbwidth,$thumbheight,
 2919:                                          $resizewidth,$resizeheight,$context,$mimetype);
 2920:         } else {
 2921:             $fname=$env{'form.folder'}.'/'.$fname;
 2922:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 2923: 				       $fname,$formname,$parser,
 2924: 				       $allfiles,$codebase,$mimetype);
 2925:         }
 2926:     } elsif (defined($destuname)) {
 2927:         my $docuname=$destuname;
 2928:         my $docudom=$destudom;
 2929: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 2930: 				     $parser,$allfiles,$codebase,
 2931:                                      $thumbwidth,$thumbheight,
 2932:                                      $resizewidth,$resizeheight,$context,$mimetype);
 2933:     } else {
 2934:         my $docuname=$env{'user.name'};
 2935:         my $docudom=$env{'user.domain'};
 2936:         if (exists($env{'form.group'})) {
 2937:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2938:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2939:         }
 2940: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 2941: 				     $parser,$allfiles,$codebase,
 2942:                                      $thumbwidth,$thumbheight,
 2943:                                      $resizewidth,$resizeheight,$context,$mimetype);
 2944:     }
 2945: }
 2946: 
 2947: sub finishuserfileupload {
 2948:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 2949:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 2950:     my $path=$docudom.'/'.$docuname.'/';
 2951:     my $filepath=$perlvar{'lonDocRoot'};
 2952:   
 2953:     my ($fnamepath,$file,$fetchthumb);
 2954:     $file=$fname;
 2955:     if ($fname=~m|/|) {
 2956:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 2957: 	$path.=$fnamepath.'/';
 2958:     }
 2959:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 2960:     my $count;
 2961:     for ($count=4;$count<=$#parts;$count++) {
 2962:         $filepath.="/$parts[$count]";
 2963:         if ((-e $filepath)!=1) {
 2964: 	    mkdir($filepath,0777);
 2965:         }
 2966:     }
 2967: 
 2968: # Save the file
 2969:     {
 2970: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 2971: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 2972: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 2973: 	    return '/adm/notfound.html';
 2974: 	}
 2975:         if ($context eq 'overwrite') {
 2976:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 2977:             my $target = $filepath.'/'.$file;
 2978:             if (-e $source) {
 2979:                 my @info = stat($source);
 2980:                 if ($info[9] eq $env{'form.timestamp'}) {   
 2981:                     unless (&File::Copy::move($source,$target)) {
 2982:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 2983:                         return "Moving from $source failed";
 2984:                     }
 2985:                 } else {
 2986:                     return "Temporary file: $source had unexpected date/time for last modification";
 2987:                 }
 2988:             } else {
 2989:                 return "Temporary file: $source missing";
 2990:             }
 2991:         } elsif (!print FH ($env{'form.'.$formname})) {
 2992: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 2993: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 2994: 	    return '/adm/notfound.html';
 2995: 	}
 2996: 	close(FH);
 2997:         if ($resizewidth && $resizeheight) {
 2998:             my $mm = new File::MMagic;
 2999:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 3000:             if ($mime_type =~ m{^image/}) {
 3001: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 3002:             }  
 3003: 	}
 3004:     }
 3005:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 3006:         if (ref($mimetype)) {
 3007:             if ($$mimetype eq '') {
 3008:                 my $mm = new File::MMagic;
 3009:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 3010:                 $$mimetype = $type;
 3011:             }
 3012:         }
 3013:     }
 3014:     if ($parser eq 'parse') {
 3015:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 3016:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 3017:                                                        $allfiles,$codebase);
 3018:             unless ($parse_result eq 'ok') {
 3019:                 &logthis('Failed to parse '.$filepath.$file.
 3020: 	   	         ' for embedded media: '.$parse_result); 
 3021:             }
 3022:         }
 3023:     }
 3024:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 3025:         my $input = $filepath.'/'.$file;
 3026:         my $output = $filepath.'/'.'tn-'.$file;
 3027:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 3028:         system("convert -sample $thumbsize $input $output");
 3029:         if (-e $filepath.'/'.'tn-'.$file) {
 3030:             $fetchthumb  = 1; 
 3031:         }
 3032:     }
 3033:  
 3034: # Notify homeserver to grep it
 3035: #
 3036:     my $docuhome=&homeserver($docuname,$docudom);	
 3037:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 3038:     if ($fetchresult eq 'ok') {
 3039:         if ($fetchthumb) {
 3040:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 3041:             if ($thumbresult ne 'ok') {
 3042:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 3043:                          $docuhome.': '.$thumbresult);
 3044:             }
 3045:         }
 3046: #
 3047: # Return the URL to it
 3048:         return '/uploaded/'.$path.$file;
 3049:     } else {
 3050:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 3051: 		 ': '.$fetchresult);
 3052:         return '/adm/notfound.html';
 3053:     }
 3054: }
 3055: 
 3056: sub extract_embedded_items {
 3057:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 3058:     my @state = ();
 3059:     my (%lastids,%related,%shockwave,%flashvars);
 3060:     my %javafiles = (
 3061:                       codebase => '',
 3062:                       code => '',
 3063:                       archive => ''
 3064:                     );
 3065:     my %mediafiles = (
 3066:                       src => '',
 3067:                       movie => '',
 3068:                      );
 3069:     my $p;
 3070:     if ($content) {
 3071:         $p = HTML::LCParser->new($content);
 3072:     } else {
 3073:         $p = HTML::LCParser->new($fullpath);
 3074:     }
 3075:     while (my $t=$p->get_token()) {
 3076: 	if ($t->[0] eq 'S') {
 3077: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 3078: 	    push(@state, $tagname);
 3079:             if (lc($tagname) eq 'allow') {
 3080:                 &add_filetype($allfiles,$attr->{'src'},'src');
 3081:             }
 3082: 	    if (lc($tagname) eq 'img') {
 3083: 		&add_filetype($allfiles,$attr->{'src'},'src');
 3084: 	    }
 3085: 	    if (lc($tagname) eq 'a') {
 3086: 		&add_filetype($allfiles,$attr->{'href'},'href');
 3087: 	    }
 3088:             if (lc($tagname) eq 'script') {
 3089:                 my $src;
 3090:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 3091:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 3092:                 } else {
 3093:                     if ($attr->{'src'} ne '') {
 3094:                         $src = $attr->{'src'};
 3095:                         &add_filetype($allfiles,$src,'src');
 3096:                     }
 3097:                 }
 3098:                 my $text = $p->get_trimmed_text();
 3099:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 3100:                     my @swfargs = split(/,/,$1);
 3101:                     foreach my $item (@swfargs) {
 3102:                         $item =~ s/["']//g;
 3103:                         $item =~ s/^\s+//;
 3104:                         $item =~ s/\s+$//;
 3105:                     }
 3106:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 3107:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 3108:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 3109:                         } else {
 3110:                             $related{$swfargs[0]} = [$swfargs[2]];
 3111:                         }
 3112:                     }
 3113:                 }
 3114:             }
 3115:             if (lc($tagname) eq 'link') {
 3116:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 3117:                     &add_filetype($allfiles,$attr->{'href'},'href');
 3118:                 }
 3119:             }
 3120: 	    if (lc($tagname) eq 'object' ||
 3121: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 3122: 		foreach my $item (keys(%javafiles)) {
 3123: 		    $javafiles{$item} = '';
 3124: 		}
 3125:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 3126:                     $lastids{lc($tagname)} = $attr->{'id'};
 3127:                 }
 3128: 	    }
 3129: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 3130: 		my $name = lc($attr->{'name'});
 3131: 		foreach my $item (keys(%javafiles)) {
 3132: 		    if ($name eq $item) {
 3133: 			$javafiles{$item} = $attr->{'value'};
 3134: 			last;
 3135: 		    }
 3136: 		}
 3137:                 my $pathfrom;
 3138: 		foreach my $item (keys(%mediafiles)) {
 3139: 		    if ($name eq $item) {
 3140:                         $pathfrom = $attr->{'value'};
 3141:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 3142: 			&add_filetype($allfiles,$pathfrom,$name);
 3143: 			last;
 3144: 		    }
 3145: 		}
 3146:                 if ($name eq 'flashvars') {
 3147:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 3148:                 }
 3149:                 if ($pathfrom ne '') {
 3150:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 3151:                                          $pathfrom);
 3152:                 }
 3153: 	    }
 3154: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 3155: 		foreach my $item (keys(%javafiles)) {
 3156: 		    if ($attr->{$item}) {
 3157: 			$javafiles{$item} = $attr->{$item};
 3158: 			last;
 3159: 		    }
 3160: 		}
 3161: 		foreach my $item (keys(%mediafiles)) {
 3162: 		    if ($attr->{$item}) {
 3163: 			&add_filetype($allfiles,$attr->{$item},$item);
 3164: 			last;
 3165: 		    }
 3166: 		}
 3167:                 if (lc($tagname) eq 'embed') {
 3168:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 3169:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 3170:                                              $attr->{'src'});
 3171:                     }
 3172:                 }
 3173: 	    }
 3174:             if ($t->[4] =~ m{/>$}) {
 3175:                 pop(@state);  
 3176:             }
 3177: 	} elsif ($t->[0] eq 'E') {
 3178: 	    my ($tagname) = ($t->[1]);
 3179: 	    if ($javafiles{'codebase'} ne '') {
 3180: 		$javafiles{'codebase'} .= '/';
 3181: 	    }  
 3182: 	    if (lc($tagname) eq 'applet' ||
 3183: 		lc($tagname) eq 'object' ||
 3184: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 3185: 		) {
 3186: 		foreach my $item (keys(%javafiles)) {
 3187: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 3188: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 3189: 			&add_filetype($allfiles,$file,$item);
 3190: 		    }
 3191: 		}
 3192: 	    } 
 3193: 	    pop @state;
 3194: 	}
 3195:     }
 3196:     foreach my $id (sort(keys(%flashvars))) {
 3197:         if ($shockwave{$id} ne '') {
 3198:             my @pairs = split(/\&/,$flashvars{$id});
 3199:             foreach my $pair (@pairs) {
 3200:                 my ($key,$value) = split(/\=/,$pair);
 3201:                 if ($key eq 'thumb') {
 3202:                     &add_filetype($allfiles,$value,$key);
 3203:                 } elsif ($key eq 'content') {
 3204:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 3205:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 3206:                     if ($ext ne '') {
 3207:                         &add_filetype($allfiles,$path.$value,$ext);
 3208:                     }
 3209:                 }
 3210:             }
 3211:         }
 3212:     }
 3213:     return 'ok';
 3214: }
 3215: 
 3216: sub add_filetype {
 3217:     my ($allfiles,$file,$type)=@_;
 3218:     if (exists($allfiles->{$file})) {
 3219: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 3220: 	    push(@{$allfiles->{$file}}, &escape($type));
 3221: 	}
 3222:     } else {
 3223: 	@{$allfiles->{$file}} = (&escape($type));
 3224:     }
 3225: }
 3226: 
 3227: sub embedded_dependency {
 3228:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 3229:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 3230:         if (($identifier ne '') &&
 3231:             (ref($related->{$identifier}) eq 'ARRAY') &&
 3232:             ($pathfrom ne '')) {
 3233:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 3234:             foreach my $dep (@{$related->{$identifier}}) {
 3235:                 &add_filetype($allfiles,$path.$dep,'object');
 3236:             }
 3237:         }
 3238:     }
 3239:     return;
 3240: }
 3241: 
 3242: sub removeuploadedurl {
 3243:     my ($url)=@_;	
 3244:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 3245:     return &removeuserfile($uname,$udom,$fname);
 3246: }
 3247: 
 3248: sub removeuserfile {
 3249:     my ($docuname,$docudom,$fname)=@_;
 3250:     my $home=&homeserver($docuname,$docudom);    
 3251:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 3252:     if ($result eq 'ok') {	
 3253:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 3254:             my $metafile = $fname.'.meta';
 3255:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 3256: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 3257:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 3258:             my $sqlresult = 
 3259:                 &update_portfolio_table($docuname,$docudom,$file,
 3260:                                         'portfolio_metadata',$group,
 3261:                                         'delete');
 3262:         }
 3263:     }
 3264:     return $result;
 3265: }
 3266: 
 3267: sub mkdiruserfile {
 3268:     my ($docuname,$docudom,$dir)=@_;
 3269:     my $home=&homeserver($docuname,$docudom);
 3270:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 3271: }
 3272: 
 3273: sub renameuserfile {
 3274:     my ($docuname,$docudom,$old,$new)=@_;
 3275:     my $home=&homeserver($docuname,$docudom);
 3276:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 3277:                         &escape("$old").':'.&escape("$new"),$home);
 3278:     if ($result eq 'ok') {
 3279:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 3280:             my $oldmeta = $old.'.meta';
 3281:             my $newmeta = $new.'.meta';
 3282:             my $metaresult = 
 3283:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 3284: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 3285:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 3286:             my $sqlresult = 
 3287:                 &update_portfolio_table($docuname,$docudom,$file,
 3288:                                         'portfolio_metadata',$group,
 3289:                                         'delete');
 3290:         }
 3291:     }
 3292:     return $result;
 3293: }
 3294: 
 3295: # ------------------------------------------------------------------------- Log
 3296: 
 3297: sub log {
 3298:     my ($dom,$nam,$hom,$what)=@_;
 3299:     return critical("log:$dom:$nam:$what",$hom);
 3300: }
 3301: 
 3302: # ------------------------------------------------------------------ Course Log
 3303: #
 3304: # This routine flushes several buffers of non-mission-critical nature
 3305: #
 3306: 
 3307: sub flushcourselogs {
 3308:     &logthis('Flushing log buffers');
 3309: #
 3310: # course logs
 3311: # This is a log of all transactions in a course, which can be used
 3312: # for data mining purposes
 3313: #
 3314: # It also collects the courseid database, which lists last transaction
 3315: # times and course titles for all courseids
 3316: #
 3317:     my %courseidbuffer=();
 3318:     foreach my $crsid (keys(%courselogs)) {
 3319:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 3320: 		          &escape($courselogs{$crsid}),
 3321: 		          $coursehombuf{$crsid}) eq 'ok') {
 3322: 	    delete $courselogs{$crsid};
 3323:         } else {
 3324:             &logthis('Failed to flush log buffer for '.$crsid);
 3325:             if (length($courselogs{$crsid})>40000) {
 3326:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 3327:                         " exceeded maximum size, deleting.</font>");
 3328:                delete $courselogs{$crsid};
 3329:             }
 3330:         }
 3331:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 3332:             'description' => $coursedescrbuf{$crsid},
 3333:             'inst_code'    => $courseinstcodebuf{$crsid},
 3334:             'type'        => $coursetypebuf{$crsid},
 3335:             'owner'       => $courseownerbuf{$crsid},
 3336:         };
 3337:     }
 3338: #
 3339: # Write course id database (reverse lookup) to homeserver of courses 
 3340: # Is used in pickcourse
 3341: #
 3342:     foreach my $crs_home (keys(%courseidbuffer)) {
 3343:         my $response = &courseidput(&host_domain($crs_home),
 3344:                                     $courseidbuffer{$crs_home},
 3345:                                     $crs_home,'timeonly');
 3346:     }
 3347: #
 3348: # File accesses
 3349: # Writes to the dynamic metadata of resources to get hit counts, etc.
 3350: #
 3351:     foreach my $entry (keys(%accesshash)) {
 3352:         if ($entry =~ /___count$/) {
 3353:             my ($dom,$name);
 3354:             ($dom,$name,undef)=
 3355: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 3356:             if (! defined($dom) || $dom eq '' || 
 3357:                 ! defined($name) || $name eq '') {
 3358:                 my $cid = $env{'request.course.id'};
 3359:                 $dom  = $env{'request.'.$cid.'.domain'};
 3360:                 $name = $env{'request.'.$cid.'.num'};
 3361:             }
 3362:             my $value = $accesshash{$entry};
 3363:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 3364:             my %temphash=($url => $value);
 3365:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 3366:             if ($result eq 'ok') {
 3367:                 delete $accesshash{$entry};
 3368:             }
 3369:         } else {
 3370:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 3371:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 3372:             my %temphash=($entry => $accesshash{$entry});
 3373:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 3374:                 delete $accesshash{$entry};
 3375:             }
 3376:         }
 3377:     }
 3378: #
 3379: # Roles
 3380: # Reverse lookup of user roles for course faculty/staff and co-authorship
 3381: #
 3382:     foreach my $entry (keys(%userrolehash)) {
 3383:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 3384: 	    split(/\:/,$entry);
 3385:         if (&Apache::lonnet::put('nohist_userroles',
 3386:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 3387:                 $rudom,$runame) eq 'ok') {
 3388: 	    delete $userrolehash{$entry};
 3389:         }
 3390:     }
 3391: #
 3392: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 3393: #
 3394:     my %domrolebuffer = ();
 3395:     foreach my $entry (keys(%domainrolehash)) {
 3396:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 3397:         if ($domrolebuffer{$rudom}) {
 3398:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 3399:                       '='.&escape($domainrolehash{$entry});
 3400:         } else {
 3401:             $domrolebuffer{$rudom}.=&escape($entry).
 3402:                       '='.&escape($domainrolehash{$entry});
 3403:         }
 3404:         delete $domainrolehash{$entry};
 3405:     }
 3406:     foreach my $dom (keys(%domrolebuffer)) {
 3407: 	my %servers = &get_servers($dom,'library');
 3408: 	foreach my $tryserver (keys(%servers)) {
 3409: 	    unless (&reply('domroleput:'.$dom.':'.
 3410: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 3411: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 3412: 	    }
 3413:         }
 3414:     }
 3415:     $dumpcount++;
 3416: }
 3417: 
 3418: sub courselog {
 3419:     my $what=shift;
 3420:     $what=time.':'.$what;
 3421:     unless ($env{'request.course.id'}) { return ''; }
 3422:     $coursedombuf{$env{'request.course.id'}}=
 3423:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 3424:     $coursenumbuf{$env{'request.course.id'}}=
 3425:        $env{'course.'.$env{'request.course.id'}.'.num'};
 3426:     $coursehombuf{$env{'request.course.id'}}=
 3427:        $env{'course.'.$env{'request.course.id'}.'.home'};
 3428:     $coursedescrbuf{$env{'request.course.id'}}=
 3429:        $env{'course.'.$env{'request.course.id'}.'.description'};
 3430:     $courseinstcodebuf{$env{'request.course.id'}}=
 3431:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 3432:     $courseownerbuf{$env{'request.course.id'}}=
 3433:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 3434:     $coursetypebuf{$env{'request.course.id'}}=
 3435:        $env{'course.'.$env{'request.course.id'}.'.type'};
 3436:     if (defined $courselogs{$env{'request.course.id'}}) {
 3437: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 3438:     } else {
 3439: 	$courselogs{$env{'request.course.id'}}.=$what;
 3440:     }
 3441:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 3442: 	&flushcourselogs();
 3443:     }
 3444: }
 3445: 
 3446: sub courseacclog {
 3447:     my $fnsymb=shift;
 3448:     unless ($env{'request.course.id'}) { return ''; }
 3449:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 3450:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 3451:         $what.=':POST';
 3452:         # FIXME: Probably ought to escape things....
 3453: 	foreach my $key (keys(%env)) {
 3454:             if ($key=~/^form\.(.*)/) {
 3455:                 my $formitem = $1;
 3456:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 3457:                     $what.=':'.$formitem.'='.$env{$key};
 3458:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 3459:                     $what.=':'.$formitem.'='.$env{$key};
 3460:                 }
 3461:             }
 3462:         }
 3463:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 3464:         # FIXME: We should not be depending on a form parameter that someone
 3465:         # editing lonsearchcat.pm might change in the future.
 3466:         if ($env{'form.phase'} eq 'course_search') {
 3467:             $what.= ':POST';
 3468:             # FIXME: Probably ought to escape things....
 3469:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 3470:                                  'crsdiscuss') {
 3471:                 $what.=':'.$element.'='.$env{'form.'.$element};
 3472:             }
 3473:         }
 3474:     }
 3475:     &courselog($what);
 3476: }
 3477: 
 3478: sub countacc {
 3479:     my $url=&declutter(shift);
 3480:     return if (! defined($url) || $url eq '');
 3481:     unless ($env{'request.course.id'}) { return ''; }
 3482: #
 3483: # Mark that this url was used in this course
 3484: #
 3485:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 3486: #
 3487: # Increase the access count for this resource in this child process
 3488: #
 3489:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 3490:     $accesshash{$key}++;
 3491: }
 3492: 
 3493: sub linklog {
 3494:     my ($from,$to)=@_;
 3495:     $from=&declutter($from);
 3496:     $to=&declutter($to);
 3497:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 3498:     $accesshash{$to.'___'.$from.'___goto'}=1;
 3499: }
 3500: 
 3501: sub statslog {
 3502:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 3503:     if ($users<2) { return; }
 3504:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 3505:             'course'       => $env{'request.course.id'},
 3506:             'sections'     => '"all"',
 3507:             'num_students' => $users,
 3508:             'part'         => $part,
 3509:             'symb'         => $symb,
 3510:             'mean_tries'   => $av_attempts,
 3511:             'deg_of_diff'  => $degdiff});
 3512:     foreach my $key (keys(%dynstore)) {
 3513:         $accesshash{$key}=$dynstore{$key};
 3514:     }
 3515: }
 3516:   
 3517: sub userrolelog {
 3518:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 3519:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
 3520:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 3521:        $userrolehash
 3522:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 3523:                     =$tend.':'.$tstart;
 3524:     }
 3525:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
 3526:        $userrolehash
 3527:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 3528:                     =$tend.':'.$tstart;
 3529:     }
 3530:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
 3531:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 3532:        $domainrolehash
 3533:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 3534:                     = $tend.':'.$tstart;
 3535:     }
 3536: }
 3537: 
 3538: sub courserolelog {
 3539:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 3540:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 3541:         my $cdom = $1;
 3542:         my $cnum = $2;
 3543:         my $sec = $3;
 3544:         my $namespace = 'rolelog';
 3545:         my %storehash = (
 3546:                            role    => $trole,
 3547:                            start   => $tstart,
 3548:                            end     => $tend,
 3549:                            selfenroll => $selfenroll,
 3550:                            context    => $context,
 3551:                         );
 3552:         if ($trole eq 'gr') {
 3553:             $namespace = 'groupslog';
 3554:             $storehash{'group'} = $sec;
 3555:         } else {
 3556:             $storehash{'section'} = $sec;
 3557:         }
 3558:         &write_log('course',$namespace,\%storehash,$delflag,$username,
 3559:                    $domain,$cnum,$cdom);
 3560:         if (($trole ne 'st') || ($sec ne '')) {
 3561:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 3562:         }
 3563:     }
 3564:     return;
 3565: }
 3566: 
 3567: sub domainrolelog {
 3568:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 3569:     if ($area =~ m{^/($match_domain)/$}) {
 3570:         my $cdom = $1;
 3571:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
 3572:         my $namespace = 'rolelog';
 3573:         my %storehash = (
 3574:                            role    => $trole,
 3575:                            start   => $tstart,
 3576:                            end     => $tend,
 3577:                            context => $context,
 3578:                         );
 3579:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
 3580:                    $domain,$domconfiguser,$cdom);
 3581:     }
 3582:     return;
 3583: 
 3584: }
 3585: 
 3586: sub coauthorrolelog {
 3587:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 3588:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
 3589:         my $audom = $1;
 3590:         my $auname = $2;
 3591:         my $namespace = 'rolelog';
 3592:         my %storehash = (
 3593:                            role    => $trole,
 3594:                            start   => $tstart,
 3595:                            end     => $tend,
 3596:                            context => $context,
 3597:                         );
 3598:         &write_log('author',$namespace,\%storehash,$delflag,$username,
 3599:                    $domain,$auname,$audom);
 3600:     }
 3601:     return;
 3602: }
 3603: 
 3604: sub get_course_adv_roles {
 3605:     my ($cid,$codes) = @_;
 3606:     $cid=$env{'request.course.id'} unless (defined($cid));
 3607:     my %coursehash=&coursedescription($cid);
 3608:     my $crstype = &Apache::loncommon::course_type($cid);
 3609:     my %nothide=();
 3610:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3611:         if ($user !~ /:/) {
 3612: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 3613:         } else {
 3614:             $nothide{$user}=1;
 3615:         }
 3616:     }
 3617:     my %returnhash=();
 3618:     my %dumphash=
 3619:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 3620:     my $now=time;
 3621:     my %privileged;
 3622:     foreach my $entry (keys(%dumphash)) {
 3623: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 3624:         if (($tstart) && ($tstart<0)) { next; }
 3625:         if (($tend) && ($tend<$now)) { next; }
 3626:         if (($tstart) && ($now<$tstart)) { next; }
 3627:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 3628: 	if ($username eq '' || $domain eq '') { next; }
 3629:         unless (ref($privileged{$domain}) eq 'HASH') {
 3630:             my %dompersonnel =
 3631:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
 3632:             $privileged{$domain} = {};
 3633:             foreach my $server (keys(%dompersonnel)) {
 3634:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 3635:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
 3636:                         my ($trole,$uname,$udom) = split(/:/,$user);
 3637:                         $privileged{$udom}{$uname} = 1;
 3638:                     }
 3639:                 }
 3640:             }
 3641:         }
 3642:         if ((exists($privileged{$domain}{$username})) && 
 3643:             (!$nothide{$username.':'.$domain})) { next; }
 3644: 	if ($role eq 'cr') { next; }
 3645:         if ($codes) {
 3646:             if ($section) { $role .= ':'.$section; }
 3647:             if ($returnhash{$role}) {
 3648:                 $returnhash{$role}.=','.$username.':'.$domain;
 3649:             } else {
 3650:                 $returnhash{$role}=$username.':'.$domain;
 3651:             }
 3652:         } else {
 3653:             my $key=&plaintext($role,$crstype);
 3654:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 3655:             if ($returnhash{$key}) {
 3656: 	        $returnhash{$key}.=','.$username.':'.$domain;
 3657:             } else {
 3658:                 $returnhash{$key}=$username.':'.$domain;
 3659:             }
 3660:         }
 3661:     }
 3662:     return %returnhash;
 3663: }
 3664: 
 3665: sub get_my_roles {
 3666:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 3667:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 3668:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 3669:     my (%dumphash,%nothide);
 3670:     if ($context eq 'userroles') {
 3671:         %dumphash = &dump('roles',$udom,$uname);
 3672:     } else {
 3673:         %dumphash=
 3674:             &dump('nohist_userroles',$udom,$uname);
 3675:         if ($hidepriv) {
 3676:             my %coursehash=&coursedescription($udom.'_'.$uname);
 3677:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3678:                 if ($user !~ /:/) {
 3679:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 3680:                 } else {
 3681:                     $nothide{$user} = 1;
 3682:                 }
 3683:             }
 3684:         }
 3685:     }
 3686:     my %returnhash=();
 3687:     my $now=time;
 3688:     my %privileged;
 3689:     foreach my $entry (keys(%dumphash)) {
 3690:         my ($role,$tend,$tstart);
 3691:         if ($context eq 'userroles') {
 3692:             next if ($entry =~ /^rolesdef/);
 3693: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 3694:         } else {
 3695:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 3696:         }
 3697:         if (($tstart) && ($tstart<0)) { next; }
 3698:         my $status = 'active';
 3699:         if (($tend) && ($tend<=$now)) {
 3700:             $status = 'previous';
 3701:         } 
 3702:         if (($tstart) && ($now<$tstart)) {
 3703:             $status = 'future';
 3704:         }
 3705:         if (ref($types) eq 'ARRAY') {
 3706:             if (!grep(/^\Q$status\E$/,@{$types})) {
 3707:                 next;
 3708:             } 
 3709:         } else {
 3710:             if ($status ne 'active') {
 3711:                 next;
 3712:             }
 3713:         }
 3714:         my ($rolecode,$username,$domain,$section,$area);
 3715:         if ($context eq 'userroles') {
 3716:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
 3717:             (undef,$domain,$username,$section) = split(/\//,$area);
 3718:         } else {
 3719:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 3720:         }
 3721:         if (ref($roledoms) eq 'ARRAY') {
 3722:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 3723:                 next;
 3724:             }
 3725:         }
 3726:         if (ref($roles) eq 'ARRAY') {
 3727:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 3728:                 if ($role =~ /^cr\//) {
 3729:                     if (!grep(/^cr$/,@{$roles})) {
 3730:                         next;
 3731:                     }
 3732:                 } elsif ($role =~ /^gr\//) {
 3733:                     if (!grep(/^gr$/,@{$roles})) {
 3734:                         next;
 3735:                     }
 3736:                 } else {
 3737:                     next;
 3738:                 }
 3739:             }
 3740:         }
 3741:         if ($hidepriv) {
 3742:             if ($context eq 'userroles') {
 3743:                 if ((&privileged($username,$domain)) &&
 3744:                     (!$nothide{$username.':'.$domain})) {
 3745:                     next;
 3746:                 }
 3747:             } else {
 3748:                 unless (ref($privileged{$domain}) eq 'HASH') {
 3749:                     my %dompersonnel =
 3750:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
 3751:                     $privileged{$domain} = {};
 3752:                     if (keys(%dompersonnel)) {
 3753:                         foreach my $server (keys(%dompersonnel)) {
 3754:                             if (ref($dompersonnel{$server}) eq 'HASH') {
 3755:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
 3756:                                     my ($trole,$uname,$udom) = split(/:/,$user);
 3757:                                     $privileged{$udom}{$uname} = $trole;
 3758:                                 }
 3759:                             }
 3760:                         }
 3761:                     }
 3762:                 }
 3763:                 if (exists($privileged{$domain}{$username})) {
 3764:                     if (!$nothide{$username.':'.$domain}) {
 3765:                         next;
 3766:                     }
 3767:                 }
 3768:             }
 3769:         }
 3770:         if ($withsec) {
 3771:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 3772:                 $tstart.':'.$tend;
 3773:         } else {
 3774:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 3775:         }
 3776:     }
 3777:     return %returnhash;
 3778: }
 3779: 
 3780: # ----------------------------------------------------- Frontpage Announcements
 3781: #
 3782: #
 3783: 
 3784: sub postannounce {
 3785:     my ($server,$text)=@_;
 3786:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 3787:     unless ($text=~/\w/) { $text=''; }
 3788:     return &reply('setannounce:'.&escape($text),$server);
 3789: }
 3790: 
 3791: sub getannounce {
 3792: 
 3793:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 3794: 	my $announcement='';
 3795: 	while (my $line = <$fh>) { $announcement .= $line; }
 3796: 	close($fh);
 3797: 	if ($announcement=~/\w/) { 
 3798: 	    return 
 3799:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 3800:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 3801: 	} else {
 3802: 	    return '';
 3803: 	}
 3804:     } else {
 3805: 	return '';
 3806:     }
 3807: }
 3808: 
 3809: # ---------------------------------------------------------- Course ID routines
 3810: # Deal with domain's nohist_courseid.db files
 3811: #
 3812: 
 3813: sub courseidput {
 3814:     my ($domain,$storehash,$coursehome,$caller) = @_;
 3815:     return unless (ref($storehash) eq 'HASH');
 3816:     my $outcome;
 3817:     if ($caller eq 'timeonly') {
 3818:         my $cids = '';
 3819:         foreach my $item (keys(%$storehash)) {
 3820:             $cids.=&escape($item).'&';
 3821:         }
 3822:         $cids=~s/\&$//;
 3823:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 3824:                           $coursehome);       
 3825:     } else {
 3826:         my $items = '';
 3827:         foreach my $item (keys(%$storehash)) {
 3828:             $items.= &escape($item).'='.
 3829:                      &freeze_escape($$storehash{$item}).'&';
 3830:         }
 3831:         $items=~s/\&$//;
 3832:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 3833:                           $coursehome);
 3834:     }
 3835:     if ($outcome eq 'unknown_cmd') {
 3836:         my $what;
 3837:         foreach my $cid (keys(%$storehash)) {
 3838:             $what .= &escape($cid).'=';
 3839:             foreach my $item ('description','inst_code','owner','type') {
 3840:                 $what .= &escape($storehash->{$cid}{$item}).':';
 3841:             }
 3842:             $what =~ s/\:$/&/;
 3843:         }
 3844:         $what =~ s/\&$//;  
 3845:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 3846:     } else {
 3847:         return $outcome;
 3848:     }
 3849: }
 3850: 
 3851: sub courseiddump {
 3852:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 3853:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 3854:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 3855:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
 3856:     my $as_hash = 1;
 3857:     my %returnhash;
 3858:     if (!$domfilter) { $domfilter=''; }
 3859:     my %libserv = &all_library();
 3860:     foreach my $tryserver (keys(%libserv)) {
 3861:         if ( (  $hostidflag == 1 
 3862: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 3863: 	     || (!defined($hostidflag)) ) {
 3864: 
 3865: 	    if (($domfilter eq '') ||
 3866: 		(&host_domain($tryserver) eq $domfilter)) {
 3867:                 my $rep;
 3868:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
 3869:                     $rep = LONCAPA::Lond::dump_course_id_handler(
 3870:                         join(":", (&host_domain($tryserver), $sincefilter, 
 3871:                                 &escape($descfilter), &escape($instcodefilter), 
 3872:                                 &escape($ownerfilter), &escape($coursefilter),
 3873:                                 &escape($typefilter), &escape($regexp_ok), 
 3874:                                 $as_hash, &escape($selfenrollonly), 
 3875:                                 &escape($catfilter), $showhidden, $caller, 
 3876:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
 3877:                                 &escape($createdbefore), &escape($createdafter), 
 3878:                                 &escape($creationcontext), $domcloner)));
 3879:                 } else {
 3880:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
 3881:                              $sincefilter.':'.&escape($descfilter).':'.
 3882:                              &escape($instcodefilter).':'.&escape($ownerfilter).
 3883:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
 3884:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
 3885:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
 3886:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
 3887:                              &escape($cc_clone).':'.$cloneonly.':'.
 3888:                              &escape($createdbefore).':'.&escape($createdafter).':'.
 3889:                              &escape($creationcontext).':'.$domcloner,
 3890:                              $tryserver);
 3891:                 }
 3892:                      
 3893:                 my @pairs=split(/\&/,$rep);
 3894:                 foreach my $item (@pairs) {
 3895:                     my ($key,$value)=split(/\=/,$item,2);
 3896:                     $key = &unescape($key);
 3897:                     next if ($key =~ /^error: 2 /);
 3898:                     my $result = &thaw_unescape($value);
 3899:                     if (ref($result) eq 'HASH') {
 3900:                         $returnhash{$key}=$result;
 3901:                     } else {
 3902:                         my @responses = split(/:/,$value);
 3903:                         my @items = ('description','inst_code','owner','type');
 3904:                         for (my $i=0; $i<@responses; $i++) {
 3905:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 3906:                         }
 3907:                     }
 3908:                 }
 3909:             }
 3910:         }
 3911:     }
 3912:     return %returnhash;
 3913: }
 3914: 
 3915: sub courselastaccess {
 3916:     my ($cdom,$cnum,$hostidref) = @_;
 3917:     my %returnhash;
 3918:     if ($cdom && $cnum) {
 3919:         my $chome = &homeserver($cnum,$cdom);
 3920:         if ($chome ne 'no_host') {
 3921:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 3922:             &extract_lastaccess(\%returnhash,$rep);
 3923:         }
 3924:     } else {
 3925:         if (!$cdom) { $cdom=''; }
 3926:         my %libserv = &all_library();
 3927:         foreach my $tryserver (keys(%libserv)) {
 3928:             if (ref($hostidref) eq 'ARRAY') {
 3929:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 3930:             } 
 3931:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 3932:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 3933:                 &extract_lastaccess(\%returnhash,$rep);
 3934:             }
 3935:         }
 3936:     }
 3937:     return %returnhash;
 3938: }
 3939: 
 3940: sub extract_lastaccess {
 3941:     my ($returnhash,$rep) = @_;
 3942:     if (ref($returnhash) eq 'HASH') {
 3943:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 3944:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 3945:                  $rep eq '') {
 3946:             my @pairs=split(/\&/,$rep);
 3947:             foreach my $item (@pairs) {
 3948:                 my ($key,$value)=split(/\=/,$item,2);
 3949:                 $key = &unescape($key);
 3950:                 next if ($key =~ /^error: 2 /);
 3951:                 $returnhash->{$key} = &thaw_unescape($value);
 3952:             }
 3953:         }
 3954:     }
 3955:     return;
 3956: }
 3957: 
 3958: # ---------------------------------------------------------- DC e-mail
 3959: 
 3960: sub dcmailput {
 3961:     my ($domain,$msgid,$message,$server)=@_;
 3962:     my $status = &Apache::lonnet::critical(
 3963:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 3964:        &escape($message),$server);
 3965:     return $status;
 3966: }
 3967: 
 3968: sub dcmaildump {
 3969:     my ($dom,$startdate,$enddate,$senders) = @_;
 3970:     my %returnhash=();
 3971: 
 3972:     if (defined(&domain($dom,'primary'))) {
 3973:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 3974:                                                          &escape($enddate).':';
 3975: 	my @esc_senders=map { &escape($_)} @$senders;
 3976: 	$cmd.=&escape(join('&',@esc_senders));
 3977: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 3978:             my ($key,$value) = split(/\=/,$line,2);
 3979:             if (($key) && ($value)) {
 3980:                 $returnhash{&unescape($key)} = &unescape($value);
 3981:             }
 3982:         }
 3983:     }
 3984:     return %returnhash;
 3985: }
 3986: # ---------------------------------------------------------- Domain roles
 3987: 
 3988: sub get_domain_roles {
 3989:     my ($dom,$roles,$startdate,$enddate)=@_;
 3990:     if ((!defined($startdate)) || ($startdate eq '')) {
 3991:         $startdate = '.';
 3992:     }
 3993:     if ((!defined($enddate)) || ($enddate eq '')) {
 3994:         $enddate = '.';
 3995:     }
 3996:     my $rolelist;
 3997:     if (ref($roles) eq 'ARRAY') {
 3998:         $rolelist = join(':',@{$roles});
 3999:     }
 4000:     my %personnel = ();
 4001: 
 4002:     my %servers = &get_servers($dom,'library');
 4003:     foreach my $tryserver (keys(%servers)) {
 4004: 	%{$personnel{$tryserver}}=();
 4005: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 4006: 					    &escape($startdate).':'.
 4007: 					    &escape($enddate).':'.
 4008: 					    &escape($rolelist), $tryserver))) {
 4009: 	    my ($key,$value) = split(/\=/,$line,2);
 4010: 	    if (($key) && ($value)) {
 4011: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 4012: 	    }
 4013: 	}
 4014:     }
 4015:     return %personnel;
 4016: }
 4017: 
 4018: # ----------------------------------------------------------- Interval timing 
 4019: 
 4020: {
 4021: # Caches needed for speedup of navmaps
 4022: # We don't want to cache this for very long at all (5 seconds at most)
 4023: # 
 4024: # The user for whom we cache
 4025: my $cachedkey='';
 4026: # The cached times for this user
 4027: my %cachedtimes=();
 4028: # When this was last done
 4029: my $cachedtime=();
 4030: 
 4031: sub load_all_first_access {
 4032:     my ($uname,$udom)=@_;
 4033:     if (($cachedkey eq $uname.':'.$udom) &&
 4034:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
 4035:         return;
 4036:     }
 4037:     $cachedtime=time;
 4038:     $cachedkey=$uname.':'.$udom;
 4039:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 4040: }
 4041: 
 4042: sub get_first_access {
 4043:     my ($type,$argsymb,$argmap)=@_;
 4044:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 4045:     if ($argsymb) { $symb=$argsymb; }
 4046:     my ($map,$id,$res)=&decode_symb($symb);
 4047:     if ($argmap) { $map = $argmap; }
 4048:     if ($type eq 'course') {
 4049: 	$res='course';
 4050:     } elsif ($type eq 'map') {
 4051: 	$res=&symbread($map);
 4052:     } else {
 4053: 	$res=$symb;
 4054:     }
 4055:     &load_all_first_access($uname,$udom);
 4056:     return $cachedtimes{"$courseid\0$res"};
 4057: }
 4058: 
 4059: sub set_first_access {
 4060:     my ($type,$interval)=@_;
 4061:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 4062:     my ($map,$id,$res)=&decode_symb($symb);
 4063:     if ($type eq 'course') {
 4064: 	$res='course';
 4065:     } elsif ($type eq 'map') {
 4066: 	$res=&symbread($map);
 4067:     } else {
 4068: 	$res=$symb;
 4069:     }
 4070:     $cachedkey='';
 4071:     my $firstaccess=&get_first_access($type,$symb,$map);
 4072:     if (!$firstaccess) {
 4073:         my $start = time;
 4074: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 4075:                           $udom,$uname);
 4076:         if ($putres eq 'ok') {
 4077:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 4078:                  $udom,$uname); 
 4079:             &appenv(
 4080:                      {
 4081:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 4082:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 4083:                      }
 4084:                   );
 4085:         }
 4086:         return $putres;
 4087:     }
 4088:     return 'already_set';
 4089: }
 4090: }
 4091: # --------------------------------------------- Set Expire Date for Spreadsheet
 4092: 
 4093: sub expirespread {
 4094:     my ($uname,$udom,$stype,$usymb)=@_;
 4095:     my $cid=$env{'request.course.id'}; 
 4096:     if ($cid) {
 4097:        my $now=time;
 4098:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 4099:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 4100:                             $env{'course.'.$cid.'.num'}.
 4101: 	        	    ':nohist_expirationdates:'.
 4102:                             &escape($key).'='.$now,
 4103:                             $env{'course.'.$cid.'.home'})
 4104:     }
 4105:     return 'ok';
 4106: }
 4107: 
 4108: # ----------------------------------------------------- Devalidate Spreadsheets
 4109: 
 4110: sub devalidate {
 4111:     my ($symb,$uname,$udom)=@_;
 4112:     my $cid=$env{'request.course.id'}; 
 4113:     if ($cid) {
 4114:         # delete the stored spreadsheets for
 4115:         # - the student level sheet of this user in course's homespace
 4116:         # - the assessment level sheet for this resource 
 4117:         #   for this user in user's homespace
 4118: 	# - current conditional state info
 4119: 	my $key=$uname.':'.$udom.':';
 4120:         my $status=
 4121: 	    &del('nohist_calculatedsheets',
 4122: 		 [$key.'studentcalc:'],
 4123: 		 $env{'course.'.$cid.'.domain'},
 4124: 		 $env{'course.'.$cid.'.num'})
 4125: 		.' '.
 4126: 	    &del('nohist_calculatedsheets_'.$cid,
 4127: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 4128:         unless ($status eq 'ok ok') {
 4129:            &logthis('Could not devalidate spreadsheet '.
 4130:                     $uname.' at '.$udom.' for '.
 4131: 		    $symb.': '.$status);
 4132:         }
 4133: 	&delenv('user.state.'.$cid);
 4134:     }
 4135: }
 4136: 
 4137: sub get_scalar {
 4138:     my ($string,$end) = @_;
 4139:     my $value;
 4140:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 4141: 	$value = $1;
 4142:     } elsif ($$string =~ s/^([^&]*?)&//) {
 4143: 	$value = $1;
 4144:     }
 4145:     return &unescape($value);
 4146: }
 4147: 
 4148: sub array2str {
 4149:   my (@array) = @_;
 4150:   my $result=&arrayref2str(\@array);
 4151:   $result=~s/^__ARRAY_REF__//;
 4152:   $result=~s/__END_ARRAY_REF__$//;
 4153:   return $result;
 4154: }
 4155: 
 4156: sub arrayref2str {
 4157:   my ($arrayref) = @_;
 4158:   my $result='__ARRAY_REF__';
 4159:   foreach my $elem (@$arrayref) {
 4160:     if(ref($elem) eq 'ARRAY') {
 4161:       $result.=&arrayref2str($elem).'&';
 4162:     } elsif(ref($elem) eq 'HASH') {
 4163:       $result.=&hashref2str($elem).'&';
 4164:     } elsif(ref($elem)) {
 4165:       #print("Got a ref of ".(ref($elem))." skipping.");
 4166:     } else {
 4167:       $result.=&escape($elem).'&';
 4168:     }
 4169:   }
 4170:   $result=~s/\&$//;
 4171:   $result .= '__END_ARRAY_REF__';
 4172:   return $result;
 4173: }
 4174: 
 4175: sub hash2str {
 4176:   my (%hash) = @_;
 4177:   my $result=&hashref2str(\%hash);
 4178:   $result=~s/^__HASH_REF__//;
 4179:   $result=~s/__END_HASH_REF__$//;
 4180:   return $result;
 4181: }
 4182: 
 4183: sub hashref2str {
 4184:   my ($hashref)=@_;
 4185:   my $result='__HASH_REF__';
 4186:   foreach my $key (sort(keys(%$hashref))) {
 4187:     if (ref($key) eq 'ARRAY') {
 4188:       $result.=&arrayref2str($key).'=';
 4189:     } elsif (ref($key) eq 'HASH') {
 4190:       $result.=&hashref2str($key).'=';
 4191:     } elsif (ref($key)) {
 4192:       $result.='=';
 4193:       #print("Got a ref of ".(ref($key))." skipping.");
 4194:     } else {
 4195: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 4196:     }
 4197: 
 4198:     if(ref($hashref->{$key}) eq 'ARRAY') {
 4199:       $result.=&arrayref2str($hashref->{$key}).'&';
 4200:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 4201:       $result.=&hashref2str($hashref->{$key}).'&';
 4202:     } elsif(ref($hashref->{$key})) {
 4203:        $result.='&';
 4204:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 4205:     } else {
 4206:       $result.=&escape($hashref->{$key}).'&';
 4207:     }
 4208:   }
 4209:   $result=~s/\&$//;
 4210:   $result .= '__END_HASH_REF__';
 4211:   return $result;
 4212: }
 4213: 
 4214: sub str2hash {
 4215:     my ($string)=@_;
 4216:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 4217:     return %$hash;
 4218: }
 4219: 
 4220: sub str2hashref {
 4221:   my ($string) = @_;
 4222: 
 4223:   my %hash;
 4224: 
 4225:   if($string !~ /^__HASH_REF__/) {
 4226:       if (! ($string eq '' || !defined($string))) {
 4227: 	  $hash{'error'}='Not hash reference';
 4228:       }
 4229:       return (\%hash, $string);
 4230:   }
 4231: 
 4232:   $string =~ s/^__HASH_REF__//;
 4233: 
 4234:   while($string !~ /^__END_HASH_REF__/) {
 4235:       #key
 4236:       my $key='';
 4237:       if($string =~ /^__HASH_REF__/) {
 4238:           ($key, $string)=&str2hashref($string);
 4239:           if(defined($key->{'error'})) {
 4240:               $hash{'error'}='Bad data';
 4241:               return (\%hash, $string);
 4242:           }
 4243:       } elsif($string =~ /^__ARRAY_REF__/) {
 4244:           ($key, $string)=&str2arrayref($string);
 4245:           if($key->[0] eq 'Array reference error') {
 4246:               $hash{'error'}='Bad data';
 4247:               return (\%hash, $string);
 4248:           }
 4249:       } else {
 4250:           $string =~ s/^(.*?)=//;
 4251: 	  $key=&unescape($1);
 4252:       }
 4253:       $string =~ s/^=//;
 4254: 
 4255:       #value
 4256:       my $value='';
 4257:       if($string =~ /^__HASH_REF__/) {
 4258:           ($value, $string)=&str2hashref($string);
 4259:           if(defined($value->{'error'})) {
 4260:               $hash{'error'}='Bad data';
 4261:               return (\%hash, $string);
 4262:           }
 4263:       } elsif($string =~ /^__ARRAY_REF__/) {
 4264:           ($value, $string)=&str2arrayref($string);
 4265:           if($value->[0] eq 'Array reference error') {
 4266:               $hash{'error'}='Bad data';
 4267:               return (\%hash, $string);
 4268:           }
 4269:       } else {
 4270: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 4271:       }
 4272:       $string =~ s/^&//;
 4273: 
 4274:       $hash{$key}=$value;
 4275:   }
 4276: 
 4277:   $string =~ s/^__END_HASH_REF__//;
 4278: 
 4279:   return (\%hash, $string);
 4280: }
 4281: 
 4282: sub str2array {
 4283:     my ($string)=@_;
 4284:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 4285:     return @$array;
 4286: }
 4287: 
 4288: sub str2arrayref {
 4289:   my ($string) = @_;
 4290:   my @array;
 4291: 
 4292:   if($string !~ /^__ARRAY_REF__/) {
 4293:       if (! ($string eq '' || !defined($string))) {
 4294: 	  $array[0]='Array reference error';
 4295:       }
 4296:       return (\@array, $string);
 4297:   }
 4298: 
 4299:   $string =~ s/^__ARRAY_REF__//;
 4300: 
 4301:   while($string !~ /^__END_ARRAY_REF__/) {
 4302:       my $value='';
 4303:       if($string =~ /^__HASH_REF__/) {
 4304:           ($value, $string)=&str2hashref($string);
 4305:           if(defined($value->{'error'})) {
 4306:               $array[0] ='Array reference error';
 4307:               return (\@array, $string);
 4308:           }
 4309:       } elsif($string =~ /^__ARRAY_REF__/) {
 4310:           ($value, $string)=&str2arrayref($string);
 4311:           if($value->[0] eq 'Array reference error') {
 4312:               $array[0] ='Array reference error';
 4313:               return (\@array, $string);
 4314:           }
 4315:       } else {
 4316: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 4317:       }
 4318:       $string =~ s/^&//;
 4319: 
 4320:       push(@array, $value);
 4321:   }
 4322: 
 4323:   $string =~ s/^__END_ARRAY_REF__//;
 4324: 
 4325:   return (\@array, $string);
 4326: }
 4327: 
 4328: # -------------------------------------------------------------------Temp Store
 4329: 
 4330: sub tmpreset {
 4331:   my ($symb,$namespace,$domain,$stuname) = @_;
 4332:   if (!$symb) {
 4333:     $symb=&symbread();
 4334:     if (!$symb) { $symb= $env{'request.url'}; }
 4335:   }
 4336:   $symb=escape($symb);
 4337: 
 4338:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4339:   $namespace=~s/\//\_/g;
 4340:   $namespace=~s/\W//g;
 4341: 
 4342:   if (!$domain) { $domain=$env{'user.domain'}; }
 4343:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4344:   if ($domain eq 'public' && $stuname eq 'public') {
 4345:       $stuname=$ENV{'REMOTE_ADDR'};
 4346:   }
 4347:   my $path=LONCAPA::tempdir();
 4348:   my %hash;
 4349:   if (tie(%hash,'GDBM_File',
 4350: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4351: 	  &GDBM_WRCREAT(),0640)) {
 4352:     foreach my $key (keys(%hash)) {
 4353:       if ($key=~ /:$symb/) {
 4354: 	delete($hash{$key});
 4355:       }
 4356:     }
 4357:   }
 4358: }
 4359: 
 4360: sub tmpstore {
 4361:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4362: 
 4363:   if (!$symb) {
 4364:     $symb=&symbread();
 4365:     if (!$symb) { $symb= $env{'request.url'}; }
 4366:   }
 4367:   $symb=escape($symb);
 4368: 
 4369:   if (!$namespace) {
 4370:     # I don't think we would ever want to store this for a course.
 4371:     # it seems this will only be used if we don't have a course.
 4372:     #$namespace=$env{'request.course.id'};
 4373:     #if (!$namespace) {
 4374:       $namespace=$env{'request.state'};
 4375:     #}
 4376:   }
 4377:   $namespace=~s/\//\_/g;
 4378:   $namespace=~s/\W//g;
 4379:   if (!$domain) { $domain=$env{'user.domain'}; }
 4380:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4381:   if ($domain eq 'public' && $stuname eq 'public') {
 4382:       $stuname=$ENV{'REMOTE_ADDR'};
 4383:   }
 4384:   my $now=time;
 4385:   my %hash;
 4386:   my $path=LONCAPA::tempdir();
 4387:   if (tie(%hash,'GDBM_File',
 4388: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4389: 	  &GDBM_WRCREAT(),0640)) {
 4390:     $hash{"version:$symb"}++;
 4391:     my $version=$hash{"version:$symb"};
 4392:     my $allkeys=''; 
 4393:     foreach my $key (keys(%$storehash)) {
 4394:       $allkeys.=$key.':';
 4395:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 4396:     }
 4397:     $hash{"$version:$symb:timestamp"}=$now;
 4398:     $allkeys.='timestamp';
 4399:     $hash{"$version:keys:$symb"}=$allkeys;
 4400:     if (untie(%hash)) {
 4401:       return 'ok';
 4402:     } else {
 4403:       return "error:$!";
 4404:     }
 4405:   } else {
 4406:     return "error:$!";
 4407:   }
 4408: }
 4409: 
 4410: # -----------------------------------------------------------------Temp Restore
 4411: 
 4412: sub tmprestore {
 4413:   my ($symb,$namespace,$domain,$stuname) = @_;
 4414: 
 4415:   if (!$symb) {
 4416:     $symb=&symbread();
 4417:     if (!$symb) { $symb= $env{'request.url'}; }
 4418:   }
 4419:   $symb=escape($symb);
 4420: 
 4421:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4422: 
 4423:   if (!$domain) { $domain=$env{'user.domain'}; }
 4424:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4425:   if ($domain eq 'public' && $stuname eq 'public') {
 4426:       $stuname=$ENV{'REMOTE_ADDR'};
 4427:   }
 4428:   my %returnhash;
 4429:   $namespace=~s/\//\_/g;
 4430:   $namespace=~s/\W//g;
 4431:   my %hash;
 4432:   my $path=LONCAPA::tempdir();
 4433:   if (tie(%hash,'GDBM_File',
 4434: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4435: 	  &GDBM_READER(),0640)) {
 4436:     my $version=$hash{"version:$symb"};
 4437:     $returnhash{'version'}=$version;
 4438:     my $scope;
 4439:     for ($scope=1;$scope<=$version;$scope++) {
 4440:       my $vkeys=$hash{"$scope:keys:$symb"};
 4441:       my @keys=split(/:/,$vkeys);
 4442:       my $key;
 4443:       $returnhash{"$scope:keys"}=$vkeys;
 4444:       foreach $key (@keys) {
 4445: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4446: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4447:       }
 4448:     }
 4449:     if (!(untie(%hash))) {
 4450:       return "error:$!";
 4451:     }
 4452:   } else {
 4453:     return "error:$!";
 4454:   }
 4455:   return %returnhash;
 4456: }
 4457: 
 4458: # ----------------------------------------------------------------------- Store
 4459: 
 4460: sub store {
 4461:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4462:     my $home='';
 4463: 
 4464:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4465: 
 4466:     $symb=&symbclean($symb);
 4467:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 4468: 
 4469:     if (!$domain) { $domain=$env{'user.domain'}; }
 4470:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4471: 
 4472:     &devalidate($symb,$stuname,$domain);
 4473: 
 4474:     $symb=escape($symb);
 4475:     if (!$namespace) { 
 4476:        unless ($namespace=$env{'request.course.id'}) { 
 4477:           return ''; 
 4478:        } 
 4479:     }
 4480:     if (!$home) { $home=$env{'user.home'}; }
 4481: 
 4482:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 4483:     $$storehash{'host'}=$perlvar{'lonHostID'};
 4484: 
 4485:     my $namevalue='';
 4486:     foreach my $key (keys(%$storehash)) {
 4487:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4488:     }
 4489:     $namevalue=~s/\&$//;
 4490:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 4491:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 4492: }
 4493: 
 4494: # -------------------------------------------------------------- Critical Store
 4495: 
 4496: sub cstore {
 4497:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4498:     my $home='';
 4499: 
 4500:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4501: 
 4502:     $symb=&symbclean($symb);
 4503:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 4504: 
 4505:     if (!$domain) { $domain=$env{'user.domain'}; }
 4506:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4507: 
 4508:     &devalidate($symb,$stuname,$domain);
 4509: 
 4510:     $symb=escape($symb);
 4511:     if (!$namespace) { 
 4512:        unless ($namespace=$env{'request.course.id'}) { 
 4513:           return ''; 
 4514:        } 
 4515:     }
 4516:     if (!$home) { $home=$env{'user.home'}; }
 4517: 
 4518:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 4519:     $$storehash{'host'}=$perlvar{'lonHostID'};
 4520: 
 4521:     my $namevalue='';
 4522:     foreach my $key (keys(%$storehash)) {
 4523:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4524:     }
 4525:     $namevalue=~s/\&$//;
 4526:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 4527:     return critical
 4528:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 4529: }
 4530: 
 4531: # --------------------------------------------------------------------- Restore
 4532: 
 4533: sub restore {
 4534:     my ($symb,$namespace,$domain,$stuname) = @_;
 4535:     my $home='';
 4536: 
 4537:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4538: 
 4539:     if (!$symb) {
 4540:       unless ($symb=escape(&symbread())) { return ''; }
 4541:     } else {
 4542:       $symb=&escape(&symbclean($symb));
 4543:     }
 4544:     if (!$namespace) { 
 4545:        unless ($namespace=$env{'request.course.id'}) { 
 4546:           return ''; 
 4547:        } 
 4548:     }
 4549:     if (!$domain) { $domain=$env{'user.domain'}; }
 4550:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4551:     if (!$home) { $home=$env{'user.home'}; }
 4552:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 4553: 
 4554:     my %returnhash=();
 4555:     foreach my $line (split(/\&/,$answer)) {
 4556: 	my ($name,$value)=split(/\=/,$line);
 4557:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 4558:     }
 4559:     my $version;
 4560:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 4561:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 4562:           $returnhash{$item}=$returnhash{$version.':'.$item};
 4563:        }
 4564:     }
 4565:     return %returnhash;
 4566: }
 4567: 
 4568: # ---------------------------------------------------------- Course Description
 4569: #
 4570: #  
 4571: 
 4572: sub coursedescription {
 4573:     my ($courseid,$args)=@_;
 4574:     $courseid=~s/^\///;
 4575:     $courseid=~s/\_/\//g;
 4576:     my ($cdomain,$cnum)=split(/\//,$courseid);
 4577:     my $chome=&homeserver($cnum,$cdomain);
 4578:     my $normalid=$cdomain.'_'.$cnum;
 4579:     # need to always cache even if we get errors otherwise we keep 
 4580:     # trying and trying and trying to get the course description.
 4581:     my %envhash=();
 4582:     my %returnhash=();
 4583:     
 4584:     my $expiretime=600;
 4585:     if ($env{'request.course.id'} eq $normalid) {
 4586: 	$expiretime=120;
 4587:     }
 4588: 
 4589:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 4590:     if (!$args->{'freshen_cache'}
 4591: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 4592: 	foreach my $key (keys(%env)) {
 4593: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 4594: 	    my ($setting) = $1;
 4595: 	    $returnhash{$setting} = $env{$key};
 4596: 	}
 4597: 	return %returnhash;
 4598:     }
 4599: 
 4600:     # get the data again
 4601: 
 4602:     if (!$args->{'one_time'}) {
 4603: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 4604:     }
 4605: 
 4606:     if ($chome ne 'no_host') {
 4607:        %returnhash=&dump('environment',$cdomain,$cnum);
 4608:        if (!exists($returnhash{'con_lost'})) {
 4609: 	   my $username = $env{'user.name'}; # Defult username
 4610: 	   if(defined $args->{'user'}) {
 4611: 	       $username = $args->{'user'};
 4612: 	   }
 4613:            $returnhash{'home'}= $chome;
 4614: 	   $returnhash{'domain'} = $cdomain;
 4615: 	   $returnhash{'num'} = $cnum;
 4616:            if (!defined($returnhash{'type'})) {
 4617:                $returnhash{'type'} = 'Course';
 4618:            }
 4619:            while (my ($name,$value) = each %returnhash) {
 4620:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 4621:            }
 4622:            $returnhash{'url'}=&clutter($returnhash{'url'});
 4623:            $returnhash{'fn'}=LONCAPA::tempdir() .
 4624: 	       $username.'_'.$cdomain.'_'.$cnum;
 4625:            $envhash{'course.'.$normalid.'.home'}=$chome;
 4626:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 4627:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 4628:        }
 4629:     }
 4630:     if (!$args->{'one_time'}) {
 4631: 	&appenv(\%envhash);
 4632:     }
 4633:     return %returnhash;
 4634: }
 4635: 
 4636: sub update_released_required {
 4637:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 4638:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 4639:         $cid = $env{'request.course.id'};
 4640:         $cdom = $env{'course.'.$cid.'.domain'};
 4641:         $cnum = $env{'course.'.$cid.'.num'};
 4642:         $chome = $env{'course.'.$cid.'.home'};
 4643:     }
 4644:     if ($needsrelease) {
 4645:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 4646:         my $needsupdate;
 4647:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 4648:             $needsupdate = 1;
 4649:         } else {
 4650:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 4651:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 4652:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 4653:                 $needsupdate = 1;
 4654:             }
 4655:         }
 4656:         if ($needsupdate) {
 4657:             my %needshash = (
 4658:                              'internal.releaserequired' => $needsrelease,
 4659:                             );
 4660:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 4661:             if ($putresult eq 'ok') {
 4662:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 4663:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 4664:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 4665:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 4666:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 4667:                 }
 4668:             }
 4669:         }
 4670:     }
 4671:     return;
 4672: }
 4673: 
 4674: # -------------------------------------------------See if a user is privileged
 4675: 
 4676: sub privileged {
 4677:     my ($username,$domain)=@_;
 4678: 
 4679:     my %rolesdump = &dump("roles", $domain, $username) or return 0;
 4680:     my $now = time;
 4681: 
 4682:     for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
 4683:             my ($trole, $tend, $tstart) = split(/_/, $role);
 4684:             if (($trole eq 'dc') || ($trole eq 'su')) {
 4685:                 return 1 unless ($tend && $tend < $now) 
 4686:                     or ($tstart && $tstart > $now);
 4687:             }
 4688: 	}
 4689: 
 4690:     return 0;
 4691: }
 4692: 
 4693: # -------------------------------------------------------- Get user privileges
 4694: 
 4695: sub rolesinit {
 4696:     my ($domain, $username) = @_;
 4697:     my %userroles = ('user.login.time' => time);
 4698:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 4699: 
 4700:     # firstaccess and timerinterval are related to timed maps/resources. 
 4701:     # also, blocking can be triggered by an activating timer
 4702:     # it's saved in the user's %env.
 4703:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 4704:     my %timerinterval = &dump('timerinterval', $domain, $username);
 4705:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 4706:         %timerintchk, %timerintenv);
 4707: 
 4708:     foreach my $key (keys(%firstaccess)) {
 4709:         my ($cid, $rest) = split(/\0/, $key);
 4710:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 4711:     }
 4712: 
 4713:     foreach my $key (keys(%timerinterval)) {
 4714:         my ($cid,$rest) = split(/\0/,$key);
 4715:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 4716:     }
 4717: 
 4718:     my %allroles=();
 4719:     my %allgroups=();
 4720: 
 4721:     for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
 4722:         my $role = $rolesdump{$area};
 4723:         $area =~ s/\_\w\w$//;
 4724: 
 4725:         my ($trole, $tend, $tstart, $group_privs);
 4726: 
 4727:         if ($role =~ /^cr/) {
 4728:         # Custom role, defined by a user 
 4729:         # e.g., user.role.cr/msu/smith/mynewrole
 4730:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 4731:                 $trole = $1;
 4732:                 ($tend, $tstart) = split('_', $2);
 4733:             } else {
 4734:                 $trole = $role;
 4735:             }
 4736:         } elsif ($role =~ m|^gr/|) {
 4737:         # Role of member in a group, defined within a course/community
 4738:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 4739:             ($trole, $tend, $tstart) = split(/_/, $role);
 4740:             next if $tstart eq '-1';
 4741:             ($trole, $group_privs) = split(/\//, $trole);
 4742:             $group_privs = &unescape($group_privs);
 4743:         } else {
 4744:         # Just a normal role, defined in roles.tab
 4745:             ($trole, $tend, $tstart) = split(/_/,$role);
 4746:         }
 4747: 
 4748:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 4749:                  $username);
 4750:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 4751: 
 4752:         # role expired or not available yet?
 4753:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 4754:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 4755: 
 4756:         next if $area eq '' or $trole eq '';
 4757: 
 4758:         my $spec = "$trole.$area";
 4759:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 4760: 
 4761:         if ($trole =~ /^cr\//) {
 4762:         # Custom role, defined by a user
 4763:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 4764:         } elsif ($trole eq 'gr') {
 4765:         # Role of a member in a group, defined within a course/community
 4766:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 4767:             next;
 4768:         } else {
 4769:         # Normal role, defined in roles.tab
 4770:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 4771:         }
 4772: 
 4773:         my $cid = $tdomain.'_'.$trest;
 4774:         unless ($firstaccchk{$cid}) {
 4775:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 4776:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 4777:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 4778:                         $coursetimerstarts{$cid}{$item}; 
 4779:                 }
 4780:             }
 4781:             $firstaccchk{$cid} = 1;
 4782:         }
 4783:         unless ($timerintchk{$cid}) {
 4784:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 4785:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 4786:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 4787:                        $coursetimerintervals{$cid}{$item};
 4788:                 }
 4789:             }
 4790:             $timerintchk{$cid} = 1;
 4791:         }
 4792:     }
 4793: 
 4794:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
 4795:         \%allroles, \%allgroups);
 4796:     $env{'user.adv'} = $userroles{'user.adv'};
 4797: 
 4798:     return (\%userroles,\%firstaccenv,\%timerintenv);
 4799: }
 4800: 
 4801: sub set_arearole {
 4802:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
 4803: # log the associated role with the area
 4804:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 4805:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 4806: }
 4807: 
 4808: sub custom_roleprivs {
 4809:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 4810:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 4811:     my $homsvr=homeserver($rauthor,$rdomain);
 4812:     if (&hostname($homsvr) ne '') {
 4813:         my ($rdummy,$roledef)=
 4814:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 4815:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 4816:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 4817:             if (defined($syspriv)) {
 4818:                 if ($trest =~ /^$match_community$/) {
 4819:                     $syspriv =~ s/bre\&S//; 
 4820:                 }
 4821:                 $$allroles{'cm./'}.=':'.$syspriv;
 4822:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 4823:             }
 4824:             if ($tdomain ne '') {
 4825:                 if (defined($dompriv)) {
 4826:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 4827:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 4828:                 }
 4829:                 if (($trest ne '') && (defined($coursepriv))) {
 4830:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 4831:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 4832:                 }
 4833:             }
 4834:         }
 4835:     }
 4836: }
 4837: 
 4838: sub group_roleprivs {
 4839:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 4840:     my $access = 1;
 4841:     my $now = time;
 4842:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 4843:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 4844:     if ($access) {
 4845:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 4846:         $$allgroups{$course}{$group} .=':'.$group_privs;
 4847:     }
 4848: }
 4849: 
 4850: sub standard_roleprivs {
 4851:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 4852:     if (defined($pr{$trole.':s'})) {
 4853:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 4854:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 4855:     }
 4856:     if ($tdomain ne '') {
 4857:         if (defined($pr{$trole.':d'})) {
 4858:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 4859:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 4860:         }
 4861:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 4862:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 4863:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 4864:         }
 4865:     }
 4866: }
 4867: 
 4868: sub set_userprivs {
 4869:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 4870:     my $author=0;
 4871:     my $adv=0;
 4872:     my %grouproles = ();
 4873:     if (keys(%{$allgroups}) > 0) {
 4874:         my @groupkeys; 
 4875:         foreach my $role (keys(%{$allroles})) {
 4876:             push(@groupkeys,$role);
 4877:         }
 4878:         if (ref($groups_roles) eq 'HASH') {
 4879:             foreach my $key (keys(%{$groups_roles})) {
 4880:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 4881:                     push(@groupkeys,$key);
 4882:                 }
 4883:             }
 4884:         }
 4885:         if (@groupkeys > 0) {
 4886:             foreach my $role (@groupkeys) {
 4887:                 my ($trole,$area,$sec,$extendedarea);
 4888:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 4889:                     $trole = $1;
 4890:                     $area = $2;
 4891:                     $sec = $3;
 4892:                     $extendedarea = $area.$sec;
 4893:                     if (exists($$allgroups{$area})) {
 4894:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 4895:                             my $spec = $trole.'.'.$extendedarea;
 4896:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 4897:                                                 $$allgroups{$area}{$group};
 4898:                         }
 4899:                     }
 4900:                 }
 4901:             }
 4902:         }
 4903:     }
 4904:     foreach my $group (keys(%grouproles)) {
 4905:         $$allroles{$group} = $grouproles{$group};
 4906:     }
 4907:     foreach my $role (keys(%{$allroles})) {
 4908:         my %thesepriv;
 4909:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 4910:         foreach my $item (split(/:/,$$allroles{$role})) {
 4911:             if ($item ne '') {
 4912:                 my ($privilege,$restrictions)=split(/&/,$item);
 4913:                 if ($restrictions eq '') {
 4914:                     $thesepriv{$privilege}='F';
 4915:                 } elsif ($thesepriv{$privilege} ne 'F') {
 4916:                     $thesepriv{$privilege}.=$restrictions;
 4917:                 }
 4918:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 4919:             }
 4920:         }
 4921:         my $thesestr='';
 4922:         foreach my $priv (sort(keys(%thesepriv))) {
 4923: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 4924: 	}
 4925:         $userroles->{'user.priv.'.$role} = $thesestr;
 4926:     }
 4927:     return ($author,$adv);
 4928: }
 4929: 
 4930: sub role_status {
 4931:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 4932:     my @pwhere = ();
 4933:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 4934:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
 4935:         unless (!defined($$role) || $$role eq '') {
 4936:             $$where=join('.',@pwhere);
 4937:             $$trolecode=$$role.'.'.$$where;
 4938:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 4939:             $$tstatus='is';
 4940:             if ($$tstart && $$tstart>$update) {
 4941:                 $$tstatus='future';
 4942:                 if ($$tstart<$now) {
 4943:                     if ($$tstart && $$tstart>$refresh) {
 4944:                         if (($$where ne '') && ($$role ne '')) {
 4945:                             my (%allroles,%allgroups,$group_privs,
 4946:                                 %groups_roles,@rolecodes);
 4947:                             my %userroles = (
 4948:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 4949:                             );
 4950:                             @rolecodes = ('cm'); 
 4951:                             my $spec=$$role.'.'.$$where;
 4952:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 4953:                             if ($$role =~ /^cr\//) {
 4954:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 4955:                                 push(@rolecodes,'cr');
 4956:                             } elsif ($$role eq 'gr') {
 4957:                                 push(@rolecodes,$$role);
 4958:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 4959:                                                     $env{'user.name'});
 4960:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 4961:                                 (undef,my $group_privs) = split(/\//,$trole);
 4962:                                 $group_privs = &unescape($group_privs);
 4963:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 4964:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 4965:                                 &get_groups_roles($tdomain,$trest,
 4966:                                                   \%course_roles,\@rolecodes,
 4967:                                                   \%groups_roles);
 4968:                             } else {
 4969:                                 push(@rolecodes,$$role);
 4970:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 4971:                             }
 4972:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
 4973:                             &appenv(\%userroles,\@rolecodes);
 4974:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 4975:                         }
 4976:                     }
 4977:                     $$tstatus = 'is';
 4978:                 }
 4979:             }
 4980:             if ($$tend) {
 4981:                 if ($$tend<$update) {
 4982:                     $$tstatus='expired';
 4983:                 } elsif ($$tend<$now) {
 4984:                     $$tstatus='will_not';
 4985:                 }
 4986:             }
 4987:         }
 4988:     }
 4989: }
 4990: 
 4991: sub get_groups_roles {
 4992:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 4993:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 4994:                   (ref($rolecodes) eq 'ARRAY') && 
 4995:                   (ref($groups_roles) eq 'HASH')); 
 4996:     if (keys(%{$cdom_courseroles}) > 0) {
 4997:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 4998:         if ($cdom ne '' && $cnum ne '') {
 4999:             foreach my $key (keys(%{$cdom_courseroles})) {
 5000:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 5001:                     my $crsrole = $1;
 5002:                     my $crssec = $2;
 5003:                     if ($crsrole =~ /^cr/) {
 5004:                         unless (grep(/^cr$/,@{$rolecodes})) {
 5005:                             push(@{$rolecodes},'cr');
 5006:                         }
 5007:                     } else {
 5008:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 5009:                             push(@{$rolecodes},$crsrole);
 5010:                         }
 5011:                     }
 5012:                     my $rolekey = "$crsrole./$cdom/$cnum";
 5013:                     if ($crssec ne '') {
 5014:                         $rolekey .= "/$crssec";
 5015:                     }
 5016:                     $rolekey .= './';
 5017:                     $groups_roles->{$rolekey} = $rolecodes;
 5018:                 }
 5019:             }
 5020:         }
 5021:     }
 5022:     return;
 5023: }
 5024: 
 5025: sub delete_env_groupprivs {
 5026:     my ($where,$courseroles,$possroles) = @_;
 5027:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 5028:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 5029:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 5030:         %{$courseroles->{$udom}} =
 5031:             &get_my_roles('','','userroles',['active'],
 5032:                           $possroles,[$udom],1);
 5033:     }
 5034:     if (ref($courseroles->{$udom}) eq 'HASH') {
 5035:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 5036:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 5037:             my $area = '/'.$cdom.'/'.$cnum;
 5038:             my $privkey = "user.priv.$crsrole.$area";
 5039:             if ($crssec ne '') {
 5040:                 $privkey .= '/'.$crssec;
 5041:             }
 5042:             $privkey .= ".$area/$group";
 5043:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 5044:         }
 5045:     }
 5046:     return;
 5047: }
 5048: 
 5049: sub check_adhoc_privs {
 5050:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
 5051:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 5052:     my $setprivs;
 5053:     if ($env{$cckey}) {
 5054:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 5055:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 5056:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 5057:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 5058:             $setprivs = 1;
 5059:         }
 5060:     } else {
 5061:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 5062:         $setprivs = 1;
 5063:     }
 5064:     return $setprivs;
 5065: }
 5066: 
 5067: sub set_adhoc_privileges {
 5068: # role can be cc or ca
 5069:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
 5070:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 5071:     my $spec = $role.'.'.$area;
 5072:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 5073:                                   $env{'user.name'});
 5074:     my %ccrole = ();
 5075:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
 5076:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
 5077:     &appenv(\%userroles,[$role,'cm']);
 5078:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 5079:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
 5080:         &appenv( {'request.role'        => $spec,
 5081:                   'request.role.domain' => $dcdom,
 5082:                   'request.course.sec'  => ''
 5083:                  }
 5084:                );
 5085:         my $tadv=0;
 5086:         if (&allowed('adv') eq 'F') { $tadv=1; }
 5087:         &appenv({'request.role.adv'    => $tadv});
 5088:     }
 5089: }
 5090: 
 5091: # --------------------------------------------------------------- get interface
 5092: 
 5093: sub get {
 5094:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5095:    my $items='';
 5096:    foreach my $item (@$storearr) {
 5097:        $items.=&escape($item).'&';
 5098:    }
 5099:    $items=~s/\&$//;
 5100:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5101:    if (!$uname) { $uname=$env{'user.name'}; }
 5102:    my $uhome=&homeserver($uname,$udomain);
 5103: 
 5104:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 5105:    my @pairs=split(/\&/,$rep);
 5106:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 5107:      return @pairs;
 5108:    }
 5109:    my %returnhash=();
 5110:    my $i=0;
 5111:    foreach my $item (@$storearr) {
 5112:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 5113:       $i++;
 5114:    }
 5115:    return %returnhash;
 5116: }
 5117: 
 5118: # --------------------------------------------------------------- del interface
 5119: 
 5120: sub del {
 5121:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5122:    my $items='';
 5123:    foreach my $item (@$storearr) {
 5124:        $items.=&escape($item).'&';
 5125:    }
 5126: 
 5127:    $items=~s/\&$//;
 5128:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5129:    if (!$uname) { $uname=$env{'user.name'}; }
 5130:    my $uhome=&homeserver($uname,$udomain);
 5131:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 5132: }
 5133: 
 5134: # -------------------------------------------------------------- dump interface
 5135: 
 5136: sub unserialize {
 5137:     my ($rep, $escapedkeys) = @_;
 5138: 
 5139:     return {} if $rep =~ /^error/;
 5140: 
 5141:     my %returnhash=();
 5142: 	foreach my $item (split /\&/, $rep) {
 5143: 	    my ($key, $value) = split(/=/, $item, 2);
 5144: 	    $key = unescape($key) unless $escapedkeys;
 5145: 	    next if $key =~ /^error: 2 /;
 5146: 	    $returnhash{$key} = Apache::lonnet::thaw_unescape($value);
 5147: 	}
 5148:     #return %returnhash;
 5149:     return \%returnhash;
 5150: }        
 5151: 
 5152: # see Lond::dump_with_regexp
 5153: # if $escapedkeys hash keys won't get unescaped.
 5154: sub dump {
 5155:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
 5156:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5157:     if (!$uname) { $uname=$env{'user.name'}; }
 5158:     my $uhome=&homeserver($uname,$udomain);
 5159: 
 5160:     my $reply;
 5161:     if (grep { $_ eq $uhome } current_machine_ids()) {
 5162:         # user is hosted on this machine
 5163:         $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
 5164:                     $uname, $namespace, $regexp, $range)), $loncaparevs{$uhome});
 5165:         return %{unserialize($reply, $escapedkeys)};
 5166:     }
 5167:     if ($regexp) {
 5168: 	$regexp=&escape($regexp);
 5169:     } else {
 5170: 	$regexp='.';
 5171:     }
 5172:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 5173:     my @pairs=split(/\&/,$rep);
 5174:     my %returnhash=();
 5175:     if (!($rep =~ /^error/ )) {
 5176: 	foreach my $item (@pairs) {
 5177: 	    my ($key,$value)=split(/=/,$item,2);
 5178:         $key = unescape($key) unless $escapedkeys;
 5179:         #$key = &unescape($key);
 5180: 	    next if ($key =~ /^error: 2 /);
 5181: 	    $returnhash{$key}=&thaw_unescape($value);
 5182: 	}
 5183:     }
 5184:     return %returnhash;
 5185: }
 5186: 
 5187: 
 5188: # --------------------------------------------------------- dumpstore interface
 5189: 
 5190: sub dumpstore {
 5191:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 5192:    # same as dump but keys must be escaped. They may contain colon separated
 5193:    # lists of values that may themself contain colons (e.g. symbs).
 5194:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
 5195: }
 5196: 
 5197: # -------------------------------------------------------------- keys interface
 5198: 
 5199: sub getkeys {
 5200:    my ($namespace,$udomain,$uname)=@_;
 5201:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5202:    if (!$uname) { $uname=$env{'user.name'}; }
 5203:    my $uhome=&homeserver($uname,$udomain);
 5204:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 5205:    my @keyarray=();
 5206:    foreach my $key (split(/\&/,$rep)) {
 5207:       next if ($key =~ /^error: 2 /);
 5208:       push(@keyarray,&unescape($key));
 5209:    }
 5210:    return @keyarray;
 5211: }
 5212: 
 5213: # --------------------------------------------------------------- currentdump
 5214: sub currentdump {
 5215:    my ($courseid,$sdom,$sname)=@_;
 5216:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 5217:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 5218:    $sname    = $env{'user.name'}         if (! defined($sname));
 5219:    my $uhome = &homeserver($sname,$sdom);
 5220:    my $rep;
 5221: 
 5222:    if (grep { $_ eq $uhome } current_machine_ids()) {
 5223:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
 5224:                    $courseid)));
 5225:    } else {
 5226:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 5227:    }
 5228: 
 5229:    return if ($rep =~ /^(error:|no_such_host)/);
 5230:    #
 5231:    my %returnhash=();
 5232:    #
 5233:    if ($rep eq "unknown_cmd") { 
 5234:        # an old lond will not know currentdump
 5235:        # Do a dump and make it look like a currentdump
 5236:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 5237:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 5238:        my %hash = @tmp;
 5239:        @tmp=();
 5240:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 5241:    } else {
 5242:        my @pairs=split(/\&/,$rep);
 5243:        foreach my $pair (@pairs) {
 5244:            my ($key,$value)=split(/=/,$pair,2);
 5245:            my ($symb,$param) = split(/:/,$key);
 5246:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 5247:                                                         &thaw_unescape($value);
 5248:        }
 5249:    }
 5250:    return %returnhash;
 5251: }
 5252: 
 5253: sub convert_dump_to_currentdump{
 5254:     my %hash = %{shift()};
 5255:     my %returnhash;
 5256:     # Code ripped from lond, essentially.  The only difference
 5257:     # here is the unescaping done by lonnet::dump().  Conceivably
 5258:     # we might run in to problems with parameter names =~ /^v\./
 5259:     while (my ($key,$value) = each(%hash)) {
 5260:         my ($v,$symb,$param) = split(/:/,$key);
 5261: 	$symb  = &unescape($symb);
 5262: 	$param = &unescape($param);
 5263:         next if ($v eq 'version' || $symb eq 'keys');
 5264:         next if (exists($returnhash{$symb}) &&
 5265:                  exists($returnhash{$symb}->{$param}) &&
 5266:                  $returnhash{$symb}->{'v.'.$param} > $v);
 5267:         $returnhash{$symb}->{$param}=$value;
 5268:         $returnhash{$symb}->{'v.'.$param}=$v;
 5269:     }
 5270:     #
 5271:     # Remove all of the keys in the hashes which keep track of
 5272:     # the version of the parameter.
 5273:     while (my ($symb,$param_hash) = each(%returnhash)) {
 5274:         # use a foreach because we are going to delete from the hash.
 5275:         foreach my $key (keys(%$param_hash)) {
 5276:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 5277:         }
 5278:     }
 5279:     return \%returnhash;
 5280: }
 5281: 
 5282: # ------------------------------------------------------ critical inc interface
 5283: 
 5284: sub cinc {
 5285:     return &inc(@_,'critical');
 5286: }
 5287: 
 5288: # --------------------------------------------------------------- inc interface
 5289: 
 5290: sub inc {
 5291:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 5292:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5293:     if (!$uname) { $uname=$env{'user.name'}; }
 5294:     my $uhome=&homeserver($uname,$udomain);
 5295:     my $items='';
 5296:     if (! ref($store)) {
 5297:         # got a single value, so use that instead
 5298:         $items = &escape($store).'=&';
 5299:     } elsif (ref($store) eq 'SCALAR') {
 5300:         $items = &escape($$store).'=&';        
 5301:     } elsif (ref($store) eq 'ARRAY') {
 5302:         $items = join('=&',map {&escape($_);} @{$store});
 5303:     } elsif (ref($store) eq 'HASH') {
 5304:         while (my($key,$value) = each(%{$store})) {
 5305:             $items.= &escape($key).'='.&escape($value).'&';
 5306:         }
 5307:     }
 5308:     $items=~s/\&$//;
 5309:     if ($critical) {
 5310: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 5311:     } else {
 5312: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 5313:     }
 5314: }
 5315: 
 5316: # --------------------------------------------------------------- put interface
 5317: 
 5318: sub put {
 5319:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5320:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5321:    if (!$uname) { $uname=$env{'user.name'}; }
 5322:    my $uhome=&homeserver($uname,$udomain);
 5323:    my $items='';
 5324:    foreach my $item (keys(%$storehash)) {
 5325:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5326:    }
 5327:    $items=~s/\&$//;
 5328:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5329: }
 5330: 
 5331: # ------------------------------------------------------------ newput interface
 5332: 
 5333: sub newput {
 5334:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5335:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5336:    if (!$uname) { $uname=$env{'user.name'}; }
 5337:    my $uhome=&homeserver($uname,$udomain);
 5338:    my $items='';
 5339:    foreach my $key (keys(%$storehash)) {
 5340:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 5341:    }
 5342:    $items=~s/\&$//;
 5343:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 5344: }
 5345: 
 5346: # ---------------------------------------------------------  putstore interface
 5347: 
 5348: sub putstore {
 5349:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 5350:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5351:    if (!$uname) { $uname=$env{'user.name'}; }
 5352:    my $uhome=&homeserver($uname,$udomain);
 5353:    my $items='';
 5354:    foreach my $key (keys(%$storehash)) {
 5355:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 5356:    }
 5357:    $items=~s/\&$//;
 5358:    my $esc_symb=&escape($symb);
 5359:    my $esc_v=&escape($version);
 5360:    my $reply =
 5361:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 5362: 	      $uhome);
 5363:    if ($reply eq 'unknown_cmd') {
 5364:        # gfall back to way things use to be done
 5365:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 5366: 			    $uname);
 5367:    }
 5368:    return $reply;
 5369: }
 5370: 
 5371: sub old_putstore {
 5372:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 5373:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5374:     if (!$uname) { $uname=$env{'user.name'}; }
 5375:     my $uhome=&homeserver($uname,$udomain);
 5376:     my %newstorehash;
 5377:     foreach my $item (keys(%$storehash)) {
 5378: 	my $key = $version.':'.&escape($symb).':'.$item;
 5379: 	$newstorehash{$key} = $storehash->{$item};
 5380:     }
 5381:     my $items='';
 5382:     my %allitems = ();
 5383:     foreach my $item (keys(%newstorehash)) {
 5384: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 5385: 	    my $key = $1.':keys:'.$2;
 5386: 	    $allitems{$key} .= $3.':';
 5387: 	}
 5388: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 5389:     }
 5390:     foreach my $item (keys(%allitems)) {
 5391: 	$allitems{$item} =~ s/\:$//;
 5392: 	$items.= $item.'='.$allitems{$item}.'&';
 5393:     }
 5394:     $items=~s/\&$//;
 5395:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5396: }
 5397: 
 5398: # ------------------------------------------------------ critical put interface
 5399: 
 5400: sub cput {
 5401:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5402:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5403:    if (!$uname) { $uname=$env{'user.name'}; }
 5404:    my $uhome=&homeserver($uname,$udomain);
 5405:    my $items='';
 5406:    foreach my $item (keys(%$storehash)) {
 5407:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5408:    }
 5409:    $items=~s/\&$//;
 5410:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 5411: }
 5412: 
 5413: # -------------------------------------------------------------- eget interface
 5414: 
 5415: sub eget {
 5416:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5417:    my $items='';
 5418:    foreach my $item (@$storearr) {
 5419:        $items.=&escape($item).'&';
 5420:    }
 5421:    $items=~s/\&$//;
 5422:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5423:    if (!$uname) { $uname=$env{'user.name'}; }
 5424:    my $uhome=&homeserver($uname,$udomain);
 5425:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 5426:    my @pairs=split(/\&/,$rep);
 5427:    my %returnhash=();
 5428:    my $i=0;
 5429:    foreach my $item (@$storearr) {
 5430:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 5431:       $i++;
 5432:    }
 5433:    return %returnhash;
 5434: }
 5435: 
 5436: # ------------------------------------------------------------ tmpput interface
 5437: sub tmpput {
 5438:     my ($storehash,$server,$context)=@_;
 5439:     my $items='';
 5440:     foreach my $item (keys(%$storehash)) {
 5441: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5442:     }
 5443:     $items=~s/\&$//;
 5444:     if (defined($context)) {
 5445:         $items .= ':'.&escape($context);
 5446:     }
 5447:     return &reply("tmpput:$items",$server);
 5448: }
 5449: 
 5450: # ------------------------------------------------------------ tmpget interface
 5451: sub tmpget {
 5452:     my ($token,$server)=@_;
 5453:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 5454:     my $rep=&reply("tmpget:$token",$server);
 5455:     my %returnhash;
 5456:     foreach my $item (split(/\&/,$rep)) {
 5457: 	my ($key,$value)=split(/=/,$item);
 5458:         next if ($key =~ /^error: 2 /);
 5459: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 5460:     }
 5461:     return %returnhash;
 5462: }
 5463: 
 5464: # ------------------------------------------------------------ tmpdel interface
 5465: sub tmpdel {
 5466:     my ($token,$server)=@_;
 5467:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 5468:     return &reply("tmpdel:$token",$server);
 5469: }
 5470: 
 5471: # -------------------------------------------------- portfolio access checking
 5472: 
 5473: sub portfolio_access {
 5474:     my ($requrl) = @_;
 5475:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 5476:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 5477:     if ($result) {
 5478:         my %setters;
 5479:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 5480:             my ($startblock,$endblock) =
 5481:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 5482:             if ($startblock && $endblock) {
 5483:                 return 'B';
 5484:             }
 5485:         } else {
 5486:             my ($startblock,$endblock) =
 5487:                 &Apache::loncommon::blockcheck(\%setters,'port');
 5488:             if ($startblock && $endblock) {
 5489:                 return 'B';
 5490:             }
 5491:         }
 5492:     }
 5493:     if ($result eq 'ok') {
 5494:        return 'F';
 5495:     } elsif ($result =~ /^[^:]+:guest_/) {
 5496:        return 'A';
 5497:     }
 5498:     return '';
 5499: }
 5500: 
 5501: sub get_portfolio_access {
 5502:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 5503: 
 5504:     if (!ref($access_hash)) {
 5505: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 5506: 	my %access_controls = &get_access_controls($current_perms,$group,
 5507: 						   $file_name);
 5508: 	$access_hash = $access_controls{$file_name};
 5509:     }
 5510: 
 5511:     my ($public,$guest,@domains,@users,@courses,@groups);
 5512:     my $now = time;
 5513:     if (ref($access_hash) eq 'HASH') {
 5514:         foreach my $key (keys(%{$access_hash})) {
 5515:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 5516:             if ($start > $now) {
 5517:                 next;
 5518:             }
 5519:             if ($end && $end<$now) {
 5520:                 next;
 5521:             }
 5522:             if ($scope eq 'public') {
 5523:                 $public = $key;
 5524:                 last;
 5525:             } elsif ($scope eq 'guest') {
 5526:                 $guest = $key;
 5527:             } elsif ($scope eq 'domains') {
 5528:                 push(@domains,$key);
 5529:             } elsif ($scope eq 'users') {
 5530:                 push(@users,$key);
 5531:             } elsif ($scope eq 'course') {
 5532:                 push(@courses,$key);
 5533:             } elsif ($scope eq 'group') {
 5534:                 push(@groups,$key);
 5535:             }
 5536:         }
 5537:         if ($public) {
 5538:             return 'ok';
 5539:         }
 5540:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 5541:             if ($guest) {
 5542:                 return $guest;
 5543:             }
 5544:         } else {
 5545:             if (@domains > 0) {
 5546:                 foreach my $domkey (@domains) {
 5547:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 5548:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 5549:                             return 'ok';
 5550:                         }
 5551:                     }
 5552:                 }
 5553:             }
 5554:             if (@users > 0) {
 5555:                 foreach my $userkey (@users) {
 5556:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 5557:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 5558:                             if (ref($item) eq 'HASH') {
 5559:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 5560:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 5561:                                     return 'ok';
 5562:                                 }
 5563:                             }
 5564:                         }
 5565:                     } 
 5566:                 }
 5567:             }
 5568:             my %roleshash;
 5569:             my @courses_and_groups = @courses;
 5570:             push(@courses_and_groups,@groups); 
 5571:             if (@courses_and_groups > 0) {
 5572:                 my (%allgroups,%allroles); 
 5573:                 my ($start,$end,$role,$sec,$group);
 5574:                 foreach my $envkey (%env) {
 5575:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 5576:                         my $cid = $2.'_'.$3; 
 5577:                         if ($1 eq 'gr') {
 5578:                             $group = $4;
 5579:                             $allgroups{$cid}{$group} = $env{$envkey};
 5580:                         } else {
 5581:                             if ($4 eq '') {
 5582:                                 $sec = 'none';
 5583:                             } else {
 5584:                                 $sec = $4;
 5585:                             }
 5586:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 5587:                         }
 5588:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 5589:                         my $cid = $2.'_'.$3;
 5590:                         if ($4 eq '') {
 5591:                             $sec = 'none';
 5592:                         } else {
 5593:                             $sec = $4;
 5594:                         }
 5595:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 5596:                     }
 5597:                 }
 5598:                 if (keys(%allroles) == 0) {
 5599:                     return;
 5600:                 }
 5601:                 foreach my $key (@courses_and_groups) {
 5602:                     my %content = %{$$access_hash{$key}};
 5603:                     my $cnum = $content{'number'};
 5604:                     my $cdom = $content{'domain'};
 5605:                     my $cid = $cdom.'_'.$cnum;
 5606:                     if (!exists($allroles{$cid})) {
 5607:                         next;
 5608:                     }    
 5609:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 5610:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 5611:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 5612:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 5613:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 5614:                         foreach my $role (keys(%{$allroles{$cid}})) {
 5615:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 5616:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 5617:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 5618:                                         if (grep/^all$/,@sections) {
 5619:                                             return 'ok';
 5620:                                         } else {
 5621:                                             if (grep/^$sec$/,@sections) {
 5622:                                                 return 'ok';
 5623:                                             }
 5624:                                         }
 5625:                                     }
 5626:                                 }
 5627:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 5628:                                     if (grep/^none$/,@groups) {
 5629:                                         return 'ok';
 5630:                                     }
 5631:                                 } else {
 5632:                                     if (grep/^all$/,@groups) {
 5633:                                         return 'ok';
 5634:                                     } 
 5635:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 5636:                                         if (grep/^$group$/,@groups) {
 5637:                                             return 'ok';
 5638:                                         }
 5639:                                     }
 5640:                                 } 
 5641:                             }
 5642:                         }
 5643:                     }
 5644:                 }
 5645:             }
 5646:             if ($guest) {
 5647:                 return $guest;
 5648:             }
 5649:         }
 5650:     }
 5651:     return;
 5652: }
 5653: 
 5654: sub course_group_datechecker {
 5655:     my ($dates,$now,$status) = @_;
 5656:     my ($start,$end) = split(/\./,$dates);
 5657:     if (!$start && !$end) {
 5658:         return 'ok';
 5659:     }
 5660:     if (grep/^active$/,@{$status}) {
 5661:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 5662:             return 'ok';
 5663:         }
 5664:     }
 5665:     if (grep/^previous$/,@{$status}) {
 5666:         if ($end > $now ) {
 5667:             return 'ok';
 5668:         }
 5669:     }
 5670:     if (grep/^future$/,@{$status}) {
 5671:         if ($start > $now) {
 5672:             return 'ok';
 5673:         }
 5674:     }
 5675:     return; 
 5676: }
 5677: 
 5678: sub parse_portfolio_url {
 5679:     my ($url) = @_;
 5680: 
 5681:     my ($type,$udom,$unum,$group,$file_name);
 5682:     
 5683:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 5684: 	$type = 1;
 5685:         $udom = $1;
 5686:         $unum = $2;
 5687:         $file_name = $3;
 5688:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 5689: 	$type = 2;
 5690:         $udom = $1;
 5691:         $unum = $2;
 5692:         $group = $3;
 5693:         $file_name = $3.'/'.$4;
 5694:     }
 5695:     if (wantarray) {
 5696: 	return ($type,$udom,$unum,$file_name,$group);
 5697:     }
 5698:     return $type;
 5699: }
 5700: 
 5701: sub is_portfolio_url {
 5702:     my ($url) = @_;
 5703:     return scalar(&parse_portfolio_url($url));
 5704: }
 5705: 
 5706: sub is_portfolio_file {
 5707:     my ($file) = @_;
 5708:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 5709:         return 1;
 5710:     }
 5711:     return;
 5712: }
 5713: 
 5714: sub usertools_access {
 5715:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 5716:     my ($access,%tools);
 5717:     if ($context eq '') {
 5718:         $context = 'tools';
 5719:     }
 5720:     if ($context eq 'requestcourses') {
 5721:         %tools = (
 5722:                       official   => 1,
 5723:                       unofficial => 1,
 5724:                       community  => 1,
 5725:                  );
 5726:     } elsif ($context eq 'requestauthor') {
 5727:         %tools = (
 5728:                       requestauthor => 1,
 5729:                  );
 5730:     } else {
 5731:         %tools = (
 5732:                       aboutme   => 1,
 5733:                       blog      => 1,
 5734:                       webdav    => 1,
 5735:                       portfolio => 1,
 5736:                  );
 5737:     }
 5738:     return if (!defined($tools{$tool}));
 5739: 
 5740:     if ((!defined($udom)) || (!defined($uname))) {
 5741:         $udom = $env{'user.domain'};
 5742:         $uname = $env{'user.name'};
 5743:     }
 5744: 
 5745:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 5746:         if ($action ne 'reload') {
 5747:             if ($context eq 'requestcourses') {
 5748:                 return $env{'environment.canrequest.'.$tool};
 5749:             } elsif ($context eq 'requestauthor') {
 5750:                 return $env{'environment.canrequest.author'};
 5751:             } else {
 5752:                 return $env{'environment.availabletools.'.$tool};
 5753:             }
 5754:         }
 5755:     }
 5756: 
 5757:     my ($toolstatus,$inststatus,$envkey);
 5758:     if ($context eq 'requestauthor') {
 5759:         $envkey = $context; 
 5760:     } else {
 5761:         $envkey = $context.'.'.$tool;
 5762:     }
 5763: 
 5764:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 5765:          ($action ne 'reload')) {
 5766:         $toolstatus = $env{'environment.'.$envkey};
 5767:         $inststatus = $env{'environment.inststatus'};
 5768:     } else {
 5769:         if (ref($userenvref) eq 'HASH') {
 5770:             $toolstatus = $userenvref->{$envkey};
 5771:             $inststatus = $userenvref->{'inststatus'};
 5772:         } else {
 5773:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 5774:             $toolstatus = $userenv{$envkey};
 5775:             $inststatus = $userenv{'inststatus'};
 5776:         }
 5777:     }
 5778: 
 5779:     if ($toolstatus ne '') {
 5780:         if ($toolstatus) {
 5781:             $access = 1;
 5782:         } else {
 5783:             $access = 0;
 5784:         }
 5785:         return $access;
 5786:     }
 5787: 
 5788:     my ($is_adv,%domdef);
 5789:     if (ref($is_advref) eq 'HASH') {
 5790:         $is_adv = $is_advref->{'is_adv'};
 5791:     } else {
 5792:         $is_adv = &is_advanced_user($udom,$uname);
 5793:     }
 5794:     if (ref($domdefref) eq 'HASH') {
 5795:         %domdef = %{$domdefref};
 5796:     } else {
 5797:         %domdef = &get_domain_defaults($udom);
 5798:     }
 5799:     if (ref($domdef{$tool}) eq 'HASH') {
 5800:         if ($is_adv) {
 5801:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 5802:                 if ($domdef{$tool}{'_LC_adv'}) { 
 5803:                     $access = 1;
 5804:                 } else {
 5805:                     $access = 0;
 5806:                 }
 5807:                 return $access;
 5808:             }
 5809:         }
 5810:         if ($inststatus ne '') {
 5811:             my ($hasaccess,$hasnoaccess);
 5812:             foreach my $affiliation (split(/:/,$inststatus)) {
 5813:                 if ($domdef{$tool}{$affiliation} ne '') { 
 5814:                     if ($domdef{$tool}{$affiliation}) {
 5815:                         $hasaccess = 1;
 5816:                     } else {
 5817:                         $hasnoaccess = 1;
 5818:                     }
 5819:                 }
 5820:             }
 5821:             if ($hasaccess || $hasnoaccess) {
 5822:                 if ($hasaccess) {
 5823:                     $access = 1;
 5824:                 } elsif ($hasnoaccess) {
 5825:                     $access = 0; 
 5826:                 }
 5827:                 return $access;
 5828:             }
 5829:         } else {
 5830:             if ($domdef{$tool}{'default'} ne '') {
 5831:                 if ($domdef{$tool}{'default'}) {
 5832:                     $access = 1;
 5833:                 } elsif ($domdef{$tool}{'default'} == 0) {
 5834:                     $access = 0;
 5835:                 }
 5836:                 return $access;
 5837:             }
 5838:         }
 5839:     } else {
 5840:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 5841:             $access = 1;
 5842:         } else {
 5843:             $access = 0;
 5844:         }
 5845:         return $access;
 5846:     }
 5847: }
 5848: 
 5849: sub is_course_owner {
 5850:     my ($cdom,$cnum,$udom,$uname) = @_;
 5851:     if (($udom eq '') || ($uname eq '')) {
 5852:         $udom = $env{'user.domain'};
 5853:         $uname = $env{'user.name'};
 5854:     }
 5855:     unless (($udom eq '') || ($uname eq '')) {
 5856:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 5857:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 5858:                 return 1;
 5859:             } else {
 5860:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 5861:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 5862:                     return 1;
 5863:                 }
 5864:             }
 5865:         }
 5866:     }
 5867:     return;
 5868: }
 5869: 
 5870: sub is_advanced_user {
 5871:     my ($udom,$uname) = @_;
 5872:     if ($udom ne '' && $uname ne '') {
 5873:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 5874:             if (wantarray) {
 5875:                 return ($env{'user.adv'},$env{'user.author'});
 5876:             } else {
 5877:                 return $env{'user.adv'};
 5878:             }
 5879:         }
 5880:     }
 5881:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 5882:     my %allroles;
 5883:     my ($is_adv,$is_author);
 5884:     foreach my $role (keys(%roleshash)) {
 5885:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 5886:         my $area = '/'.$tdomain.'/'.$trest;
 5887:         if ($sec ne '') {
 5888:             $area .= '/'.$sec;
 5889:         }
 5890:         if (($area ne '') && ($trole ne '')) {
 5891:             my $spec=$trole.'.'.$area;
 5892:             if ($trole =~ /^cr\//) {
 5893:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 5894:             } elsif ($trole ne 'gr') {
 5895:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 5896:             }
 5897:             if ($trole eq 'au') {
 5898:                 $is_author = 1;
 5899:             }
 5900:         }
 5901:     }
 5902:     foreach my $role (keys(%allroles)) {
 5903:         last if ($is_adv);
 5904:         foreach my $item (split(/:/,$allroles{$role})) {
 5905:             if ($item ne '') {
 5906:                 my ($privilege,$restrictions)=split(/&/,$item);
 5907:                 if ($privilege eq 'adv') {
 5908:                     $is_adv = 1;
 5909:                     last;
 5910:                 }
 5911:             }
 5912:         }
 5913:     }
 5914:     if (wantarray) {
 5915:         return ($is_adv,$is_author);
 5916:     }
 5917:     return $is_adv;
 5918: }
 5919: 
 5920: sub check_can_request {
 5921:     my ($dom,$can_request,$request_domains) = @_;
 5922:     my $canreq = 0;
 5923:     my ($types,$typename) = &Apache::loncommon::course_types();
 5924:     my @options = ('approval','validate','autolimit');
 5925:     my $optregex = join('|',@options);
 5926:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 5927:         foreach my $type (@{$types}) {
 5928:             if (&usertools_access($env{'user.name'},
 5929:                                   $env{'user.domain'},
 5930:                                   $type,undef,'requestcourses')) {
 5931:                 $canreq ++;
 5932:                 if (ref($request_domains) eq 'HASH') {
 5933:                     push(@{$request_domains->{$type}},$env{'user.domain'});
 5934:                 }
 5935:                 if ($dom eq $env{'user.domain'}) {
 5936:                     $can_request->{$type} = 1;
 5937:                 }
 5938:             }
 5939:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
 5940:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 5941:                 if (@curr > 0) {
 5942:                     foreach my $item (@curr) {
 5943:                         if (ref($request_domains) eq 'HASH') {
 5944:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 5945:                             if ($otherdom ne '') {
 5946:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 5947:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 5948:                                         push(@{$request_domains->{$type}},$otherdom);
 5949:                                     }
 5950:                                 } else {
 5951:                                     push(@{$request_domains->{$type}},$otherdom);
 5952:                                 }
 5953:                             }
 5954:                         }
 5955:                     }
 5956:                     unless($dom eq $env{'user.domain'}) {
 5957:                         $canreq ++;
 5958:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 5959:                             $can_request->{$type} = 1;
 5960:                         }
 5961:                     }
 5962:                 }
 5963:             }
 5964:         }
 5965:     }
 5966:     return $canreq;
 5967: }
 5968: 
 5969: # ---------------------------------------------- Custom access rule evaluation
 5970: 
 5971: sub customaccess {
 5972:     my ($priv,$uri)=@_;
 5973:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 5974:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 5975:     $udom = &LONCAPA::clean_domain($udom);
 5976:     $ucrs = &LONCAPA::clean_username($ucrs);
 5977:     my $access=0;
 5978:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 5979: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 5980: 	if ($type eq 'user') {
 5981: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 5982: 		my ($tdom,$tuname)=split(m{/},$scope);
 5983: 		if ($tdom) {
 5984: 		    if ($tdom ne $env{'user.domain'}) { next; }
 5985: 		}
 5986: 		if ($tuname) {
 5987: 		    if ($tuname ne $env{'user.name'}) { next; }
 5988: 		}
 5989: 		$access=($effect eq 'allow');
 5990: 		last;
 5991: 	    }
 5992: 	} else {
 5993: 	    if ($role) {
 5994: 		if ($role ne $urole) { next; }
 5995: 	    }
 5996: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 5997: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 5998: 		if ($tdom) {
 5999: 		    if ($tdom ne $udom) { next; }
 6000: 		}
 6001: 		if ($tcrs) {
 6002: 		    if ($tcrs ne $ucrs) { next; }
 6003: 		}
 6004: 		if ($tsec) {
 6005: 		    if ($tsec ne $usec) { next; }
 6006: 		}
 6007: 		$access=($effect eq 'allow');
 6008: 		last;
 6009: 	    }
 6010: 	    if ($realm eq '' && $role eq '') {
 6011: 		$access=($effect eq 'allow');
 6012: 	    }
 6013: 	}
 6014:     }
 6015:     return $access;
 6016: }
 6017: 
 6018: # ------------------------------------------------- Check for a user privilege
 6019: 
 6020: sub allowed {
 6021:     my ($priv,$uri,$symb,$role)=@_;
 6022:     my $ver_orguri=$uri;
 6023:     $uri=&deversion($uri);
 6024:     my $orguri=$uri;
 6025:     $uri=&declutter($uri);
 6026: 
 6027:     if ($priv eq 'evb') {
 6028: # Evade communication block restrictions for specified role in a course
 6029:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 6030:             return $1;
 6031:         } else {
 6032:             return;
 6033:         }
 6034:     }
 6035: 
 6036:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 6037: # Free bre access to adm and meta resources
 6038:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 6039: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 6040: 	&& ($priv eq 'bre')) {
 6041: 	return 'F';
 6042:     }
 6043: 
 6044: # Free bre access to user's own portfolio contents
 6045:     my ($space,$domain,$name,@dir)=split('/',$uri);
 6046:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 6047: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 6048:         my %setters;
 6049:         my ($startblock,$endblock) = 
 6050:             &Apache::loncommon::blockcheck(\%setters,'port');
 6051:         if ($startblock && $endblock) {
 6052:             return 'B';
 6053:         } else {
 6054:             return 'F';
 6055:         }
 6056:     }
 6057: 
 6058: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 6059:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 6060:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 6061:         if (exists($env{'request.course.id'})) {
 6062:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6063:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6064:             if (($domain eq $cdom) && ($name eq $cnum)) {
 6065:                 my $courseprivid=$env{'request.course.id'};
 6066:                 $courseprivid=~s/\_/\//;
 6067:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 6068:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 6069:                     return $1; 
 6070:                 } else {
 6071:                     if ($env{'request.course.sec'}) {
 6072:                         $courseprivid.='/'.$env{'request.course.sec'};
 6073:                     }
 6074:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 6075:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 6076:                         return $2;
 6077:                     }
 6078:                 }
 6079:             }
 6080:         }
 6081:     }
 6082: 
 6083: # Free bre to public access
 6084: 
 6085:     if ($priv eq 'bre') {
 6086:         my $copyright=&metadata($uri,'copyright');
 6087: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 6088:            return 'F'; 
 6089:         }
 6090:         if ($copyright eq 'priv') {
 6091:             $uri=~/([^\/]+)\/([^\/]+)\//;
 6092: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 6093: 		return '';
 6094:             }
 6095:         }
 6096:         if ($copyright eq 'domain') {
 6097:             $uri=~/([^\/]+)\/([^\/]+)\//;
 6098: 	    unless (($env{'user.domain'} eq $1) ||
 6099:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 6100: 		return '';
 6101:             }
 6102:         }
 6103:         if ($env{'request.role'}=~ /li\.\//) {
 6104:             # Library role, so allow browsing of resources in this domain.
 6105:             return 'F';
 6106:         }
 6107:         if ($copyright eq 'custom') {
 6108: 	    unless (&customaccess($priv,$uri)) { return ''; }
 6109:         }
 6110:     }
 6111:     # Domain coordinator is trying to create a course
 6112:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 6113:         # uri is the requested domain in this case.
 6114:         # comparison to 'request.role.domain' shows if the user has selected
 6115:         # a role of dc for the domain in question.
 6116:         return 'F' if ($uri eq $env{'request.role.domain'});
 6117:     }
 6118: 
 6119:     my $thisallowed='';
 6120:     my $statecond=0;
 6121:     my $courseprivid='';
 6122: 
 6123:     my $ownaccess;
 6124:     # Community Coordinator or Assistant Co-author browsing resource space.
 6125:     if (($priv eq 'bro') && ($env{'user.author'})) {
 6126:         if ($uri eq '') {
 6127:             $ownaccess = 1;
 6128:         } else {
 6129:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 6130:                 my $udom = $env{'user.domain'};
 6131:                 my $uname = $env{'user.name'};
 6132:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 6133:                     $ownaccess = 1;
 6134:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 6135:                     unless ($uri =~ m{\.\./}) {
 6136:                         $ownaccess = 1;
 6137:                     }
 6138:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 6139:                     my $now = time;
 6140:                     if ($uri =~ m{^([^/]+)/?$}) {
 6141:                         my $adom = $1;
 6142:                         foreach my $key (keys(%env)) {
 6143:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 6144:                                 my ($start,$end) = split('.',$env{$key});
 6145:                                 if (($now >= $start) && (!$end || $end < $now)) {
 6146:                                     $ownaccess = 1;
 6147:                                     last;
 6148:                                 }
 6149:                             }
 6150:                         }
 6151:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 6152:                         my $adom = $1;
 6153:                         my $aname = $2;
 6154:                         foreach my $role ('ca','aa') { 
 6155:                             if ($env{"user.role.$role./$adom/$aname"}) {
 6156:                                 my ($start,$end) =
 6157:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 6158:                                 if (($now >= $start) && (!$end || $end < $now)) {
 6159:                                     $ownaccess = 1;
 6160:                                     last;
 6161:                                 }
 6162:                             }
 6163:                         }
 6164:                     }
 6165:                 }
 6166:             }
 6167:         }
 6168:     }
 6169: 
 6170: # Course
 6171: 
 6172:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 6173:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6174:             $thisallowed.=$1;
 6175:         }
 6176:     }
 6177: 
 6178: # Domain
 6179: 
 6180:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 6181:        =~/\Q$priv\E\&([^\:]*)/) {
 6182:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6183:             $thisallowed.=$1;
 6184:         }
 6185:     }
 6186: 
 6187: # User who is not author or co-author might still be able to edit
 6188: # resource of an author in the domain (e.g., if Domain Coordinator).
 6189:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 6190:         (&allowed('mdc',$env{'request.course.id'}))) {
 6191:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 6192:             $thisallowed.=$1;
 6193:         }
 6194:     }
 6195: 
 6196: # Course: uri itself is a course
 6197:     my $courseuri=$uri;
 6198:     $courseuri=~s/\_(\d)/\/$1/;
 6199:     $courseuri=~s/^([^\/])/\/$1/;
 6200: 
 6201:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 6202:        =~/\Q$priv\E\&([^\:]*)/) {
 6203:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6204:             $thisallowed.=$1;
 6205:         }
 6206:     }
 6207: 
 6208: # URI is an uploaded document for this course, default permissions don't matter
 6209: # not allowing 'edit' access (editupload) to uploaded course docs
 6210:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 6211: 	$thisallowed='';
 6212:         my ($match)=&is_on_map($uri);
 6213:         if ($match) {
 6214:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 6215:                   =~/\Q$priv\E\&([^\:]*)/) {
 6216:                 my @blockers = &has_comm_blocking($priv,$symb,$uri);
 6217:                 if (@blockers > 0) {
 6218:                     $thisallowed = 'B';
 6219:                 } else {
 6220:                     $thisallowed.=$1;
 6221:                 }
 6222:             }
 6223:         } else {
 6224:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 6225:             if ($refuri) {
 6226:                 if ($refuri =~ m|^/adm/|) {
 6227:                     $thisallowed='F';
 6228:                 } else {
 6229:                     $refuri=&declutter($refuri);
 6230:                     my ($match) = &is_on_map($refuri);
 6231:                     if ($match) {
 6232:                         my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 6233:                         if (@blockers > 0) {
 6234:                             $thisallowed = 'B';
 6235:                         } else {
 6236:                             $thisallowed='F';
 6237:                         }
 6238:                     }
 6239:                 }
 6240:             }
 6241:         }
 6242:     }
 6243: 
 6244:     if ($priv eq 'bre'
 6245: 	&& $thisallowed ne 'F' 
 6246: 	&& $thisallowed ne '2'
 6247: 	&& &is_portfolio_url($uri)) {
 6248: 	$thisallowed = &portfolio_access($uri);
 6249:     }
 6250:     
 6251: # Full access at system, domain or course-wide level? Exit.
 6252:     if ($thisallowed=~/F/) {
 6253: 	return 'F';
 6254:     }
 6255: 
 6256: # If this is generating or modifying users, exit with special codes
 6257: 
 6258:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 6259: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 6260: 	    my ($audom,$auname)=split('/',$uri);
 6261: # no author name given, so this just checks on the general right to make a co-author in this domain
 6262: 	    unless ($auname) { return $thisallowed; }
 6263: # an author name is given, so we are about to actually make a co-author for a certain account
 6264: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 6265: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 6266: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 6267: 	}
 6268: 	return $thisallowed;
 6269:     }
 6270: #
 6271: # Gathered so far: system, domain and course wide privileges
 6272: #
 6273: # Course: See if uri or referer is an individual resource that is part of 
 6274: # the course
 6275: 
 6276:     if ($env{'request.course.id'}) {
 6277: 
 6278:        $courseprivid=$env{'request.course.id'};
 6279:        if ($env{'request.course.sec'}) {
 6280:           $courseprivid.='/'.$env{'request.course.sec'};
 6281:        }
 6282:        $courseprivid=~s/\_/\//;
 6283:        my $checkreferer=1;
 6284:        my ($match,$cond)=&is_on_map($uri);
 6285:        if ($match) {
 6286:            $statecond=$cond;
 6287:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 6288:                =~/\Q$priv\E\&([^\:]*)/) {
 6289:                my $value = $1;
 6290:                if ($priv eq 'bre') {
 6291:                    my @blockers = &has_comm_blocking($priv,$symb,$uri);
 6292:                    if (@blockers > 0) {
 6293:                        $thisallowed = 'B';
 6294:                    } else {
 6295:                        $thisallowed.=$value;
 6296:                    }
 6297:                } else {
 6298:                    $thisallowed.=$value;
 6299:                }
 6300:                $checkreferer=0;
 6301:            }
 6302:        }
 6303:        
 6304:        if ($checkreferer) {
 6305: 	  my $refuri=$env{'httpref.'.$orguri};
 6306:             unless ($refuri) {
 6307:                 foreach my $key (keys(%env)) {
 6308: 		    if ($key=~/^httpref\..*\*/) {
 6309: 			my $pattern=$key;
 6310:                         $pattern=~s/^httpref\.\/res\///;
 6311:                         $pattern=~s/\*/\[\^\/\]\+/g;
 6312:                         $pattern=~s/\//\\\//g;
 6313:                         if ($orguri=~/$pattern/) {
 6314: 			    $refuri=$env{$key};
 6315:                         }
 6316:                     }
 6317:                 }
 6318:             }
 6319: 
 6320:          if ($refuri) { 
 6321: 	  $refuri=&declutter($refuri);
 6322:           my ($match,$cond)=&is_on_map($refuri);
 6323:             if ($match) {
 6324:               my $refstatecond=$cond;
 6325:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 6326:                   =~/\Q$priv\E\&([^\:]*)/) {
 6327:                   my $value = $1;
 6328:                   if ($priv eq 'bre') {
 6329:                       my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 6330:                       if (@blockers > 0) {
 6331:                           $thisallowed = 'B';
 6332:                       } else {
 6333:                           $thisallowed.=$value;
 6334:                       }
 6335:                   } else {
 6336:                       $thisallowed.=$value;
 6337:                   }
 6338:                   $uri=$refuri;
 6339:                   $statecond=$refstatecond;
 6340:               }
 6341:           }
 6342:         }
 6343:        }
 6344:    }
 6345: 
 6346: #
 6347: # Gathered now: all privileges that could apply, and condition number
 6348: # 
 6349: #
 6350: # Full or no access?
 6351: #
 6352: 
 6353:     if ($thisallowed=~/F/) {
 6354: 	return 'F';
 6355:     }
 6356: 
 6357:     unless ($thisallowed) {
 6358:         return '';
 6359:     }
 6360: 
 6361: # Restrictions exist, deal with them
 6362: #
 6363: #   C:according to course preferences
 6364: #   R:according to resource settings
 6365: #   L:unless locked
 6366: #   X:according to user session state
 6367: #
 6368: 
 6369: # Possibly locked functionality, check all courses
 6370: # Locks might take effect only after 10 minutes cache expiration for other
 6371: # courses, and 2 minutes for current course
 6372: 
 6373:     my $envkey;
 6374:     if ($thisallowed=~/L/) {
 6375:         foreach $envkey (keys(%env)) {
 6376:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 6377:                my $courseid=$2;
 6378:                my $roleid=$1.'.'.$2;
 6379:                $courseid=~s/^\///;
 6380:                my $expiretime=600;
 6381:                if ($env{'request.role'} eq $roleid) {
 6382: 		  $expiretime=120;
 6383:                }
 6384: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 6385:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 6386:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 6387: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 6388:                }
 6389:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 6390:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 6391: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 6392:                        &log($env{'user.domain'},$env{'user.name'},
 6393:                             $env{'user.home'},
 6394:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 6395:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 6396:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 6397: 		       return '';
 6398:                    }
 6399:                }
 6400:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 6401:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 6402: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 6403:                        &log($env{'user.domain'},$env{'user.name'},
 6404:                             $env{'user.home'},
 6405:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 6406:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 6407:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 6408: 		       return '';
 6409:                    }
 6410:                }
 6411: 	   }
 6412:        }
 6413:     }
 6414:    
 6415: #
 6416: # Rest of the restrictions depend on selected course
 6417: #
 6418: 
 6419:     unless ($env{'request.course.id'}) {
 6420: 	if ($thisallowed eq 'A') {
 6421: 	    return 'A';
 6422:         } elsif ($thisallowed eq 'B') {
 6423:             return 'B';
 6424: 	} else {
 6425: 	    return '1';
 6426: 	}
 6427:     }
 6428: 
 6429: #
 6430: # Now user is definitely in a course
 6431: #
 6432: 
 6433: 
 6434: # Course preferences
 6435: 
 6436:    if ($thisallowed=~/C/) {
 6437:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 6438:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 6439:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 6440: 	   =~/\Q$rolecode\E/) {
 6441: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6442: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 6443: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 6444: 			$env{'request.course.id'});
 6445: 	   }
 6446:            return '';
 6447:        }
 6448: 
 6449:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 6450: 	   =~/\Q$unamedom\E/) {
 6451: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6452: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 6453: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 6454: 			$env{'request.course.id'});
 6455: 	   }
 6456:            return '';
 6457:        }
 6458:    }
 6459: 
 6460: # Resource preferences
 6461: 
 6462:    if ($thisallowed=~/R/) {
 6463:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 6464:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 6465: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6466: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 6467: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 6468: 	   }
 6469: 	   return '';
 6470:        }
 6471:    }
 6472: 
 6473: # Restricted by state or randomout?
 6474: 
 6475:    if ($thisallowed=~/X/) {
 6476:       if ($env{'acc.randomout'}) {
 6477: 	 if (!$symb) { $symb=&symbread($uri,1); }
 6478:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 6479:             return ''; 
 6480:          }
 6481:       }
 6482:       if (&condval($statecond)) {
 6483: 	 return '2';
 6484:       } else {
 6485:          return '';
 6486:       }
 6487:    }
 6488: 
 6489:     if ($thisallowed eq 'A') {
 6490: 	return 'A';
 6491:     } elsif ($thisallowed eq 'B') {
 6492:         return 'B';
 6493:     }
 6494:    return 'F';
 6495: }
 6496: 
 6497: sub get_comm_blocks {
 6498:     my ($cdom,$cnum) = @_;
 6499:     if ($cdom eq '' || $cnum eq '') {
 6500:         return unless ($env{'request.course.id'});
 6501:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6502:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6503:     }
 6504:     my %commblocks;
 6505:     my $hashid=$cdom.'_'.$cnum;
 6506:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 6507:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 6508:         %commblocks = %{$blocksref};
 6509:     } else {
 6510:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 6511:         my $cachetime = 600;
 6512:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 6513:     }
 6514:     return %commblocks;
 6515: }
 6516: 
 6517: sub has_comm_blocking {
 6518:     my ($priv,$symb,$uri,$blocks) = @_;
 6519:     return unless ($env{'request.course.id'});
 6520:     return unless ($priv eq 'bre');
 6521:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 6522:     my %commblocks;
 6523:     if (ref($blocks) eq 'HASH') {
 6524:         %commblocks = %{$blocks};
 6525:     } else {
 6526:         %commblocks = &get_comm_blocks();
 6527:     }
 6528:     return unless (keys(%commblocks) > 0);
 6529:     if (!$symb) { $symb=&symbread($uri,1); }
 6530:     my ($map,$resid,undef)=&decode_symb($symb);
 6531:     my %tocheck = (
 6532:                     maps      => $map,
 6533:                     resources => $symb,
 6534:                   );
 6535:     my @blockers;
 6536:     my $now = time;
 6537:     my $navmap = Apache::lonnavmaps::navmap->new();
 6538:     foreach my $block (keys(%commblocks)) {
 6539:         if ($block =~ /^(\d+)____(\d+)$/) {
 6540:             my ($start,$end) = ($1,$2);
 6541:             if ($start <= $now && $end >= $now) {
 6542:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 6543:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 6544:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 6545:                             if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
 6546:                                 unless (grep(/^\Q$block\E$/,@blockers)) {
 6547:                                     push(@blockers,$block);
 6548:                                 }
 6549:                             }
 6550:                         }
 6551:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 6552:                             if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
 6553:                                 unless (grep(/^\Q$block\E$/,@blockers)) {  
 6554:                                     push(@blockers,$block);
 6555:                                 }
 6556:                             }
 6557:                         }
 6558:                     }
 6559:                 }
 6560:             }
 6561:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 6562:             my $item = $1;
 6563:             my @to_test;
 6564:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 6565:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 6566:                     my $check_interval;
 6567:                     if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
 6568:                         my @interval;
 6569:                         my $type = 'map';
 6570:                         if ($item eq 'course') {
 6571:                             $type = 'course';
 6572:                             @interval=&EXT("resource.0.interval");
 6573:                         } else {
 6574:                             if ($item =~ /___\d+___/) {
 6575:                                 $type = 'resource';
 6576:                                 @interval=&EXT("resource.0.interval",$item);
 6577:                                 if (ref($navmap)) {                        
 6578:                                     my $res = $navmap->getBySymb($item); 
 6579:                                     push(@to_test,$res);
 6580:                                 }
 6581:                             } else {
 6582:                                 my $mapsymb = &symbread($item,1);
 6583:                                 if ($mapsymb) {
 6584:                                     if (ref($navmap)) {
 6585:                                         my $mapres = $navmap->getBySymb($mapsymb);
 6586:                                         @to_test = $mapres->retrieveResources($mapres,undef,0,1);
 6587:                                         foreach my $res (@to_test) {
 6588:                                             my $symb = $res->symb();
 6589:                                             next if ($symb eq $mapsymb);
 6590:                                             if ($symb ne '') {
 6591:                                                 @interval=&EXT("resource.0.interval",$symb);
 6592:                                                 last;
 6593:                                             }
 6594:                                         }
 6595:                                     }
 6596:                                 }
 6597:                             }
 6598:                         }
 6599:                         if ($interval[0] =~ /\d+/) {
 6600:                             my $first_access;
 6601:                             if ($type eq 'resource') {
 6602:                                 $first_access=&get_first_access($interval[1],$item);
 6603:                             } elsif ($type eq 'map') {
 6604:                                 $first_access=&get_first_access($interval[1],undef,$item);
 6605:                             } else {
 6606:                                 $first_access=&get_first_access($interval[1]);
 6607:                             }
 6608:                             if ($first_access) {
 6609:                                 my $timesup = $first_access+$interval[0];
 6610:                                 if ($timesup > $now) {
 6611:                                     foreach my $res (@to_test) {
 6612:                                         if ($res->is_problem()) {
 6613:                                             if ($res->completable()) {
 6614:                                                 unless (grep(/^\Q$block\E$/,@blockers)) {
 6615:                                                     push(@blockers,$block);
 6616:                                                 }
 6617:                                                 last;
 6618:                                             }
 6619:                                         }
 6620:                                     }
 6621:                                 }
 6622:                             }
 6623:                         }
 6624:                     }
 6625:                 }
 6626:             }
 6627:         }
 6628:     }
 6629:     return @blockers;
 6630: }
 6631: 
 6632: sub check_docs_block {
 6633:     my ($docsblock,$tocheck) =@_;
 6634:     if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
 6635:         return;
 6636:     }
 6637:     if (ref($docsblock->{'maps'}) eq 'HASH') {
 6638:         if ($tocheck->{'maps'}) {
 6639:             if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
 6640:                 return 1;
 6641:             }
 6642:         }
 6643:     }
 6644:     if (ref($docsblock->{'resources'}) eq 'HASH') {
 6645:         if ($tocheck->{'resources'}) {
 6646:             if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
 6647:                 return 1;
 6648:             }
 6649:         }
 6650:     }
 6651:     return;
 6652: }
 6653: 
 6654: #
 6655: #   Removes the versino from a URI and
 6656: #   splits it in to its filename and path to the filename.
 6657: #   Seems like File::Basename could have done this more clearly.
 6658: #   Parameters:
 6659: #      $uri   - input URI
 6660: #   Returns:
 6661: #     Two element list consisting of 
 6662: #     $pathname  - the URI up to and excluding the trailing /
 6663: #     $filename  - The part of the URI following the last /
 6664: #  NOTE:
 6665: #    Another realization of this is simply:
 6666: #    use File::Basename;
 6667: #    ...
 6668: #    $uri = shift;
 6669: #    $filename = basename($uri);
 6670: #    $path     = dirname($uri);
 6671: #    return ($filename, $path);
 6672: #
 6673: #     The implementation below is probably faster however.
 6674: #
 6675: sub split_uri_for_cond {
 6676:     my $uri=&deversion(&declutter(shift));
 6677:     my @uriparts=split(/\//,$uri);
 6678:     my $filename=pop(@uriparts);
 6679:     my $pathname=join('/',@uriparts);
 6680:     return ($pathname,$filename);
 6681: }
 6682: # --------------------------------------------------- Is a resource on the map?
 6683: 
 6684: sub is_on_map {
 6685:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 6686:     #Trying to find the conditional for the file
 6687:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 6688: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 6689:     if ($match) {
 6690: 	return (1,$1);
 6691:     } else {
 6692: 	return (0,0);
 6693:     }
 6694: }
 6695: 
 6696: # --------------------------------------------------------- Get symb from alias
 6697: 
 6698: sub get_symb_from_alias {
 6699:     my $symb=shift;
 6700:     my ($map,$resid,$url)=&decode_symb($symb);
 6701: # Already is a symb
 6702:     if ($url) { return $symb; }
 6703: # Must be an alias
 6704:     my $aliassymb='';
 6705:     my %bighash;
 6706:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6707:                             &GDBM_READER(),0640)) {
 6708:         my $rid=$bighash{'mapalias_'.$symb};
 6709: 	if ($rid) {
 6710: 	    my ($mapid,$resid)=split(/\./,$rid);
 6711: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 6712: 				    $resid,$bighash{'src_'.$rid});
 6713: 	}
 6714:         untie %bighash;
 6715:     }
 6716:     return $aliassymb;
 6717: }
 6718: 
 6719: # ----------------------------------------------------------------- Define Role
 6720: 
 6721: sub definerole {
 6722:   if (allowed('mcr','/')) {
 6723:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 6724:     foreach my $role (split(':',$sysrole)) {
 6725: 	my ($crole,$cqual)=split(/\&/,$role);
 6726:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 6727:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 6728: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 6729:                return "refused:s:$crole&$cqual"; 
 6730:             }
 6731:         }
 6732:     }
 6733:     foreach my $role (split(':',$domrole)) {
 6734: 	my ($crole,$cqual)=split(/\&/,$role);
 6735:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 6736:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 6737: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 6738:                return "refused:d:$crole&$cqual"; 
 6739:             }
 6740:         }
 6741:     }
 6742:     foreach my $role (split(':',$courole)) {
 6743: 	my ($crole,$cqual)=split(/\&/,$role);
 6744:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 6745:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 6746: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 6747:                return "refused:c:$crole&$cqual"; 
 6748:             }
 6749:         }
 6750:     }
 6751:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 6752:                 "$env{'user.domain'}:$env{'user.name'}:".
 6753: 	        "rolesdef_$rolename=".
 6754:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 6755:     return reply($command,$env{'user.home'});
 6756:   } else {
 6757:     return 'refused';
 6758:   }
 6759: }
 6760: 
 6761: # ---------------- Make a metadata query against the network of library servers
 6762: 
 6763: sub metadata_query {
 6764:     my ($query,$custom,$customshow,$server_array)=@_;
 6765:     my %rhash;
 6766:     my %libserv = &all_library();
 6767:     my @server_list = (defined($server_array) ? @$server_array
 6768:                                               : keys(%libserv) );
 6769:     for my $server (@server_list) {
 6770: 	unless ($custom or $customshow) {
 6771: 	    my $reply=&reply("querysend:".&escape($query),$server);
 6772: 	    $rhash{$server}=$reply;
 6773: 	}
 6774: 	else {
 6775: 	    my $reply=&reply("querysend:".&escape($query).':'.
 6776: 			     &escape($custom).':'.&escape($customshow),
 6777: 			     $server);
 6778: 	    $rhash{$server}=$reply;
 6779: 	}
 6780:     }
 6781:     return \%rhash;
 6782: }
 6783: 
 6784: # ----------------------------------------- Send log queries and wait for reply
 6785: 
 6786: sub log_query {
 6787:     my ($uname,$udom,$query,%filters)=@_;
 6788:     my $uhome=&homeserver($uname,$udom);
 6789:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 6790:     my $uhost=&hostname($uhome);
 6791:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 6792:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 6793:                        $uhome);
 6794:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 6795:     return get_query_reply($queryid);
 6796: }
 6797: 
 6798: # -------------------------- Update MySQL table for portfolio file
 6799: 
 6800: sub update_portfolio_table {
 6801:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 6802:     if ($group ne '') {
 6803:         $file_name =~s /^\Q$group\E//;
 6804:     }
 6805:     my $homeserver = &homeserver($uname,$udom);
 6806:     my $queryid=
 6807:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 6808:                ':'.&escape($file_name).':'.$action,$homeserver);
 6809:     my $reply = &get_query_reply($queryid);
 6810:     return $reply;
 6811: }
 6812: 
 6813: # -------------------------- Update MySQL allusers table
 6814: 
 6815: sub update_allusers_table {
 6816:     my ($uname,$udom,$names) = @_;
 6817:     my $homeserver = &homeserver($uname,$udom);
 6818:     my $queryid=
 6819:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 6820:                'lastname='.&escape($names->{'lastname'}).'%%'.
 6821:                'firstname='.&escape($names->{'firstname'}).'%%'.
 6822:                'middlename='.&escape($names->{'middlename'}).'%%'.
 6823:                'generation='.&escape($names->{'generation'}).'%%'.
 6824:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 6825:                'id='.&escape($names->{'id'}),$homeserver);
 6826:     return;
 6827: }
 6828: 
 6829: # ------- Request retrieval of institutional classlists for course(s)
 6830: 
 6831: sub fetch_enrollment_query {
 6832:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 6833:     my $homeserver;
 6834:     my $maxtries = 1;
 6835:     if ($context eq 'automated') {
 6836:         $homeserver = $perlvar{'lonHostID'};
 6837:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 6838:     } else {
 6839:         $homeserver = &homeserver($cnum,$dom);
 6840:     }
 6841:     my $host=&hostname($homeserver);
 6842:     my $cmd = '';
 6843:     foreach my $affiliate (keys(%{$affiliatesref})) {
 6844:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 6845:     }
 6846:     $cmd =~ s/%%$//;
 6847:     $cmd = &escape($cmd);
 6848:     my $query = 'fetchenrollment';
 6849:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 6850:     unless ($queryid=~/^\Q$host\E\_/) { 
 6851:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 6852:         return 'error: '.$queryid;
 6853:     }
 6854:     my $reply = &get_query_reply($queryid);
 6855:     my $tries = 1;
 6856:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 6857:         $reply = &get_query_reply($queryid);
 6858:         $tries ++;
 6859:     }
 6860:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 6861:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 6862:     } else {
 6863:         my @responses = split(/:/,$reply);
 6864:         if ($homeserver eq $perlvar{'lonHostID'}) {
 6865:             foreach my $line (@responses) {
 6866:                 my ($key,$value) = split(/=/,$line,2);
 6867:                 $$replyref{$key} = $value;
 6868:             }
 6869:         } else {
 6870:             my $pathname = LONCAPA::tempdir();
 6871:             foreach my $line (@responses) {
 6872:                 my ($key,$value) = split(/=/,$line);
 6873:                 $$replyref{$key} = $value;
 6874:                 if ($value > 0) {
 6875:                     foreach my $item (@{$$affiliatesref{$key}}) {
 6876:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 6877:                         my $destname = $pathname.'/'.$filename;
 6878:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 6879:                         if ($xml_classlist =~ /^error/) {
 6880:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 6881:                         } else {
 6882:                             if ( open(FILE,">$destname") ) {
 6883:                                 print FILE &unescape($xml_classlist);
 6884:                                 close(FILE);
 6885:                             } else {
 6886:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 6887:                             }
 6888:                         }
 6889:                     }
 6890:                 }
 6891:             }
 6892:         }
 6893:         return 'ok';
 6894:     }
 6895:     return 'error';
 6896: }
 6897: 
 6898: sub get_query_reply {
 6899:     my $queryid=shift;
 6900:     my $replyfile=LONCAPA::tempdir().$queryid;
 6901:     my $reply='';
 6902:     for (1..100) {
 6903: 	sleep 2;
 6904:         if (-e $replyfile.'.end') {
 6905: 	    if (open(my $fh,$replyfile)) {
 6906: 		$reply = join('',<$fh>);
 6907: 		close($fh);
 6908: 	   } else { return 'error: reply_file_error'; }
 6909:            return &unescape($reply);
 6910: 	}
 6911:     }
 6912:     return 'timeout:'.$queryid;
 6913: }
 6914: 
 6915: sub courselog_query {
 6916: #
 6917: # possible filters:
 6918: # url: url or symb
 6919: # username
 6920: # domain
 6921: # action: view, submit, grade
 6922: # start: timestamp
 6923: # end: timestamp
 6924: #
 6925:     my (%filters)=@_;
 6926:     unless ($env{'request.course.id'}) { return 'no_course'; }
 6927:     if ($filters{'url'}) {
 6928: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 6929:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 6930:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 6931:     }
 6932:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6933:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6934:     return &log_query($cname,$cdom,'courselog',%filters);
 6935: }
 6936: 
 6937: sub userlog_query {
 6938: #
 6939: # possible filters:
 6940: # action: log check role
 6941: # start: timestamp
 6942: # end: timestamp
 6943: #
 6944:     my ($uname,$udom,%filters)=@_;
 6945:     return &log_query($uname,$udom,'userlog',%filters);
 6946: }
 6947: 
 6948: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 6949: 
 6950: sub auto_run {
 6951:     my ($cnum,$cdom) = @_;
 6952:     my $response = 0;
 6953:     my $settings;
 6954:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 6955:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 6956:         $settings = $domconfig{'autoenroll'};
 6957:         if ($settings->{'run'} eq '1') {
 6958:             $response = 1;
 6959:         }
 6960:     } else {
 6961:         my $homeserver;
 6962:         if (&is_course($cdom,$cnum)) {
 6963:             $homeserver = &homeserver($cnum,$cdom);
 6964:         } else {
 6965:             $homeserver = &domain($cdom,'primary');
 6966:         }
 6967:         if ($homeserver ne 'no_host') {
 6968:             $response = &reply('autorun:'.$cdom,$homeserver);
 6969:         }
 6970:     }
 6971:     return $response;
 6972: }
 6973: 
 6974: sub auto_get_sections {
 6975:     my ($cnum,$cdom,$inst_coursecode) = @_;
 6976:     my $homeserver;
 6977:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 6978:         $homeserver = &homeserver($cnum,$cdom);
 6979:     }
 6980:     if (!defined($homeserver)) { 
 6981:         if ($cdom =~ /^$match_domain$/) {
 6982:             $homeserver = &domain($cdom,'primary');
 6983:         }
 6984:     }
 6985:     my @secs;
 6986:     if (defined($homeserver)) {
 6987:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 6988:         unless ($response eq 'refused') {
 6989:             @secs = split(/:/,$response);
 6990:         }
 6991:     }
 6992:     return @secs;
 6993: }
 6994: 
 6995: sub auto_new_course {
 6996:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 6997:     my $homeserver = &homeserver($cnum,$cdom);
 6998:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 6999:     return $response;
 7000: }
 7001: 
 7002: sub auto_validate_courseID {
 7003:     my ($cnum,$cdom,$inst_course_id) = @_;
 7004:     my $homeserver = &homeserver($cnum,$cdom);
 7005:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 7006:     return $response;
 7007: }
 7008: 
 7009: sub auto_validate_instcode {
 7010:     my ($cnum,$cdom,$instcode,$owner) = @_;
 7011:     my ($homeserver,$response);
 7012:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 7013:         $homeserver = &homeserver($cnum,$cdom);
 7014:     }
 7015:     if (!defined($homeserver)) {
 7016:         if ($cdom =~ /^$match_domain$/) {
 7017:             $homeserver = &domain($cdom,'primary');
 7018:         }
 7019:     }
 7020:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 7021:                         &escape($instcode).':'.&escape($owner),$homeserver));
 7022:     my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
 7023:     return ($outcome,$description);
 7024: }
 7025: 
 7026: sub auto_create_password {
 7027:     my ($cnum,$cdom,$authparam,$udom) = @_;
 7028:     my ($homeserver,$response);
 7029:     my $create_passwd = 0;
 7030:     my $authchk = '';
 7031:     if ($udom =~ /^$match_domain$/) {
 7032:         $homeserver = &domain($udom,'primary');
 7033:     }
 7034:     if ($homeserver eq '') {
 7035:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 7036:             $homeserver = &homeserver($cnum,$cdom);
 7037:         }
 7038:     }
 7039:     if ($homeserver eq '') {
 7040:         $authchk = 'nodomain';
 7041:     } else {
 7042:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 7043:         if ($response eq 'refused') {
 7044:             $authchk = 'refused';
 7045:         } else {
 7046:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 7047:         }
 7048:     }
 7049:     return ($authparam,$create_passwd,$authchk);
 7050: }
 7051: 
 7052: sub auto_photo_permission {
 7053:     my ($cnum,$cdom,$students) = @_;
 7054:     my $homeserver = &homeserver($cnum,$cdom);
 7055:     my ($outcome,$perm_reqd,$conditions) = 
 7056: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 7057:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7058: 	return (undef,undef);
 7059:     }
 7060:     return ($outcome,$perm_reqd,$conditions);
 7061: }
 7062: 
 7063: sub auto_checkphotos {
 7064:     my ($uname,$udom,$pid) = @_;
 7065:     my $homeserver = &homeserver($uname,$udom);
 7066:     my ($result,$resulttype);
 7067:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 7068: 				   &escape($uname).':'.&escape($pid),
 7069: 				   $homeserver));
 7070:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7071: 	return (undef,undef);
 7072:     }
 7073:     if ($outcome) {
 7074:         ($result,$resulttype) = split(/:/,$outcome);
 7075:     } 
 7076:     return ($result,$resulttype);
 7077: }
 7078: 
 7079: sub auto_photochoice {
 7080:     my ($cnum,$cdom) = @_;
 7081:     my $homeserver = &homeserver($cnum,$cdom);
 7082:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 7083: 						       &escape($cdom),
 7084: 						       $homeserver)));
 7085:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7086: 	return (undef,undef);
 7087:     }
 7088:     return ($update,$comment);
 7089: }
 7090: 
 7091: sub auto_photoupdate {
 7092:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 7093:     my $homeserver = &homeserver($cnum,$dom);
 7094:     my $host=&hostname($homeserver);
 7095:     my $cmd = '';
 7096:     my $maxtries = 1;
 7097:     foreach my $affiliate (keys(%{$affiliatesref})) {
 7098:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 7099:     }
 7100:     $cmd =~ s/%%$//;
 7101:     $cmd = &escape($cmd);
 7102:     my $query = 'institutionalphotos';
 7103:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 7104:     unless ($queryid=~/^\Q$host\E\_/) {
 7105:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 7106:         return 'error: '.$queryid;
 7107:     }
 7108:     my $reply = &get_query_reply($queryid);
 7109:     my $tries = 1;
 7110:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 7111:         $reply = &get_query_reply($queryid);
 7112:         $tries ++;
 7113:     }
 7114:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 7115:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 7116:     } else {
 7117:         my @responses = split(/:/,$reply);
 7118:         my $outcome = shift(@responses); 
 7119:         foreach my $item (@responses) {
 7120:             my ($key,$value) = split(/=/,$item);
 7121:             $$photo{$key} = $value;
 7122:         }
 7123:         return $outcome;
 7124:     }
 7125:     return 'error';
 7126: }
 7127: 
 7128: sub auto_instcode_format {
 7129:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 7130: 	$cat_order) = @_;
 7131:     my $courses = '';
 7132:     my @homeservers;
 7133:     if ($caller eq 'global') {
 7134: 	my %servers = &get_servers($codedom,'library');
 7135: 	foreach my $tryserver (keys(%servers)) {
 7136: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7137: 		push(@homeservers,$tryserver);
 7138: 	    }
 7139:         }
 7140:     } elsif ($caller eq 'requests') {
 7141:         if ($codedom =~ /^$match_domain$/) {
 7142:             my $chome = &domain($codedom,'primary');
 7143:             unless ($chome eq 'no_host') {
 7144:                 push(@homeservers,$chome);
 7145:             }
 7146:         }
 7147:     } else {
 7148:         push(@homeservers,&homeserver($caller,$codedom));
 7149:     }
 7150:     foreach my $code (keys(%{$instcodes})) {
 7151:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 7152:     }
 7153:     chop($courses);
 7154:     my $ok_response = 0;
 7155:     my $response;
 7156:     while (@homeservers > 0 && $ok_response == 0) {
 7157:         my $server = shift(@homeservers); 
 7158:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 7159:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 7160:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 7161: 		split(/:/,$response);
 7162:             %{$codes} = (%{$codes},&str2hash($codes_str));
 7163:             push(@{$codetitles},&str2array($codetitles_str));
 7164:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 7165:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 7166:             $ok_response = 1;
 7167:         }
 7168:     }
 7169:     if ($ok_response) {
 7170:         return 'ok';
 7171:     } else {
 7172:         return $response;
 7173:     }
 7174: }
 7175: 
 7176: sub auto_instcode_defaults {
 7177:     my ($domain,$returnhash,$code_order) = @_;
 7178:     my @homeservers;
 7179: 
 7180:     my %servers = &get_servers($domain,'library');
 7181:     foreach my $tryserver (keys(%servers)) {
 7182: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7183: 	    push(@homeservers,$tryserver);
 7184: 	}
 7185:     }
 7186: 
 7187:     my $response;
 7188:     foreach my $server (@homeservers) {
 7189:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 7190:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 7191: 	
 7192: 	foreach my $pair (split(/\&/,$response)) {
 7193: 	    my ($name,$value)=split(/\=/,$pair);
 7194: 	    if ($name eq 'code_order') {
 7195: 		@{$code_order} = split(/\&/,&unescape($value));
 7196: 	    } else {
 7197: 		$returnhash->{&unescape($name)}=&unescape($value);
 7198: 	    }
 7199: 	}
 7200: 	return 'ok';
 7201:     }
 7202: 
 7203:     return $response;
 7204: }
 7205: 
 7206: sub auto_possible_instcodes {
 7207:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 7208:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 7209:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 7210:         return;
 7211:     }
 7212:     my (@homeservers,$uhome);
 7213:     if (defined(&domain($domain,'primary'))) {
 7214:         $uhome=&domain($domain,'primary');
 7215:         push(@homeservers,&domain($domain,'primary'));
 7216:     } else {
 7217:         my %servers = &get_servers($domain,'library');
 7218:         foreach my $tryserver (keys(%servers)) {
 7219:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7220:                 push(@homeservers,$tryserver);
 7221:             }
 7222:         }
 7223:     }
 7224:     my $response;
 7225:     foreach my $server (@homeservers) {
 7226:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 7227:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 7228:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 7229:             split(':',$response);
 7230:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 7231:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 7232:         foreach my $item (split('&',$cat_title)) {   
 7233:             my ($name,$value)=split('=',$item);
 7234:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 7235:         }
 7236:         foreach my $item (split('&',$cat_order)) {
 7237:             my ($name,$value)=split('=',$item);
 7238:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 7239:         }
 7240:         return 'ok';
 7241:     }
 7242:     return $response;
 7243: }
 7244: 
 7245: sub auto_courserequest_checks {
 7246:     my ($dom) = @_;
 7247:     my ($homeserver,%validations);
 7248:     if ($dom =~ /^$match_domain$/) {
 7249:         $homeserver = &domain($dom,'primary');
 7250:     }
 7251:     unless ($homeserver eq 'no_host') {
 7252:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 7253:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 7254:             my @items = split(/&/,$response);
 7255:             foreach my $item (@items) {
 7256:                 my ($key,$value) = split('=',$item);
 7257:                 $validations{&unescape($key)} = &thaw_unescape($value);
 7258:             }
 7259:         }
 7260:     }
 7261:     return %validations; 
 7262: }
 7263: 
 7264: sub auto_courserequest_validation {
 7265:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
 7266:     my ($homeserver,$response);
 7267:     if ($dom =~ /^$match_domain$/) {
 7268:         $homeserver = &domain($dom,'primary');
 7269:     }
 7270:     unless ($homeserver eq 'no_host') {  
 7271:           
 7272:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 7273:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 7274:                                     ':'.&escape($instcode).':'.&escape($instseclist),
 7275:                                     $homeserver));
 7276:     }
 7277:     return $response;
 7278: }
 7279: 
 7280: sub auto_validate_class_sec {
 7281:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 7282:     my $homeserver = &homeserver($cnum,$cdom);
 7283:     my $ownerlist;
 7284:     if (ref($owners) eq 'ARRAY') {
 7285:         $ownerlist = join(',',@{$owners});
 7286:     } else {
 7287:         $ownerlist = $owners;
 7288:     }
 7289:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 7290:                         &escape($ownerlist).':'.$cdom,$homeserver);
 7291:     return $response;
 7292: }
 7293: 
 7294: # ------------------------------------------------------- Course Group routines
 7295: 
 7296: sub get_coursegroups {
 7297:     my ($cdom,$cnum,$group,$namespace) = @_;
 7298:     return(&dump($namespace,$cdom,$cnum,$group));
 7299: }
 7300: 
 7301: sub modify_coursegroup {
 7302:     my ($cdom,$cnum,$groupsettings) = @_;
 7303:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 7304: }
 7305: 
 7306: sub toggle_coursegroup_status {
 7307:     my ($cdom,$cnum,$group,$action) = @_;
 7308:     my ($from_namespace,$to_namespace);
 7309:     if ($action eq 'delete') {
 7310:         $from_namespace = 'coursegroups';
 7311:         $to_namespace = 'deleted_groups';
 7312:     } else {
 7313:         $from_namespace = 'deleted_groups';
 7314:         $to_namespace = 'coursegroups';
 7315:     }
 7316:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 7317:     if (my $tmp = &error(%curr_group)) {
 7318:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 7319:         return ('read error',$tmp);
 7320:     } else {
 7321:         my %savedsettings = %curr_group; 
 7322:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 7323:         my $deloutcome;
 7324:         if ($result eq 'ok') {
 7325:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 7326:         } else {
 7327:             return ('write error',$result);
 7328:         }
 7329:         if ($deloutcome eq 'ok') {
 7330:             return 'ok';
 7331:         } else {
 7332:             return ('delete error',$deloutcome);
 7333:         }
 7334:     }
 7335: }
 7336: 
 7337: sub modify_group_roles {
 7338:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 7339:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 7340:     my $role = 'gr/'.&escape($userprivs);
 7341:     my ($uname,$udom) = split(/:/,$user);
 7342:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 7343:     if ($result eq 'ok') {
 7344:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 7345:     }
 7346:     return $result;
 7347: }
 7348: 
 7349: sub modify_coursegroup_membership {
 7350:     my ($cdom,$cnum,$membership) = @_;
 7351:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 7352:     return $result;
 7353: }
 7354: 
 7355: sub get_active_groups {
 7356:     my ($udom,$uname,$cdom,$cnum) = @_;
 7357:     my $now = time;
 7358:     my %groups = ();
 7359:     foreach my $key (keys(%env)) {
 7360:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 7361:             my ($start,$end) = split(/\./,$env{$key});
 7362:             if (($end!=0) && ($end<$now)) { next; }
 7363:             if (($start!=0) && ($start>$now)) { next; }
 7364:             if ($1 eq $cdom && $2 eq $cnum) {
 7365:                 $groups{$3} = $env{$key} ;
 7366:             }
 7367:         }
 7368:     }
 7369:     return %groups;
 7370: }
 7371: 
 7372: sub get_group_membership {
 7373:     my ($cdom,$cnum,$group) = @_;
 7374:     return(&dump('groupmembership',$cdom,$cnum,$group));
 7375: }
 7376: 
 7377: sub get_users_groups {
 7378:     my ($udom,$uname,$courseid) = @_;
 7379:     my @usersgroups;
 7380:     my $cachetime=1800;
 7381: 
 7382:     my $hashid="$udom:$uname:$courseid";
 7383:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 7384:     if (defined($cached)) {
 7385:         @usersgroups = split(/:/,$grouplist);
 7386:     } else {  
 7387:         $grouplist = '';
 7388:         my $courseurl = &courseid_to_courseurl($courseid);
 7389:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 7390:         my $access_end = $env{'course.'.$courseid.
 7391:                               '.default_enrollment_end_date'};
 7392:         my $now = time;
 7393:         foreach my $key (keys(%roleshash)) {
 7394:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 7395:                 my $group = $1;
 7396:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 7397:                     my $start = $2;
 7398:                     my $end = $1;
 7399:                     if ($start == -1) { next; } # deleted from group
 7400:                     if (($start!=0) && ($start>$now)) { next; }
 7401:                     if (($end!=0) && ($end<$now)) {
 7402:                         if ($access_end && $access_end < $now) {
 7403:                             if ($access_end - $end < 86400) {
 7404:                                 push(@usersgroups,$group);
 7405:                             }
 7406:                         }
 7407:                         next;
 7408:                     }
 7409:                     push(@usersgroups,$group);
 7410:                 }
 7411:             }
 7412:         }
 7413:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 7414:         $grouplist = join(':',@usersgroups);
 7415:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 7416:     }
 7417:     return @usersgroups;
 7418: }
 7419: 
 7420: sub devalidate_getgroups_cache {
 7421:     my ($udom,$uname,$cdom,$cnum)=@_;
 7422:     my $courseid = $cdom.'_'.$cnum;
 7423: 
 7424:     my $hashid="$udom:$uname:$courseid";
 7425:     &devalidate_cache_new('getgroups',$hashid);
 7426: }
 7427: 
 7428: # ------------------------------------------------------------------ Plain Text
 7429: 
 7430: sub plaintext {
 7431:     my ($short,$type,$cid,$forcedefault) = @_;
 7432:     if ($short =~ m{^cr/}) {
 7433: 	return (split('/',$short))[-1];
 7434:     }
 7435:     if (!defined($cid)) {
 7436:         $cid = $env{'request.course.id'};
 7437:     }
 7438:     my %rolenames = (
 7439:                       Course    => 'std',
 7440:                       Community => 'alt1',
 7441:                     );
 7442:     if ($cid ne '') {
 7443:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 7444:             unless ($forcedefault) {
 7445:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 7446:                 &Apache::lonlocal::mt_escape(\$roletext);
 7447:                 return &Apache::lonlocal::mt($roletext);
 7448:             }
 7449:         }
 7450:     }
 7451:     if ((defined($type)) && (defined($rolenames{$type})) &&
 7452:         (defined($rolenames{$type})) && 
 7453:         (defined($prp{$short}{$rolenames{$type}}))) {
 7454:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 7455:     } elsif ($cid ne '') {
 7456:         my $crstype = $env{'course.'.$cid.'.type'};
 7457:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
 7458:             (defined($prp{$short}{$rolenames{$crstype}}))) {
 7459:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
 7460:         }
 7461:     }
 7462:     return &Apache::lonlocal::mt($prp{$short}{'std'});
 7463: }
 7464: 
 7465: # ----------------------------------------------------------------- Assign Role
 7466: 
 7467: sub assignrole {
 7468:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 7469:         $context)=@_;
 7470:     my $mrole;
 7471:     if ($role =~ /^cr\//) {
 7472:         my $cwosec=$url;
 7473:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 7474: 	unless (&allowed('ccr',$cwosec)) {
 7475:            my $refused = 1;
 7476:            if ($context eq 'requestcourses') {
 7477:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 7478:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
 7479:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
 7480:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 7481:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 7482:                            if ($crsenv{'internal.courseowner'} eq
 7483:                                $env{'user.name'}.':'.$env{'user.domain'}) {
 7484:                                $refused = '';
 7485:                            }
 7486:                        }
 7487:                    }
 7488:                }
 7489:            }
 7490:            if ($refused) {
 7491:                &logthis('Refused custom assignrole: '.
 7492:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
 7493:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
 7494:                return 'refused';
 7495:            }
 7496:         }
 7497:         $mrole='cr';
 7498:     } elsif ($role =~ /^gr\//) {
 7499:         my $cwogrp=$url;
 7500:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 7501:         unless (&allowed('mdg',$cwogrp)) {
 7502:             &logthis('Refused group assignrole: '.
 7503:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 7504:                     $env{'user.name'}.' at '.$env{'user.domain'});
 7505:             return 'refused';
 7506:         }
 7507:         $mrole='gr';
 7508:     } else {
 7509:         my $cwosec=$url;
 7510:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 7511:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 7512:             my $refused;
 7513:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 7514:                 if (!(&allowed('c'.$role,$url))) {
 7515:                     $refused = 1;
 7516:                 }
 7517:             } else {
 7518:                 $refused = 1;
 7519:             }
 7520:             if ($refused) {
 7521:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 7522:                 if (!$selfenroll && $context eq 'course') {
 7523:                     my %crsenv;
 7524:                     if ($role eq 'cc' || $role eq 'co') {
 7525:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 7526:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
 7527:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
 7528:                                 if ($crsenv{'internal.courseowner'} eq 
 7529:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 7530:                                     $refused = '';
 7531:                                 }
 7532:                             }
 7533:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
 7534:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
 7535:                                 if ($crsenv{'internal.courseowner'} eq 
 7536:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 7537:                                     $refused = '';
 7538:                                 }
 7539:                             }
 7540:                         }
 7541:                     }
 7542:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7543:                     $refused = '';
 7544:                 } elsif ($context eq 'requestcourses') {
 7545:                     my @possroles = ('st','ta','ep','in','cc','co');
 7546:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
 7547:                         my $wrongcc;
 7548:                         if ($cnum =~ /^$match_community$/) {
 7549:                             $wrongcc = 1 if ($role eq 'cc');
 7550:                         } else {
 7551:                             $wrongcc = 1 if ($role eq 'co');
 7552:                         }
 7553:                         unless ($wrongcc) {
 7554:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 7555:                             if ($crsenv{'internal.courseowner'} eq 
 7556:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
 7557:                                 $refused = '';
 7558:                             }
 7559:                         }
 7560:                     }
 7561:                 } elsif ($context eq 'requestauthor') {
 7562:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
 7563:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
 7564:                         if ($env{'environment.requestauthor'} eq 'automatic') {
 7565:                             $refused = '';
 7566:                         } else {
 7567:                             my %domdefaults = &get_domain_defaults($udom);
 7568:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
 7569:                                 my $checkbystatus;
 7570:                                 if ($env{'user.adv'}) { 
 7571:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
 7572:                                     if ($disposition eq 'automatic') {
 7573:                                         $refused = '';
 7574:                                     } elsif ($disposition eq '') {
 7575:                                         $checkbystatus = 1;
 7576:                                     } 
 7577:                                 } else {
 7578:                                     $checkbystatus = 1;
 7579:                                 }
 7580:                                 if ($checkbystatus) {
 7581:                                     if ($env{'environment.inststatus'}) {
 7582:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
 7583:                                         foreach my $type (@inststatuses) {
 7584:                                             if (($type ne '') &&
 7585:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
 7586:                                                 $refused = '';
 7587:                                             }
 7588:                                         }
 7589:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
 7590:                                         $refused = '';
 7591:                                     }
 7592:                                 }
 7593:                             }
 7594:                         }
 7595:                     }
 7596:                 }
 7597:                 if ($refused) {
 7598:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 7599:                              ' '.$role.' '.$end.' '.$start.' by '.
 7600: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 7601:                     return 'refused';
 7602:                 }
 7603:             }
 7604:         } elsif ($role eq 'au') {
 7605:             if ($url ne '/'.$udom.'/') {
 7606:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
 7607:                          ' to assign author role for '.$uname.':'.$udom.
 7608:                          ' in domain: '.$url.' refused (wrong domain).');
 7609:                 return 'refused';
 7610:             }
 7611:         }
 7612:         $mrole=$role;
 7613:     }
 7614:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 7615:                 "$udom:$uname:$url".'_'."$mrole=$role";
 7616:     if ($end) { $command.='_'.$end; }
 7617:     if ($start) {
 7618: 	if ($end) { 
 7619:            $command.='_'.$start; 
 7620:         } else {
 7621:            $command.='_0_'.$start;
 7622:         }
 7623:     }
 7624:     my $origstart = $start;
 7625:     my $origend = $end;
 7626:     my $delflag;
 7627: # actually delete
 7628:     if ($deleteflag) {
 7629: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 7630: # modify command to delete the role
 7631:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 7632:                 "$udom:$uname:$url".'_'."$mrole";
 7633: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 7634: # set start and finish to negative values for userrolelog
 7635:            $start=-1;
 7636:            $end=-1;
 7637:            $delflag = 1;
 7638:         }
 7639:     }
 7640: # send command
 7641:     my $answer=&reply($command,&homeserver($uname,$udom));
 7642: # log new user role if status is ok
 7643:     if ($answer eq 'ok') {
 7644: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 7645: # for course roles, perform group memberships changes triggered by role change.
 7646:         unless ($role =~ /^gr/) {
 7647:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 7648:                                              $origstart,$selfenroll,$context);
 7649:         }
 7650:         if (($role eq 'cc') || ($role eq 'in') ||
 7651:             ($role eq 'ep') || ($role eq 'ad') ||
 7652:             ($role eq 'ta') || ($role eq 'st') ||
 7653:             ($role=~/^cr/) || ($role eq 'gr') ||
 7654:             ($role eq 'co')) {
 7655:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 7656:                            $selfenroll,$context);
 7657:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
 7658:                  ($role eq 'au') || ($role eq 'dc')) {
 7659:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 7660:                            $context);
 7661:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
 7662:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 7663:                              $context); 
 7664:         }
 7665:         if ($role eq 'cc') {
 7666:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
 7667:         }
 7668:     }
 7669:     return $answer;
 7670: }
 7671: 
 7672: sub autoupdate_coowners {
 7673:     my ($url,$end,$start,$uname,$udom) = @_;
 7674:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
 7675:     if (($cdom ne '') && ($cnum ne '')) {
 7676:         my $now = time;
 7677:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
 7678:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
 7679:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
 7680:             my $instcode = $coursehash{'internal.coursecode'};
 7681:             if ($instcode ne '') {
 7682:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
 7683:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
 7684:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
 7685:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
 7686:                         if ($result eq 'valid') {
 7687:                             if ($coursehash{'internal.co-owners'}) {
 7688:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 7689:                                     push(@newcoowners,$coowner);
 7690:                                 }
 7691:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
 7692:                                     push(@newcoowners,$uname.':'.$udom);
 7693:                                 }
 7694:                                 @newcoowners = sort(@newcoowners);
 7695:                             } else {
 7696:                                 push(@newcoowners,$uname.':'.$udom);
 7697:                             }
 7698:                         } else {
 7699:                             if ($coursehash{'internal.co-owners'}) {
 7700:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 7701:                                     unless ($coowner eq $uname.':'.$udom) {
 7702:                                         push(@newcoowners,$coowner);
 7703:                                     }
 7704:                                 }
 7705:                                 unless (@newcoowners > 0) {
 7706:                                     $delcoowners = 1;
 7707:                                     $coowners = '';
 7708:                                 }
 7709:                             }
 7710:                         }
 7711:                         if (@newcoowners || $delcoowners) {
 7712:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
 7713:                                             $delcoowners,@newcoowners);
 7714:                         }
 7715:                     }
 7716:                 }
 7717:             }
 7718:         }
 7719:     }
 7720: }
 7721: 
 7722: sub store_coowners {
 7723:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
 7724:     my $cid = $cdom.'_'.$cnum;
 7725:     my ($coowners,$delresult,$putresult);
 7726:     if (@newcoowners) {
 7727:         $coowners = join(',',@newcoowners);
 7728:         my %coownershash = (
 7729:                             'internal.co-owners' => $coowners,
 7730:                            );
 7731:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
 7732:         if ($putresult eq 'ok') {
 7733:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
 7734:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
 7735:             }
 7736:         }
 7737:     }
 7738:     if ($delcoowners) {
 7739:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
 7740:         if ($delresult eq 'ok') {
 7741:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
 7742:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
 7743:             }
 7744:         }
 7745:     }
 7746:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
 7747:         my %crsinfo =
 7748:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 7749:         if (ref($crsinfo{$cid}) eq 'HASH') {
 7750:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
 7751:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
 7752:         }
 7753:     }
 7754: }
 7755: 
 7756: # -------------------------------------------------- Modify user authentication
 7757: # Overrides without validation
 7758: 
 7759: sub modifyuserauth {
 7760:     my ($udom,$uname,$umode,$upass)=@_;
 7761:     my $uhome=&homeserver($uname,$udom);
 7762:     unless (&allowed('mau',$udom)) { return 'refused'; }
 7763:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 7764:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 7765:              ' in domain '.$env{'request.role.domain'});  
 7766:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 7767: 		     &escape($upass),$uhome);
 7768:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 7769:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 7770:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 7771:     &log($udom,,$uname,$uhome,
 7772:         'Authentication changed by '.$env{'user.domain'}.', '.
 7773:                                      $env{'user.name'}.', '.$umode.
 7774:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 7775:     unless ($reply eq 'ok') {
 7776:         &logthis('Authentication mode error: '.$reply);
 7777: 	return 'error: '.$reply;
 7778:     }   
 7779:     return 'ok';
 7780: }
 7781: 
 7782: # --------------------------------------------------------------- Modify a user
 7783: 
 7784: sub modifyuser {
 7785:     my ($udom,    $uname, $uid,
 7786:         $umode,   $upass, $first,
 7787:         $middle,  $last,  $gene,
 7788:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
 7789:     $udom= &LONCAPA::clean_domain($udom);
 7790:     $uname=&LONCAPA::clean_username($uname);
 7791:     my $showcandelete = 'none';
 7792:     if (ref($candelete) eq 'ARRAY') {
 7793:         if (@{$candelete} > 0) {
 7794:             $showcandelete = join(', ',@{$candelete});
 7795:         }
 7796:     }
 7797:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 7798:              $umode.', '.$first.', '.$middle.', '.
 7799: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
 7800:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 7801:                                      ' desiredhome not specified'). 
 7802:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 7803:              ' in domain '.$env{'request.role.domain'});
 7804:     my $uhome=&homeserver($uname,$udom,'true');
 7805:     my $newuser;
 7806:     if ($uhome eq 'no_host') {
 7807:         $newuser = 1;
 7808:     }
 7809: # ----------------------------------------------------------------- Create User
 7810:     if (($uhome eq 'no_host') && 
 7811: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 7812:         my $unhome='';
 7813:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 7814:             $unhome = $desiredhome;
 7815: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 7816: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 7817:         } else { # load balancing routine for determining $unhome
 7818:             my $loadm=10000000;
 7819: 	    my %servers = &get_servers($udom,'library');
 7820: 	    foreach my $tryserver (keys(%servers)) {
 7821: 		my $answer=reply('load',$tryserver);
 7822: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 7823: 		    $loadm=$answer;
 7824: 		    $unhome=$tryserver;
 7825: 		}
 7826: 	    }
 7827:         }
 7828:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 7829: 	    return 'error: unable to find a home server for '.$uname.
 7830:                    ' in domain '.$udom;
 7831:         }
 7832:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 7833:                          &escape($upass),$unhome);
 7834: 	unless ($reply eq 'ok') {
 7835:             return 'error: '.$reply;
 7836:         }   
 7837:         $uhome=&homeserver($uname,$udom,'true');
 7838:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 7839: 	    return 'error: unable verify users home machine.';
 7840:         }
 7841:     }   # End of creation of new user
 7842: # ---------------------------------------------------------------------- Add ID
 7843:     if ($uid) {
 7844:        $uid=~tr/A-Z/a-z/;
 7845:        my %uidhash=&idrget($udom,$uname);
 7846:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 7847:          && (!$forceid)) {
 7848: 	  unless ($uid eq $uidhash{$uname}) {
 7849: 	      return 'error: user id "'.$uid.'" does not match '.
 7850:                   'current user id "'.$uidhash{$uname}.'".';
 7851:           }
 7852:        } else {
 7853: 	  &idput($udom,($uname => $uid));
 7854:        }
 7855:     }
 7856: # -------------------------------------------------------------- Add names, etc
 7857:     my @tmp=&get('environment',
 7858: 		   ['firstname','middlename','lastname','generation','id',
 7859:                     'permanentemail','inststatus'],
 7860: 		   $udom,$uname);
 7861:     my (%names,%oldnames);
 7862:     if ($tmp[0] =~ m/^error:.*/) { 
 7863:         %names=(); 
 7864:     } else {
 7865:         %names = @tmp;
 7866:         %oldnames = %names;
 7867:     }
 7868: #
 7869: # If name, email and/or uid are blank (e.g., because an uploaded file
 7870: # of users did not contain them), do not overwrite existing values
 7871: # unless field is in $candelete array ref.  
 7872: #
 7873: 
 7874:     my @fields = ('firstname','middlename','lastname','generation',
 7875:                   'permanentemail','id');
 7876:     my %newvalues;
 7877:     if (ref($candelete) eq 'ARRAY') {
 7878:         foreach my $field (@fields) {
 7879:             if (grep(/^\Q$field\E$/,@{$candelete})) {
 7880:                 if ($field eq 'firstname') {
 7881:                     $names{$field} = $first;
 7882:                 } elsif ($field eq 'middlename') {
 7883:                     $names{$field} = $middle;
 7884:                 } elsif ($field eq 'lastname') {
 7885:                     $names{$field} = $last;
 7886:                 } elsif ($field eq 'generation') { 
 7887:                     $names{$field} = $gene;
 7888:                 } elsif ($field eq 'permanentemail') {
 7889:                     $names{$field} = $email;
 7890:                 } elsif ($field eq 'id') {
 7891:                     $names{$field}  = $uid;
 7892:                 }
 7893:             }
 7894:         }
 7895:     }
 7896:     if ($first)  { $names{'firstname'}  = $first; }
 7897:     if (defined($middle)) { $names{'middlename'} = $middle; }
 7898:     if ($last)   { $names{'lastname'}   = $last; }
 7899:     if (defined($gene))   { $names{'generation'} = $gene; }
 7900:     if ($email) {
 7901:        $email=~s/[^\w\@\.\-\,]//gs;
 7902:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 7903:     }
 7904:     if ($uid) { $names{'id'}  = $uid; }
 7905:     if (defined($inststatus)) {
 7906:         $names{'inststatus'} = '';
 7907:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
 7908:         if (ref($usertypes) eq 'HASH') {
 7909:             my @okstatuses; 
 7910:             foreach my $item (split(/:/,$inststatus)) {
 7911:                 if (defined($usertypes->{$item})) {
 7912:                     push(@okstatuses,$item);  
 7913:                 }
 7914:             }
 7915:             if (@okstatuses) {
 7916:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
 7917:             }
 7918:         }
 7919:     }
 7920:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
 7921:                  $umode.', '.$first.', '.$middle.', '.
 7922:                  $last.', '.$gene.', '.$email.', '.$inststatus;
 7923:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 7924:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 7925:     } else {
 7926:         $logmsg .= ' during self creation';
 7927:     }
 7928:     my $changed;
 7929:     if ($newuser) {
 7930:         $changed = 1;
 7931:     } else {
 7932:         foreach my $field (@fields) {
 7933:             if ($names{$field} ne $oldnames{$field}) {
 7934:                 $changed = 1;
 7935:                 last;
 7936:             }
 7937:         }
 7938:     }
 7939:     unless ($changed) {
 7940:         $logmsg = 'No changes in user information needed for: '.$logmsg;
 7941:         &logthis($logmsg);
 7942:         return 'ok';
 7943:     }
 7944:     my $reply = &put('environment', \%names, $udom,$uname);
 7945:     if ($reply ne 'ok') { 
 7946:         return 'error: '.$reply;
 7947:     }
 7948:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
 7949:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
 7950:     }
 7951:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 7952:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 7953:     $logmsg = 'Success modifying user '.$logmsg;
 7954:     &logthis($logmsg);
 7955:     return 'ok';
 7956: }
 7957: 
 7958: # -------------------------------------------------------------- Modify student
 7959: 
 7960: sub modifystudent {
 7961:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 7962:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 7963:         $selfenroll,$context,$inststatus)=@_;
 7964:     if (!$cid) {
 7965: 	unless ($cid=$env{'request.course.id'}) {
 7966: 	    return 'not_in_class';
 7967: 	}
 7968:     }
 7969: # --------------------------------------------------------------- Make the user
 7970:     my $reply=&modifyuser
 7971: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 7972:          $desiredhome,$email,$inststatus);
 7973:     unless ($reply eq 'ok') { return $reply; }
 7974:     # This will cause &modify_student_enrollment to get the uid from the
 7975:     # students environment
 7976:     $uid = undef if (!$forceid);
 7977:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 7978: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
 7979:     return $reply;
 7980: }
 7981: 
 7982: sub modify_student_enrollment {
 7983:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
 7984:     my ($cdom,$cnum,$chome);
 7985:     if (!$cid) {
 7986: 	unless ($cid=$env{'request.course.id'}) {
 7987: 	    return 'not_in_class';
 7988: 	}
 7989: 	$cdom=$env{'course.'.$cid.'.domain'};
 7990: 	$cnum=$env{'course.'.$cid.'.num'};
 7991:     } else {
 7992: 	($cdom,$cnum)=split(/_/,$cid);
 7993:     }
 7994:     $chome=$env{'course.'.$cid.'.home'};
 7995:     if (!$chome) {
 7996: 	$chome=&homeserver($cnum,$cdom);
 7997:     }
 7998:     if (!$chome) { return 'unknown_course'; }
 7999:     # Make sure the user exists
 8000:     my $uhome=&homeserver($uname,$udom);
 8001:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 8002: 	return 'error: no such user';
 8003:     }
 8004:     # Get student data if we were not given enough information
 8005:     if (!defined($first)  || $first  eq '' || 
 8006:         !defined($last)   || $last   eq '' || 
 8007:         !defined($uid)    || $uid    eq '' || 
 8008:         !defined($middle) || $middle eq '' || 
 8009:         !defined($gene)   || $gene   eq '') {
 8010:         # They did not supply us with enough data to enroll the student, so
 8011:         # we need to pick up more information.
 8012:         my %tmp = &get('environment',
 8013:                        ['firstname','middlename','lastname', 'generation','id']
 8014:                        ,$udom,$uname);
 8015: 
 8016:         #foreach my $key (keys(%tmp)) {
 8017:         #    &logthis("key $key = ".$tmp{$key});
 8018:         #}
 8019:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 8020:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 8021:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 8022:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 8023:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 8024:     }
 8025:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 8026:     my $user = "$uname:$udom";
 8027:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
 8028:     my $reply=cput('classlist',
 8029: 		   {$user => 
 8030: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
 8031: 		   $cdom,$cnum);
 8032:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
 8033:         &devalidate_getsection_cache($udom,$uname,$cid);
 8034:     } else { 
 8035: 	return 'error: '.$reply;
 8036:     }
 8037:     # Add student role to user
 8038:     my $uurl='/'.$cid;
 8039:     $uurl=~s/\_/\//g;
 8040:     if ($usec) {
 8041: 	$uurl.='/'.$usec;
 8042:     }
 8043:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
 8044:                              $selfenroll,$context);
 8045:     if ($result ne 'ok') {
 8046:         if ($old_entry{$user} ne '') {
 8047:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
 8048:         } else {
 8049:             $reply = &del('classlist',[$user],$cdom,$cnum);
 8050:         }
 8051:     }
 8052:     return $result; 
 8053: }
 8054: 
 8055: sub format_name {
 8056:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 8057:     my $name;
 8058:     if ($first ne 'lastname') {
 8059: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 8060:     } else {
 8061: 	if ($lastname=~/\S/) {
 8062: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 8063: 	    $name=~s/\s+,/,/;
 8064: 	} else {
 8065: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 8066: 	}
 8067:     }
 8068:     $name=~s/^\s+//;
 8069:     $name=~s/\s+$//;
 8070:     $name=~s/\s+/ /g;
 8071:     return $name;
 8072: }
 8073: 
 8074: # ------------------------------------------------- Write to course preferences
 8075: 
 8076: sub writecoursepref {
 8077:     my ($courseid,%prefs)=@_;
 8078:     $courseid=~s/^\///;
 8079:     $courseid=~s/\_/\//g;
 8080:     my ($cdomain,$cnum)=split(/\//,$courseid);
 8081:     my $chome=homeserver($cnum,$cdomain);
 8082:     if (($chome eq '') || ($chome eq 'no_host')) { 
 8083: 	return 'error: no such course';
 8084:     }
 8085:     my $cstring='';
 8086:     foreach my $pref (keys(%prefs)) {
 8087: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 8088:     }
 8089:     $cstring=~s/\&$//;
 8090:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 8091: }
 8092: 
 8093: # ---------------------------------------------------------- Make/modify course
 8094: 
 8095: sub createcourse {
 8096:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 8097:         $course_owner,$crstype,$cnum,$context,$category)=@_;
 8098:     $url=&declutter($url);
 8099:     my $cid='';
 8100:     if ($context eq 'requestcourses') {
 8101:         my $can_create = 0;
 8102:         my ($ownername,$ownerdom) = split(':',$course_owner);
 8103:         if ($udom eq $ownerdom) {
 8104:             if (&usertools_access($ownername,$ownerdom,$category,undef,
 8105:                                   $context)) {
 8106:                 $can_create = 1;
 8107:             }
 8108:         } else {
 8109:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
 8110:                                            $category);
 8111:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
 8112:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
 8113:                 if (@curr > 0) {
 8114:                     my @options = qw(approval validate autolimit);
 8115:                     my $optregex = join('|',@options);
 8116:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
 8117:                         $can_create = 1;
 8118:                     }
 8119:                 }
 8120:             }
 8121:         }
 8122:         if ($can_create) {
 8123:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
 8124:                 unless (&allowed('ccc',$udom)) {
 8125:                     return 'refused'; 
 8126:                 }
 8127:             }
 8128:         } else {
 8129:             return 'refused';
 8130:         }
 8131:     } elsif (!&allowed('ccc',$udom)) {
 8132:         return 'refused';
 8133:     }
 8134: # --------------------------------------------------------------- Get Unique ID
 8135:     my $uname;
 8136:     if ($cnum =~ /^$match_courseid$/) {
 8137:         my $chome=&homeserver($cnum,$udom,'true');
 8138:         if (($chome eq '') || ($chome eq 'no_host')) {
 8139:             $uname = $cnum;
 8140:         } else {
 8141:             $uname = &generate_coursenum($udom,$crstype);
 8142:         }
 8143:     } else {
 8144:         $uname = &generate_coursenum($udom,$crstype);
 8145:     }
 8146:     return $uname if ($uname =~ /^error/);
 8147: # -------------------------------------------------- Check supplied server name
 8148:     if (!defined($course_server)) {
 8149:         if (defined(&domain($udom,'primary'))) {
 8150:             $course_server = &domain($udom,'primary');
 8151:         } else {
 8152:             $course_server = $env{'user.home'}; 
 8153:         }
 8154:     }
 8155:     my %host_servers =
 8156:         &Apache::lonnet::get_servers($udom,'library');
 8157:     unless ($host_servers{$course_server}) {
 8158:         return 'error: invalid home server for course: '.$course_server;
 8159:     }
 8160: # ------------------------------------------------------------- Make the course
 8161:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 8162:                       $course_server);
 8163:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 8164:     my $uhome=&homeserver($uname,$udom,'true');
 8165:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 8166: 	return 'error: no such course';
 8167:     }
 8168: # ----------------------------------------------------------------- Course made
 8169: # log existence
 8170:     my $now = time;
 8171:     my $newcourse = {
 8172:                     $udom.'_'.$uname => {
 8173:                                      description => $description,
 8174:                                      inst_code   => $inst_code,
 8175:                                      owner       => $course_owner,
 8176:                                      type        => $crstype,
 8177:                                      creator     => $env{'user.name'}.':'.
 8178:                                                     $env{'user.domain'},
 8179:                                      created     => $now,
 8180:                                      context     => $context,
 8181:                                                 },
 8182:                     };
 8183:     &courseidput($udom,$newcourse,$uhome,'notime');
 8184: # set toplevel url
 8185:     my $topurl=$url;
 8186:     unless ($nonstandard) {
 8187: # ------------------------------------------ For standard courses, make top url
 8188:         my $mapurl=&clutter($url);
 8189:         if ($mapurl eq '/res/') { $mapurl=''; }
 8190:         $env{'form.initmap'}=(<<ENDINITMAP);
 8191: <map>
 8192: <resource id="1" type="start"></resource>
 8193: <resource id="2" src="$mapurl"></resource>
 8194: <resource id="3" type="finish"></resource>
 8195: <link index="1" from="1" to="2"></link>
 8196: <link index="2" from="2" to="3"></link>
 8197: </map>
 8198: ENDINITMAP
 8199:         $topurl=&declutter(
 8200:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 8201:                           );
 8202:     }
 8203: # ----------------------------------------------------------- Write preferences
 8204:     &writecoursepref($udom.'_'.$uname,
 8205:                      ('description'              => $description,
 8206:                       'url'                      => $topurl,
 8207:                       'internal.creator'         => $env{'user.name'}.':'.
 8208:                                                     $env{'user.domain'},
 8209:                       'internal.created'         => $now,
 8210:                       'internal.creationcontext' => $context)
 8211:                     );
 8212:     return '/'.$udom.'/'.$uname;
 8213: }
 8214: 
 8215: # ------------------------------------------------------------------- Create ID
 8216: sub generate_coursenum {
 8217:     my ($udom,$crstype) = @_;
 8218:     my $domdesc = &domain($udom);
 8219:     return 'error: invalid domain' if ($domdesc eq '');
 8220:     my $first;
 8221:     if ($crstype eq 'Community') {
 8222:         $first = '0';
 8223:     } else {
 8224:         $first = int(1+rand(9)); 
 8225:     } 
 8226:     my $uname=$first.
 8227:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 8228:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
 8229:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 8230: # ----------------------------------------------- Make sure that does not exist
 8231:     my $uhome=&homeserver($uname,$udom,'true');
 8232:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
 8233:         if ($crstype eq 'Community') {
 8234:             $first = '0';
 8235:         } else {
 8236:             $first = int(1+rand(9));
 8237:         }
 8238:         $uname=$first.
 8239:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 8240:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
 8241:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 8242:         $uhome=&homeserver($uname,$udom,'true');
 8243:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
 8244:             return 'error: unable to generate unique course-ID';
 8245:         }
 8246:     }
 8247:     return $uname;
 8248: }
 8249: 
 8250: sub is_course {
 8251:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
 8252:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
 8253: 
 8254:     return unless $cdom and $cnum;
 8255: 
 8256:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
 8257:         '.');
 8258: 
 8259:     return unless exists($courses{$cdom.'_'.$cnum});
 8260:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
 8261: }
 8262: 
 8263: sub store_userdata {
 8264:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
 8265:     my $result;
 8266:     if ($datakey ne '') {
 8267:         if (ref($storehash) eq 'HASH') {
 8268:             if ($udom eq '' || $uname eq '') {
 8269:                 $udom = $env{'user.domain'};
 8270:                 $uname = $env{'user.name'};
 8271:             }
 8272:             my $uhome=&homeserver($uname,$udom);
 8273:             if (($uhome eq '') || ($uhome eq 'no_host')) {
 8274:                 $result = 'error: no_host';
 8275:             } else {
 8276:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
 8277:                 $storehash->{'host'} = $perlvar{'lonHostID'};
 8278: 
 8279:                 my $namevalue='';
 8280:                 foreach my $key (keys(%{$storehash})) {
 8281:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 8282:                 }
 8283:                 $namevalue=~s/\&$//;
 8284:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
 8285:                                   $namevalue,$uhome);
 8286:             }
 8287:         } else {
 8288:             $result = 'error: data to store was not a hash reference'; 
 8289:         }
 8290:     } else {
 8291:         $result= 'error: invalid requestkey'; 
 8292:     }
 8293:     return $result;
 8294: }
 8295: 
 8296: # ---------------------------------------------------------- Assign Custom Role
 8297: 
 8298: sub assigncustomrole {
 8299:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
 8300:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 8301:                        $end,$start,$deleteflag,$selfenroll,$context);
 8302: }
 8303: 
 8304: # ----------------------------------------------------------------- Revoke Role
 8305: 
 8306: sub revokerole {
 8307:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
 8308:     my $now=time;
 8309:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
 8310: }
 8311: 
 8312: # ---------------------------------------------------------- Revoke Custom Role
 8313: 
 8314: sub revokecustomrole {
 8315:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
 8316:     my $now=time;
 8317:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 8318:            $deleteflag,$selfenroll,$context);
 8319: }
 8320: 
 8321: # ------------------------------------------------------------ Disk usage
 8322: sub diskusage {
 8323:     my ($udom,$uname,$directorypath,$getpropath)=@_;
 8324:     $directorypath =~ s/\/$//;
 8325:     my $listing=&reply('du2:'.&escape($directorypath).':'
 8326:                        .&escape($getpropath).':'.&escape($uname).':'
 8327:                        .&escape($udom),homeserver($uname,$udom));
 8328:     if ($listing eq 'unknown_cmd') {
 8329:         if ($getpropath) {
 8330:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
 8331:         }
 8332:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
 8333:     }
 8334:     return $listing;
 8335: }
 8336: 
 8337: sub is_locked {
 8338:     my ($file_name, $domain, $user, $which) = @_;
 8339:     my @check;
 8340:     my $is_locked;
 8341:     push (@check,$file_name);
 8342:     my %locked = &get('file_permissions',\@check,
 8343: 		      $env{'user.domain'},$env{'user.name'});
 8344:     my ($tmp)=keys(%locked);
 8345:     if ($tmp=~/^error:/) { undef(%locked); }
 8346:     
 8347:     if (ref($locked{$file_name}) eq 'ARRAY') {
 8348:         $is_locked = 'false';
 8349:         foreach my $entry (@{$locked{$file_name}}) {
 8350:            if (ref($entry) eq 'ARRAY') {
 8351:                $is_locked = 'true';
 8352:                if (ref($which) eq 'ARRAY') {
 8353:                    push(@{$which},$entry);
 8354:                } else {
 8355:                    last;
 8356:                }
 8357:            }
 8358:        }
 8359:     } else {
 8360:         $is_locked = 'false';
 8361:     }
 8362:     return $is_locked;
 8363: }
 8364: 
 8365: sub declutter_portfile {
 8366:     my ($file) = @_;
 8367:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 8368:     return $file;
 8369: }
 8370: 
 8371: # ------------------------------------------------------------- Mark as Read Only
 8372: 
 8373: sub mark_as_readonly {
 8374:     my ($domain,$user,$files,$what) = @_;
 8375:     my %current_permissions = &dump('file_permissions',$domain,$user);
 8376:     my ($tmp)=keys(%current_permissions);
 8377:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 8378:     foreach my $file (@{$files}) {
 8379: 	$file = &declutter_portfile($file);
 8380:         push(@{$current_permissions{$file}},$what);
 8381:     }
 8382:     &put('file_permissions',\%current_permissions,$domain,$user);
 8383:     return;
 8384: }
 8385: 
 8386: # ------------------------------------------------------------Save Selected Files
 8387: 
 8388: sub save_selected_files {
 8389:     my ($user, $path, @files) = @_;
 8390:     my $filename = $user."savedfiles";
 8391:     my @other_files = &files_not_in_path($user, $path);
 8392:     open (OUT, '>'.$tmpdir.$filename);
 8393:     foreach my $file (@files) {
 8394:         print (OUT $env{'form.currentpath'}.$file."\n");
 8395:     }
 8396:     foreach my $file (@other_files) {
 8397:         print (OUT $file."\n");
 8398:     }
 8399:     close (OUT);
 8400:     return 'ok';
 8401: }
 8402: 
 8403: sub clear_selected_files {
 8404:     my ($user) = @_;
 8405:     my $filename = $user."savedfiles";
 8406:     open (OUT, '>'.LONCAPA::tempdir().$filename);
 8407:     print (OUT undef);
 8408:     close (OUT);
 8409:     return ("ok");    
 8410: }
 8411: 
 8412: sub files_in_path {
 8413:     my ($user, $path) = @_;
 8414:     my $filename = $user."savedfiles";
 8415:     my %return_files;
 8416:     open (IN, '<'.LONCAPA::tempdir().$filename);
 8417:     while (my $line_in = <IN>) {
 8418:         chomp ($line_in);
 8419:         my @paths_and_file = split (m!/!, $line_in);
 8420:         my $file_part = pop (@paths_and_file);
 8421:         my $path_part = join ('/', @paths_and_file);
 8422:         $path_part.='/';
 8423:         my $path_and_file = $path_part.$file_part;
 8424:         if ($path_part eq $path) {
 8425:             $return_files{$file_part}= 'selected';
 8426:         }
 8427:     }
 8428:     close (IN);
 8429:     return (\%return_files);
 8430: }
 8431: 
 8432: # called in portfolio select mode, to show files selected NOT in current directory
 8433: sub files_not_in_path {
 8434:     my ($user, $path) = @_;
 8435:     my $filename = $user."savedfiles";
 8436:     my @return_files;
 8437:     my $path_part;
 8438:     open(IN, '<'.LONCAPA::.$filename);
 8439:     while (my $line = <IN>) {
 8440:         #ok, I know it's clunky, but I want it to work
 8441:         my @paths_and_file = split(m|/|, $line);
 8442:         my $file_part = pop(@paths_and_file);
 8443:         chomp($file_part);
 8444:         my $path_part = join('/', @paths_and_file);
 8445:         $path_part .= '/';
 8446:         my $path_and_file = $path_part.$file_part;
 8447:         if ($path_part ne $path) {
 8448:             push(@return_files, ($path_and_file));
 8449:         }
 8450:     }
 8451:     close(OUT);
 8452:     return (@return_files);
 8453: }
 8454: 
 8455: #----------------------------------------------Get portfolio file permissions
 8456: 
 8457: sub get_portfile_permissions {
 8458:     my ($domain,$user) = @_;
 8459:     my %current_permissions = &dump('file_permissions',$domain,$user);
 8460:     my ($tmp)=keys(%current_permissions);
 8461:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 8462:     return \%current_permissions;
 8463: }
 8464: 
 8465: #---------------------------------------------Get portfolio file access controls
 8466: 
 8467: sub get_access_controls {
 8468:     my ($current_permissions,$group,$file) = @_;
 8469:     my %access;
 8470:     my $real_file = $file;
 8471:     $file =~ s/\.meta$//;
 8472:     if (defined($file)) {
 8473:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 8474:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 8475:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 8476:             }
 8477:         }
 8478:     } else {
 8479:         foreach my $key (keys(%{$current_permissions})) {
 8480:             if ($key =~ /\0accesscontrol$/) {
 8481:                 if (defined($group)) {
 8482:                     if ($key !~ m-^\Q$group\E/-) {
 8483:                         next;
 8484:                     }
 8485:                 }
 8486:                 my ($fullpath) = split(/\0/,$key);
 8487:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 8488:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 8489:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 8490:                     }
 8491:                 }
 8492:             }
 8493:         }
 8494:     }
 8495:     return %access;
 8496: }
 8497: 
 8498: sub modify_access_controls {
 8499:     my ($file_name,$changes,$domain,$user)=@_;
 8500:     my ($outcome,$deloutcome);
 8501:     my %store_permissions;
 8502:     my %new_values;
 8503:     my %new_control;
 8504:     my %translation;
 8505:     my @deletions = ();
 8506:     my $now = time;
 8507:     if (exists($$changes{'activate'})) {
 8508:         if (ref($$changes{'activate'}) eq 'HASH') {
 8509:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 8510:             my $numnew = scalar(@newitems);
 8511:             for (my $i=0; $i<$numnew; $i++) {
 8512:                 my $newkey = $newitems[$i];
 8513:                 my $newid = &Apache::loncommon::get_cgi_id();
 8514:                 if ($newkey =~ /^\d+:/) { 
 8515:                     $newkey =~ s/^(\d+)/$newid/;
 8516:                     $translation{$1} = $newid;
 8517:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 8518:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 8519:                     $translation{$1} = $newid;
 8520:                 }
 8521:                 $new_values{$file_name."\0".$newkey} = 
 8522:                                           $$changes{'activate'}{$newitems[$i]};
 8523:                 $new_control{$newkey} = $now;
 8524:             }
 8525:         }
 8526:     }
 8527:     my %todelete;
 8528:     my %changed_items;
 8529:     foreach my $action ('delete','update') {
 8530:         if (exists($$changes{$action})) {
 8531:             if (ref($$changes{$action}) eq 'HASH') {
 8532:                 foreach my $key (keys(%{$$changes{$action}})) {
 8533:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 8534:                     if ($action eq 'delete') { 
 8535:                         $todelete{$itemnum} = 1;
 8536:                     } else {
 8537:                         $changed_items{$itemnum} = $key;
 8538:                     }
 8539:                 }
 8540:             }
 8541:         }
 8542:     }
 8543:     # get lock on access controls for file.
 8544:     my $lockhash = {
 8545:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 8546:                                                        ':'.$env{'user.domain'},
 8547:                    }; 
 8548:     my $tries = 0;
 8549:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 8550:    
 8551:     while (($gotlock ne 'ok') && $tries <3) {
 8552:         $tries ++;
 8553:         sleep 1;
 8554:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 8555:     }
 8556:     if ($gotlock eq 'ok') {
 8557:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 8558:         my ($tmp)=keys(%curr_permissions);
 8559:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 8560:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 8561:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 8562:             if (ref($curr_controls) eq 'HASH') {
 8563:                 foreach my $control_item (keys(%{$curr_controls})) {
 8564:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 8565:                     if (defined($todelete{$itemnum})) {
 8566:                         push(@deletions,$file_name."\0".$control_item);
 8567:                     } else {
 8568:                         if (defined($changed_items{$itemnum})) {
 8569:                             $new_control{$changed_items{$itemnum}} = $now;
 8570:                             push(@deletions,$file_name."\0".$control_item);
 8571:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 8572:                         } else {
 8573:                             $new_control{$control_item} = $$curr_controls{$control_item};
 8574:                         }
 8575:                     }
 8576:                 }
 8577:             }
 8578:         }
 8579:         my ($group);
 8580:         if (&is_course($domain,$user)) {
 8581:             ($group,my $file) = split(/\//,$file_name,2);
 8582:         }
 8583:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 8584:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 8585:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 8586:         #  remove lock
 8587:         my @del_lock = ($file_name."\0".'locked_access_records');
 8588:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 8589:         my $sqlresult =
 8590:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
 8591:                                     $group);
 8592:     } else {
 8593:         $outcome = "error: could not obtain lockfile\n";  
 8594:     }
 8595:     return ($outcome,$deloutcome,\%new_values,\%translation);
 8596: }
 8597: 
 8598: sub make_public_indefinitely {
 8599:     my ($requrl) = @_;
 8600:     my $now = time;
 8601:     my $action = 'activate';
 8602:     my $aclnum = 0;
 8603:     if (&is_portfolio_url($requrl)) {
 8604:         my (undef,$udom,$unum,$file_name,$group) =
 8605:             &parse_portfolio_url($requrl);
 8606:         my $current_perms = &get_portfile_permissions($udom,$unum);
 8607:         my %access_controls = &get_access_controls($current_perms,
 8608:                                                    $group,$file_name);
 8609:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 8610:             my ($num,$scope,$end,$start) = 
 8611:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 8612:             if ($scope eq 'public') {
 8613:                 if ($start <= $now && $end == 0) {
 8614:                     $action = 'none';
 8615:                 } else {
 8616:                     $action = 'update';
 8617:                     $aclnum = $num;
 8618:                 }
 8619:                 last;
 8620:             }
 8621:         }
 8622:         if ($action eq 'none') {
 8623:              return 'ok';
 8624:         } else {
 8625:             my %changes;
 8626:             my $newend = 0;
 8627:             my $newstart = $now;
 8628:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 8629:             $changes{$action}{$newkey} = {
 8630:                 type => 'public',
 8631:                 time => {
 8632:                     start => $newstart,
 8633:                     end   => $newend,
 8634:                 },
 8635:             };
 8636:             my ($outcome,$deloutcome,$new_values,$translation) =
 8637:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 8638:             return $outcome;
 8639:         }
 8640:     } else {
 8641:         return 'invalid';
 8642:     }
 8643: }
 8644: 
 8645: #------------------------------------------------------Get Marked as Read Only
 8646: 
 8647: sub get_marked_as_readonly {
 8648:     my ($domain,$user,$what,$group) = @_;
 8649:     my $current_permissions = &get_portfile_permissions($domain,$user);
 8650:     my @readonly_files;
 8651:     my $cmp1=$what;
 8652:     if (ref($what)) { $cmp1=join('',@{$what}) };
 8653:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 8654:         if (defined($group)) {
 8655:             if ($file_name !~ m-^\Q$group\E/-) {
 8656:                 next;
 8657:             }
 8658:         }
 8659:         if (ref($value) eq "ARRAY"){
 8660:             foreach my $stored_what (@{$value}) {
 8661:                 my $cmp2=$stored_what;
 8662:                 if (ref($stored_what) eq 'ARRAY') {
 8663:                     $cmp2=join('',@{$stored_what});
 8664:                 }
 8665:                 if ($cmp1 eq $cmp2) {
 8666:                     push(@readonly_files, $file_name);
 8667:                     last;
 8668:                 } elsif (!defined($what)) {
 8669:                     push(@readonly_files, $file_name);
 8670:                     last;
 8671:                 }
 8672:             }
 8673:         }
 8674:     }
 8675:     return @readonly_files;
 8676: }
 8677: #-----------------------------------------------------------Get Marked as Read Only Hash
 8678: 
 8679: sub get_marked_as_readonly_hash {
 8680:     my ($current_permissions,$group,$what) = @_;
 8681:     my %readonly_files;
 8682:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 8683:         if (defined($group)) {
 8684:             if ($file_name !~ m-^\Q$group\E/-) {
 8685:                 next;
 8686:             }
 8687:         }
 8688:         if (ref($value) eq "ARRAY"){
 8689:             foreach my $stored_what (@{$value}) {
 8690:                 if (ref($stored_what) eq 'ARRAY') {
 8691:                     foreach my $lock_descriptor(@{$stored_what}) {
 8692:                         if ($lock_descriptor eq 'graded') {
 8693:                             $readonly_files{$file_name} = 'graded';
 8694:                         } elsif ($lock_descriptor eq 'handback') {
 8695:                             $readonly_files{$file_name} = 'handback';
 8696:                         } else {
 8697:                             if (!exists($readonly_files{$file_name})) {
 8698:                                 $readonly_files{$file_name} = 'locked';
 8699:                             }
 8700:                         }
 8701:                     }
 8702:                 } 
 8703:             }
 8704:         } 
 8705:     }
 8706:     return %readonly_files;
 8707: }
 8708: # ------------------------------------------------------------ Unmark as Read Only
 8709: 
 8710: sub unmark_as_readonly {
 8711:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 8712:     # for portfolio submissions, $what contains [$symb,$crsid] 
 8713:     my ($domain,$user,$what,$file_name,$group) = @_;
 8714:     $file_name = &declutter_portfile($file_name);
 8715:     my $symb_crs = $what;
 8716:     if (ref($what)) { $symb_crs=join('',@$what); }
 8717:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 8718:     my ($tmp)=keys(%current_permissions);
 8719:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 8720:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 8721:     foreach my $file (@readonly_files) {
 8722: 	my $clean_file = &declutter_portfile($file);
 8723: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 8724: 	my $current_locks = $current_permissions{$file};
 8725:         my @new_locks;
 8726:         my @del_keys;
 8727:         if (ref($current_locks) eq "ARRAY"){
 8728:             foreach my $locker (@{$current_locks}) {
 8729:                 my $compare=$locker;
 8730:                 if (ref($locker) eq 'ARRAY') {
 8731:                     $compare=join('',@{$locker});
 8732:                     if ($compare ne $symb_crs) {
 8733:                         push(@new_locks, $locker);
 8734:                     }
 8735:                 }
 8736:             }
 8737:             if (scalar(@new_locks) > 0) {
 8738:                 $current_permissions{$file} = \@new_locks;
 8739:             } else {
 8740:                 push(@del_keys, $file);
 8741:                 &del('file_permissions',\@del_keys, $domain, $user);
 8742:                 delete($current_permissions{$file});
 8743:             }
 8744:         }
 8745:     }
 8746:     &put('file_permissions',\%current_permissions,$domain,$user);
 8747:     return;
 8748: }
 8749: 
 8750: # ------------------------------------------------------------ Directory lister
 8751: 
 8752: sub dirlist {
 8753:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
 8754:     $uri=~s/^\///;
 8755:     $uri=~s/\/$//;
 8756:     my ($udom, $uname);
 8757:     if ($getuserdir) {
 8758:         $udom = $userdomain;
 8759:         $uname = $username;
 8760:     } else {
 8761:         (undef,$udom,$uname)=split(/\//,$uri);
 8762:         if(defined($userdomain)) {
 8763:             $udom = $userdomain;
 8764:         }
 8765:         if(defined($username)) {
 8766:             $uname = $username;
 8767:         }
 8768:     }
 8769:     my ($dirRoot,$listing,@listing_results);
 8770: 
 8771:     $dirRoot = $perlvar{'lonDocRoot'};
 8772:     if (defined($getpropath)) {
 8773:         $dirRoot = &propath($udom,$uname);
 8774:         $dirRoot =~ s/\/$//;
 8775:     } elsif (defined($getuserdir)) {
 8776:         my $subdir=$uname.'__';
 8777:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 8778:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
 8779:                    ."/$udom/$subdir/$uname";
 8780:     } elsif (defined($alternateRoot)) {
 8781:         $dirRoot = $alternateRoot;
 8782:     }
 8783: 
 8784:     if($udom) {
 8785:         if($uname) {
 8786:             my $uhome = &homeserver($uname,$udom);
 8787:             if ($uhome eq 'no_host') {
 8788:                 return ([],'no_host');
 8789:             }
 8790:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
 8791:                               .$getuserdir.':'.&escape($dirRoot)
 8792:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
 8793:             if ($listing eq 'unknown_cmd') {
 8794:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
 8795:             } else {
 8796:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 8797:             }
 8798:             if ($listing eq 'unknown_cmd') {
 8799:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
 8800:                 @listing_results = split(/:/,$listing);
 8801:             } else {
 8802:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 8803:             }
 8804:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
 8805:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
 8806:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 8807:                 return ([],$listing);
 8808:             } else {
 8809:                 return (\@listing_results);
 8810:             }
 8811:         } elsif(!$alternateRoot) {
 8812:             my (%allusers,%listerror);
 8813: 	    my %servers = &get_servers($udom,'library');
 8814:  	    foreach my $tryserver (keys(%servers)) {
 8815:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
 8816:                                   &escape($udom),$tryserver);
 8817:                 if ($listing eq 'unknown_cmd') {
 8818: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 8819: 				      $udom, $tryserver);
 8820:                 } else {
 8821:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
 8822:                 }
 8823: 		if ($listing eq 'unknown_cmd') {
 8824: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 8825: 				      $udom, $tryserver);
 8826: 		    @listing_results = split(/:/,$listing);
 8827: 		} else {
 8828: 		    @listing_results =
 8829: 			map { &unescape($_); } split(/:/,$listing);
 8830: 		}
 8831:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
 8832:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
 8833:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 8834:                     $listerror{$tryserver} = $listing;
 8835:                 } else {
 8836: 		    foreach my $line (@listing_results) {
 8837: 			my ($entry) = split(/&/,$line,2);
 8838: 			$allusers{$entry} = 1;
 8839: 		    }
 8840: 		}
 8841:             }
 8842:             my @alluserslist=();
 8843:             foreach my $user (sort(keys(%allusers))) {
 8844:                 push(@alluserslist,$user.'&user');
 8845:             }
 8846:             return (\@alluserslist);
 8847:         } else {
 8848:             return ([],'missing username');
 8849:         }
 8850:     } elsif(!defined($getpropath)) {
 8851:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
 8852:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
 8853:         return (\@all_domains);
 8854:     } else {
 8855:         return ([],'missing domain');
 8856:     }
 8857: }
 8858: 
 8859: # --------------------------------------------- GetFileTimestamp
 8860: # This function utilizes dirlist and returns the date stamp for
 8861: # when it was last modified.  It will also return an error of -1
 8862: # if an error occurs
 8863: 
 8864: sub GetFileTimestamp {
 8865:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
 8866:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 8867:     $studentName   = &LONCAPA::clean_username($studentName);
 8868:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
 8869:                                     undef,$getuserdir);
 8870:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 8871:         return -1;
 8872:     }
 8873:     if (ref($fileref) eq 'ARRAY') {
 8874:         my @stats = split('&',$fileref->[0]);
 8875:         # @stats contains first the filename, then the stat output
 8876:         return $stats[10]; # so this is 10 instead of 9.
 8877:     } else {
 8878:         return -1;
 8879:     }
 8880: }
 8881: 
 8882: sub stat_file {
 8883:     my ($uri) = @_;
 8884:     $uri = &clutter_with_no_wrapper($uri);
 8885: 
 8886:     my ($udom,$uname,$file);
 8887:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 8888: 	($udom,$uname,$file) =
 8889: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 8890: 	$file = 'userfiles/'.$file;
 8891:     }
 8892:     if ($uri =~ m-^/res/-) {
 8893: 	($udom,$uname) = 
 8894: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 8895: 	$file = $uri;
 8896:     }
 8897: 
 8898:     if (!$udom || !$uname || !$file) {
 8899: 	# unable to handle the uri
 8900: 	return ();
 8901:     }
 8902:     my $getpropath;
 8903:     if ($file =~ /^userfiles\//) {
 8904:         $getpropath = 1;
 8905:     }
 8906:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
 8907:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 8908:         return ();
 8909:     } else {
 8910:         if (ref($listref) eq 'ARRAY') {
 8911:             my @stats = split('&',$listref->[0]);
 8912: 	    shift(@stats); #filename is first
 8913: 	    return @stats;
 8914:         }
 8915:     }
 8916:     return ();
 8917: }
 8918: 
 8919: # -------------------------------------------------------- Value of a Condition
 8920: 
 8921: # gets the value of a specific preevaluated condition
 8922: #    stored in the string  $env{user.state.<cid>}
 8923: # or looks up a condition reference in the bighash and if if hasn't
 8924: # already been evaluated recurses into docondval to get the value of
 8925: # the condition, then memoizing it to 
 8926: #   $env{user.state.<cid>.<condition>}
 8927: sub directcondval {
 8928:     my $number=shift;
 8929:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 8930: 	&Apache::lonuserstate::evalstate();
 8931:     }
 8932:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 8933: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 8934:     } elsif ($number =~ /^_/) {
 8935: 	my $sub_condition;
 8936: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8937: 		&GDBM_READER(),0640)) {
 8938: 	    $sub_condition=$bighash{'conditions'.$number};
 8939: 	    untie(%bighash);
 8940: 	}
 8941: 	my $value = &docondval($sub_condition);
 8942: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
 8943: 	return $value;
 8944:     }
 8945:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 8946:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 8947:     } else {
 8948:        return 2;
 8949:     }
 8950: }
 8951: 
 8952: # get the collection of conditions for this resource
 8953: sub condval {
 8954:     my $condidx=shift;
 8955:     my $allpathcond='';
 8956:     foreach my $cond (split(/\|/,$condidx)) {
 8957: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 8958: 	    $allpathcond.=
 8959: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 8960: 	}
 8961:     }
 8962:     $allpathcond=~s/\|$//;
 8963:     return &docondval($allpathcond);
 8964: }
 8965: 
 8966: #evaluates an expression of conditions
 8967: sub docondval {
 8968:     my ($allpathcond) = @_;
 8969:     my $result=0;
 8970:     if ($env{'request.course.id'}
 8971: 	&& defined($allpathcond)) {
 8972: 	my $operand='|';
 8973: 	my @stack;
 8974: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 8975: 	    if ($chunk eq '(') {
 8976: 		push @stack,($operand,$result);
 8977: 	    } elsif ($chunk eq ')') {
 8978: 		my $before=pop @stack;
 8979: 		if (pop @stack eq '&') {
 8980: 		    $result=$result>$before?$before:$result;
 8981: 		} else {
 8982: 		    $result=$result>$before?$result:$before;
 8983: 		}
 8984: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 8985: 		$operand=$chunk;
 8986: 	    } else {
 8987: 		my $new=directcondval($chunk);
 8988: 		if ($operand eq '&') {
 8989: 		    $result=$result>$new?$new:$result;
 8990: 		} else {
 8991: 		    $result=$result>$new?$result:$new;
 8992: 		}
 8993: 	    }
 8994: 	}
 8995:     }
 8996:     return $result;
 8997: }
 8998: 
 8999: # ---------------------------------------------------- Devalidate courseresdata
 9000: 
 9001: sub devalidatecourseresdata {
 9002:     my ($coursenum,$coursedomain)=@_;
 9003:     my $hashid=$coursenum.':'.$coursedomain;
 9004:     &devalidate_cache_new('courseres',$hashid);
 9005: }
 9006: 
 9007: 
 9008: # --------------------------------------------------- Course Resourcedata Query
 9009: #
 9010: #  Parameters:
 9011: #      $coursenum    - Number of the course.
 9012: #      $coursedomain - Domain at which the course was created.
 9013: #  Returns:
 9014: #     A hash of the course parameters along (I think) with timestamps
 9015: #     and version info.
 9016: 
 9017: sub get_courseresdata {
 9018:     my ($coursenum,$coursedomain)=@_;
 9019:     my $coursehom=&homeserver($coursenum,$coursedomain);
 9020:     my $hashid=$coursenum.':'.$coursedomain;
 9021:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 9022:     my %dumpreply;
 9023:     unless (defined($cached)) {
 9024: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 9025: 	$result=\%dumpreply;
 9026: 	my ($tmp) = keys(%dumpreply);
 9027: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 9028: 	    &do_cache_new('courseres',$hashid,$result,600);
 9029: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 9030: 	    return $tmp;
 9031: 	} elsif ($tmp =~ /^(error)/) {
 9032: 	    $result=undef;
 9033: 	    &do_cache_new('courseres',$hashid,$result,600);
 9034: 	}
 9035:     }
 9036:     return $result;
 9037: }
 9038: 
 9039: sub devalidateuserresdata {
 9040:     my ($uname,$udom)=@_;
 9041:     my $hashid="$udom:$uname";
 9042:     &devalidate_cache_new('userres',$hashid);
 9043: }
 9044: 
 9045: sub get_userresdata {
 9046:     my ($uname,$udom)=@_;
 9047:     #most student don\'t have any data set, check if there is some data
 9048:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 9049: 
 9050:     my $hashid="$udom:$uname";
 9051:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 9052:     if (!defined($cached)) {
 9053: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 9054: 	$result=\%resourcedata;
 9055: 	&do_cache_new('userres',$hashid,$result,600);
 9056:     }
 9057:     my ($tmp)=keys(%$result);
 9058:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 9059: 	return $result;
 9060:     }
 9061:     #error 2 occurs when the .db doesn't exist
 9062:     if ($tmp!~/error: 2 /) {
 9063: 	&logthis("<font color=\"blue\">WARNING:".
 9064: 		 " Trying to get resource data for ".
 9065: 		 $uname." at ".$udom.": ".
 9066: 		 $tmp."</font>");
 9067:     } elsif ($tmp=~/error: 2 /) {
 9068: 	#&EXT_cache_set($udom,$uname);
 9069: 	&do_cache_new('userres',$hashid,undef,600);
 9070: 	undef($tmp); # not really an error so don't send it back
 9071:     }
 9072:     return $tmp;
 9073: }
 9074: #----------------------------------------------- resdata - return resource data
 9075: #  Purpose:
 9076: #    Return resource data for either users or for a course.
 9077: #  Parameters:
 9078: #     $name      - Course/user name.
 9079: #     $domain    - Name of the domain the user/course is registered on.
 9080: #     $type      - Type of thing $name is (must be 'course' or 'user'
 9081: #     @which     - Array of names of resources desired.
 9082: #  Returns:
 9083: #     The value of the first reasource in @which that is found in the
 9084: #     resource hash.
 9085: #  Exceptional Conditions:
 9086: #     If the $type passed in is not valid (not the string 'course' or 
 9087: #     'user', an undefined  reference is returned.
 9088: #     If none of the resources are found, an undef is returned
 9089: sub resdata {
 9090:     my ($name,$domain,$type,@which)=@_;
 9091:     my $result;
 9092:     if ($type eq 'course') {
 9093: 	$result=&get_courseresdata($name,$domain);
 9094:     } elsif ($type eq 'user') {
 9095: 	$result=&get_userresdata($name,$domain);
 9096:     }
 9097:     if (!ref($result)) { return $result; }    
 9098:     foreach my $item (@which) {
 9099: 	if (defined($result->{$item->[0]})) {
 9100: 	    return [$result->{$item->[0]},$item->[1]];
 9101: 	}
 9102:     }
 9103:     return undef;
 9104: }
 9105: 
 9106: #
 9107: # EXT resource caching routines
 9108: #
 9109: 
 9110: sub clear_EXT_cache_status {
 9111:     &delenv('cache.EXT.');
 9112: }
 9113: 
 9114: sub EXT_cache_status {
 9115:     my ($target_domain,$target_user) = @_;
 9116:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 9117:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 9118:         # We know already the user has no data
 9119:         return 1;
 9120:     } else {
 9121:         return 0;
 9122:     }
 9123: }
 9124: 
 9125: sub EXT_cache_set {
 9126:     my ($target_domain,$target_user) = @_;
 9127:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 9128:     #&appenv({$cachename => time});
 9129: }
 9130: 
 9131: # --------------------------------------------------------- Value of a Variable
 9132: sub EXT {
 9133: 
 9134:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
 9135:     unless ($varname) { return ''; }
 9136:     #get real user name/domain, courseid and symb
 9137:     my $courseid;
 9138:     my $publicuser;
 9139:     if ($symbparm) {
 9140: 	$symbparm=&get_symb_from_alias($symbparm);
 9141:     }
 9142:     if (!($uname && $udom)) {
 9143:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 9144:       if (!$symbparm) {	$symbparm=$cursymb; }
 9145:     } else {
 9146: 	$courseid=$env{'request.course.id'};
 9147:     }
 9148:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 9149:     my $rest;
 9150:     if (defined($therest[0])) {
 9151:        $rest=join('.',@therest);
 9152:     } else {
 9153:        $rest='';
 9154:     }
 9155: 
 9156:     my $qualifierrest=$qualifier;
 9157:     if ($rest) { $qualifierrest.='.'.$rest; }
 9158:     my $spacequalifierrest=$space;
 9159:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 9160:     if ($realm eq 'user') {
 9161: # --------------------------------------------------------------- user.resource
 9162: 	if ($space eq 'resource') {
 9163: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 9164: 		  || defined($Apache::lonhomework::parsing_a_task))
 9165: 		 &&
 9166: 		 ($symbparm eq &symbread()) ) {	
 9167: 		# if we are in the middle of processing the resource the
 9168: 		# get the value we are planning on committing
 9169:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 9170:                     return $Apache::lonhomework::results{$qualifierrest};
 9171:                 } else {
 9172:                     return $Apache::lonhomework::history{$qualifierrest};
 9173:                 }
 9174: 	    } else {
 9175: 		my %restored;
 9176: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 9177: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 9178: 		} else {
 9179: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 9180: 		}
 9181: 		return $restored{$qualifierrest};
 9182: 	    }
 9183: # ----------------------------------------------------------------- user.access
 9184:         } elsif ($space eq 'access') {
 9185: 	    # FIXME - not supporting calls for a specific user
 9186:             return &allowed($qualifier,$rest);
 9187: # ------------------------------------------ user.preferences, user.environment
 9188:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 9189: 	    if (($uname eq $env{'user.name'}) &&
 9190: 		($udom eq $env{'user.domain'})) {
 9191: 		return $env{join('.',('environment',$qualifierrest))};
 9192: 	    } else {
 9193: 		my %returnhash;
 9194: 		if (!$publicuser) {
 9195: 		    %returnhash=&userenvironment($udom,$uname,
 9196: 						 $qualifierrest);
 9197: 		}
 9198: 		return $returnhash{$qualifierrest};
 9199: 	    }
 9200: # ----------------------------------------------------------------- user.course
 9201:         } elsif ($space eq 'course') {
 9202: 	    # FIXME - not supporting calls for a specific user
 9203:             return $env{join('.',('request.course',$qualifier))};
 9204: # ------------------------------------------------------------------- user.role
 9205:         } elsif ($space eq 'role') {
 9206: 	    # FIXME - not supporting calls for a specific user
 9207:             my ($role,$where)=split(/\./,$env{'request.role'});
 9208:             if ($qualifier eq 'value') {
 9209: 		return $role;
 9210:             } elsif ($qualifier eq 'extent') {
 9211:                 return $where;
 9212:             }
 9213: # ----------------------------------------------------------------- user.domain
 9214:         } elsif ($space eq 'domain') {
 9215:             return $udom;
 9216: # ------------------------------------------------------------------- user.name
 9217:         } elsif ($space eq 'name') {
 9218:             return $uname;
 9219: # ---------------------------------------------------- Any other user namespace
 9220:         } else {
 9221: 	    my %reply;
 9222: 	    if (!$publicuser) {
 9223: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 9224: 	    }
 9225: 	    return $reply{$qualifierrest};
 9226:         }
 9227:     } elsif ($realm eq 'query') {
 9228: # ---------------------------------------------- pull stuff out of query string
 9229:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 9230: 						[$spacequalifierrest]);
 9231: 	return $env{'form.'.$spacequalifierrest}; 
 9232:    } elsif ($realm eq 'request') {
 9233: # ------------------------------------------------------------- request.browser
 9234:         if ($space eq 'browser') {
 9235:             return $env{'browser.'.$qualifier};
 9236: # ------------------------------------------------------------ request.filename
 9237:         } else {
 9238:             return $env{'request.'.$spacequalifierrest};
 9239:         }
 9240:     } elsif ($realm eq 'course') {
 9241: # ---------------------------------------------------------- course.description
 9242:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 9243:     } elsif ($realm eq 'resource') {
 9244: 
 9245: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 9246: 	    if (!$symbparm) { $symbparm=&symbread(); }
 9247: 	}
 9248: 
 9249: 	if ($space eq 'title') {
 9250: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 9251: 	    return &gettitle($symbparm);
 9252: 	}
 9253: 	
 9254: 	if ($space eq 'map') {
 9255: 	    my ($map) = &decode_symb($symbparm);
 9256: 	    return &symbread($map);
 9257: 	}
 9258: 	if ($space eq 'filename') {
 9259: 	    if ($symbparm) {
 9260: 		return &clutter((&decode_symb($symbparm))[2]);
 9261: 	    }
 9262: 	    return &hreflocation('',$env{'request.filename'});
 9263: 	}
 9264: 
 9265: 	my ($section, $group, @groups);
 9266: 	my ($courselevelm,$courselevel);
 9267: 	if ($symbparm && defined($courseid) && 
 9268: 	    $courseid eq $env{'request.course.id'}) {
 9269: 
 9270: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 9271: 
 9272: # ----------------------------------------------------- Cascading lookup scheme
 9273: 	    my $symbp=$symbparm;
 9274: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 9275: 
 9276: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 9277: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 9278: 
 9279: 	    if (($env{'user.name'} eq $uname) &&
 9280: 		($env{'user.domain'} eq $udom)) {
 9281: 		$section=$env{'request.course.sec'};
 9282:                 @groups = split(/:/,$env{'request.course.groups'});  
 9283:                 @groups=&sort_course_groups($courseid,@groups); 
 9284: 	    } else {
 9285: 		if (! defined($usection)) {
 9286: 		    $section=&getsection($udom,$uname,$courseid);
 9287: 		} else {
 9288: 		    $section = $usection;
 9289: 		}
 9290:                 @groups = &get_users_groups($udom,$uname,$courseid);
 9291: 	    }
 9292: 
 9293: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 9294: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 9295: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 9296: 
 9297: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 9298: 	    my $courselevelr=$courseid.'.'.$symbparm;
 9299: 	    $courselevelm=$courseid.'.'.$mapparm;
 9300: 
 9301: # ----------------------------------------------------------- first, check user
 9302: 
 9303: 	    my $userreply=&resdata($uname,$udom,'user',
 9304: 				       ([$courselevelr,'resource'],
 9305: 					[$courselevelm,'map'     ],
 9306: 					[$courselevel, 'course'  ]));
 9307: 	    if (defined($userreply)) { return &get_reply($userreply); }
 9308: 
 9309: # ------------------------------------------------ second, check some of course
 9310:             my $coursereply;
 9311:             if (@groups > 0) {
 9312:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 9313:                                        $mapparm,$spacequalifierrest);
 9314:                 if (defined($coursereply)) { return &get_reply($coursereply); }
 9315:             }
 9316: 
 9317: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 9318: 				  $env{'course.'.$courseid.'.domain'},
 9319: 				  'course',
 9320: 				  ([$seclevelr,   'resource'],
 9321: 				   [$seclevelm,   'map'     ],
 9322: 				   [$seclevel,    'course'  ],
 9323: 				   [$courselevelr,'resource']));
 9324: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 9325: 
 9326: # ------------------------------------------------------ third, check map parms
 9327: 	    my %parmhash=();
 9328: 	    my $thisparm='';
 9329: 	    if (tie(%parmhash,'GDBM_File',
 9330: 		    $env{'request.course.fn'}.'_parms.db',
 9331: 		    &GDBM_READER(),0640)) {
 9332: 		$thisparm=$parmhash{$symbparm};
 9333: 		untie(%parmhash);
 9334: 	    }
 9335: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
 9336: 	}
 9337: # ------------------------------------------ fourth, look in resource metadata
 9338: 
 9339: 	$spacequalifierrest=~s/\./\_/;
 9340: 	my $filename;
 9341: 	if (!$symbparm) { $symbparm=&symbread(); }
 9342: 	if ($symbparm) {
 9343: 	    $filename=(&decode_symb($symbparm))[2];
 9344: 	} else {
 9345: 	    $filename=$env{'request.filename'};
 9346: 	}
 9347: 	my $metadata=&metadata($filename,$spacequalifierrest);
 9348: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 9349: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 9350: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 9351: 
 9352: # ---------------------------------------------- fourth, look in rest of course
 9353: 	if ($symbparm && defined($courseid) && 
 9354: 	    $courseid eq $env{'request.course.id'}) {
 9355: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 9356: 				     $env{'course.'.$courseid.'.domain'},
 9357: 				     'course',
 9358: 				     ([$courselevelm,'map'   ],
 9359: 				      [$courselevel, 'course']));
 9360: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 9361: 	}
 9362: # ------------------------------------------------------------------ Cascade up
 9363: 	unless ($space eq '0') {
 9364: 	    my @parts=split(/_/,$space);
 9365: 	    my $id=pop(@parts);
 9366: 	    my $part=join('_',@parts);
 9367: 	    if ($part eq '') { $part='0'; }
 9368: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 9369: 				 $symbparm,$udom,$uname,$section,1);
 9370: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
 9371: 	}
 9372: 	if ($recurse) { return undef; }
 9373: 	my $pack_def=&packages_tab_default($filename,$varname);
 9374: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
 9375: # ---------------------------------------------------- Any other user namespace
 9376:     } elsif ($realm eq 'environment') {
 9377: # ----------------------------------------------------------------- environment
 9378: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 9379: 	    return $env{'environment.'.$spacequalifierrest};
 9380: 	} else {
 9381: 	    if ($uname eq 'anonymous' && $udom eq '') {
 9382: 		return '';
 9383: 	    }
 9384: 	    my %returnhash=&userenvironment($udom,$uname,
 9385: 					    $spacequalifierrest);
 9386: 	    return $returnhash{$spacequalifierrest};
 9387: 	}
 9388:     } elsif ($realm eq 'system') {
 9389: # ----------------------------------------------------------------- system.time
 9390: 	if ($space eq 'time') {
 9391: 	    return time;
 9392:         }
 9393:     } elsif ($realm eq 'server') {
 9394: # ----------------------------------------------------------------- system.time
 9395: 	if ($space eq 'name') {
 9396: 	    return $ENV{'SERVER_NAME'};
 9397:         }
 9398:     }
 9399:     return '';
 9400: }
 9401: 
 9402: sub get_reply {
 9403:     my ($reply_value) = @_;
 9404:     if (ref($reply_value) eq 'ARRAY') {
 9405:         if (wantarray) {
 9406: 	    return @$reply_value;
 9407:         }
 9408:         return $reply_value->[0];
 9409:     } else {
 9410:         return $reply_value;
 9411:     }
 9412: }
 9413: 
 9414: sub check_group_parms {
 9415:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
 9416:     my @groupitems = ();
 9417:     my $resultitem;
 9418:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
 9419:     foreach my $group (@{$groups}) {
 9420:         foreach my $level (@levels) {
 9421:              my $item = $courseid.'.['.$group.'].'.$level->[0];
 9422:              push(@groupitems,[$item,$level->[1]]);
 9423:         }
 9424:     }
 9425:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
 9426:                             $env{'course.'.$courseid.'.domain'},
 9427:                                      'course',@groupitems);
 9428:     return $coursereply;
 9429: }
 9430: 
 9431: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
 9432:     my ($courseid,@groups) = @_;
 9433:     @groups = sort(@groups);
 9434:     return @groups;
 9435: }
 9436: 
 9437: sub packages_tab_default {
 9438:     my ($uri,$varname)=@_;
 9439:     my (undef,$part,$name)=split(/\./,$varname);
 9440: 
 9441:     my (@extension,@specifics,$do_default);
 9442:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
 9443: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 9444: 	if ($pack_type eq 'default') {
 9445: 	    $do_default=1;
 9446: 	} elsif ($pack_type eq 'extension') {
 9447: 	    push(@extension,[$package,$pack_type,$pack_part]);
 9448: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
 9449: 	    # only look at packages defaults for packages that this id is
 9450: 	    push(@specifics,[$package,$pack_type,$pack_part]);
 9451: 	}
 9452:     }
 9453:     # first look for a package that matches the requested part id
 9454:     foreach my $package (@specifics) {
 9455: 	my (undef,$pack_type,$pack_part)=@{$package};
 9456: 	next if ($pack_part ne $part);
 9457: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 9458: 	    return $packagetab{"$pack_type&$name&default"};
 9459: 	}
 9460:     }
 9461:     # look for any possible matching non extension_ package
 9462:     foreach my $package (@specifics) {
 9463: 	my (undef,$pack_type,$pack_part)=@{$package};
 9464: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 9465: 	    return $packagetab{"$pack_type&$name&default"};
 9466: 	}
 9467: 	if ($pack_type eq 'part') { $pack_part='0'; }
 9468: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
 9469: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
 9470: 	}
 9471:     }
 9472:     # look for any posible extension_ match
 9473:     foreach my $package (@extension) {
 9474: 	my ($package,$pack_type)=@{$package};
 9475: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 9476: 	    return $packagetab{"$pack_type&$name&default"};
 9477: 	}
 9478: 	if (defined($packagetab{$package."&$name&default"})) {
 9479: 	    return $packagetab{$package."&$name&default"};
 9480: 	}
 9481:     }
 9482:     # look for a global default setting
 9483:     if ($do_default && defined($packagetab{"default&$name&default"})) {
 9484: 	return $packagetab{"default&$name&default"};
 9485:     }
 9486:     return undef;
 9487: }
 9488: 
 9489: sub add_prefix_and_part {
 9490:     my ($prefix,$part)=@_;
 9491:     my $keyroot;
 9492:     if (defined($prefix) && $prefix !~ /^__/) {
 9493: 	# prefix that has a part already
 9494: 	$keyroot=$prefix;
 9495:     } elsif (defined($prefix)) {
 9496: 	# prefix that is missing a part
 9497: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 9498:     } else {
 9499: 	# no prefix at all
 9500: 	if (defined($part)) { $keyroot='_'.$part; }
 9501:     }
 9502:     return $keyroot;
 9503: }
 9504: 
 9505: # ---------------------------------------------------------------- Get metadata
 9506: 
 9507: my %metaentry;
 9508: my %importedpartids;
 9509: sub metadata {
 9510:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 9511:     $uri=&declutter($uri);
 9512:     # if it is a non metadata possible uri return quickly
 9513:     if (($uri eq '') || 
 9514: 	(($uri =~ m|^/*adm/|) && 
 9515: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
 9516:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
 9517: 	return undef;
 9518:     }
 9519:     if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) 
 9520: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
 9521: 	return undef;
 9522:     }
 9523:     my $filename=$uri;
 9524:     $uri=~s/\.meta$//;
 9525: #
 9526: # Is the metadata already cached?
 9527: # Look at timestamp of caching
 9528: # Everything is cached by the main uri, libraries are never directly cached
 9529: #
 9530:     if (!defined($liburi)) {
 9531: 	my ($result,$cached)=&is_cached_new('meta',$uri);
 9532: 	if (defined($cached)) { return $result->{':'.$what}; }
 9533:     }
 9534:     {
 9535: # Imported parts would go here
 9536:         my %importedids=();
 9537:         my @origfileimportpartids=();
 9538:         my $importedparts=0;
 9539: #
 9540: # Is this a recursive call for a library?
 9541: #
 9542: #	if (! exists($metacache{$uri})) {
 9543: #	    $metacache{$uri}={};
 9544: #	}
 9545: 	my $cachetime = 60*60;
 9546:         if ($liburi) {
 9547: 	    $liburi=&declutter($liburi);
 9548:             $filename=$liburi;
 9549:         } else {
 9550: 	    &devalidate_cache_new('meta',$uri);
 9551: 	    undef(%metaentry);
 9552: 	}
 9553:         my %metathesekeys=();
 9554:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 9555: 	my $metastring;
 9556: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
 9557: 	    my $which = &hreflocation('','/'.($liburi || $uri));
 9558: 	    $metastring = 
 9559: 		&Apache::lonnet::ssi_body($which,
 9560: 					  ('grade_target' => 'meta'));
 9561: 	    $cachetime = 1; # only want this cached in the child not long term
 9562: 	} elsif (($uri !~ m -^(editupload)/-) && 
 9563:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
 9564: 	    my $file=&filelocation('',&clutter($filename));
 9565: 	    #push(@{$metaentry{$uri.'.file'}},$file);
 9566: 	    $metastring=&getfile($file);
 9567: 	}
 9568:         my $parser=HTML::LCParser->new(\$metastring);
 9569:         my $token;
 9570:         undef %metathesekeys;
 9571:         while ($token=$parser->get_token) {
 9572: 	    if ($token->[0] eq 'S') {
 9573: 		if (defined($token->[2]->{'package'})) {
 9574: #
 9575: # This is a package - get package info
 9576: #
 9577: 		    my $package=$token->[2]->{'package'};
 9578: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 9579: 		    if (defined($token->[2]->{'id'})) { 
 9580: 			$keyroot.='_'.$token->[2]->{'id'}; 
 9581: 		    }
 9582: 		    if ($metaentry{':packages'}) {
 9583: 			$metaentry{':packages'}.=','.$package.$keyroot;
 9584: 		    } else {
 9585: 			$metaentry{':packages'}=$package.$keyroot;
 9586: 		    }
 9587: 		    foreach my $pack_entry (keys(%packagetab)) {
 9588: 			my $part=$keyroot;
 9589: 			$part=~s/^\_//;
 9590: 			if ($pack_entry=~/^\Q$package\E\&/ || 
 9591: 			    $pack_entry=~/^\Q$package\E_0\&/) {
 9592: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
 9593: 			    # ignore package.tab specified default values
 9594:                             # here &package_tab_default() will fetch those
 9595: 			    if ($subp eq 'default') { next; }
 9596: 			    my $value=$packagetab{$pack_entry};
 9597: 			    my $unikey;
 9598: 			    if ($pack =~ /_0$/) {
 9599: 				$unikey='parameter_0_'.$name;
 9600: 				$part=0;
 9601: 			    } else {
 9602: 				$unikey='parameter'.$keyroot.'_'.$name;
 9603: 			    }
 9604: 			    if ($subp eq 'display') {
 9605: 				$value.=' [Part: '.$part.']';
 9606: 			    }
 9607: 			    $metaentry{':'.$unikey.'.part'}=$part;
 9608: 			    $metathesekeys{$unikey}=1;
 9609: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 9610: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
 9611: 			    }
 9612: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
 9613: 				$metaentry{':'.$unikey}=
 9614: 				    $metaentry{':'.$unikey.'.default'};
 9615: 			    }
 9616: 			}
 9617: 		    }
 9618: 		} else {
 9619: #
 9620: # This is not a package - some other kind of start tag
 9621: #
 9622: 		    my $entry=$token->[1];
 9623: 		    my $unikey='';
 9624: 
 9625: 		    if ($entry eq 'import') {
 9626: #
 9627: # Importing a library here
 9628: #
 9629:                         my $location=$parser->get_text('/import');
 9630:                         my $dir=$filename;
 9631:                         $dir=~s|[^/]*$||;
 9632:                         $location=&filelocation($dir,$location);
 9633:                        
 9634:                         my $importmode=$token->[2]->{'importmode'};
 9635:                         if ($importmode eq 'problem') {
 9636: # Import as problem/response
 9637:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 9638:                         } elsif ($importmode eq 'part') {
 9639: # Import as part(s)
 9640:                            $importedparts=1;
 9641: # We need to get the original file and the imported file to get the part order correct
 9642: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
 9643: # Load and inspect original file
 9644:                            if ($#origfileimportpartids<0) {
 9645:                               undef(%importedpartids);
 9646:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
 9647:                               my $origfile=&getfile($origfilelocation);
 9648:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
 9649:                            }
 9650: 
 9651: # Load and inspect imported file
 9652:                            my $impfile=&getfile($location);
 9653:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
 9654:                            if ($#impfilepartids>=0) {
 9655: # This problem had parts
 9656:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
 9657:                            } else {
 9658: # Importing by turning a single problem into a problem part
 9659: # It gets the import-tags ID as part-ID
 9660:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
 9661:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
 9662:                            }
 9663:                         } else {
 9664: # Normal import
 9665:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 9666:                            if (defined($token->[2]->{'id'})) {
 9667:                               $unikey.='_'.$token->[2]->{'id'};
 9668:                            }
 9669:                         }
 9670: 
 9671: 			if ($depthcount<20) {
 9672: 			    my $metadata = 
 9673: 				&metadata($uri,'keys', $location,$unikey,
 9674: 					  $depthcount+1);
 9675: 			    foreach my $meta (split(',',$metadata)) {
 9676: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
 9677: 				$metathesekeys{$meta}=1;
 9678: 			    }
 9679: 			
 9680:                         }
 9681: 		    } else {
 9682: #
 9683: # Not importing, some other kind of non-package, non-library start tag
 9684: # 
 9685:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
 9686:                         if (defined($token->[2]->{'id'})) {
 9687:                             $unikey.='_'.$token->[2]->{'id'};
 9688:                         }
 9689: 			if (defined($token->[2]->{'name'})) { 
 9690: 			    $unikey.='_'.$token->[2]->{'name'}; 
 9691: 			}
 9692: 			$metathesekeys{$unikey}=1;
 9693: 			foreach my $param (@{$token->[3]}) {
 9694: 			    $metaentry{':'.$unikey.'.'.$param} =
 9695: 				$token->[2]->{$param};
 9696: 			}
 9697: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
 9698: 			my $default=$metaentry{':'.$unikey.'.default'};
 9699: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
 9700: 		 # only ws inside the tag, and not in default, so use default
 9701: 		 # as value
 9702: 			    $metaentry{':'.$unikey}=$default;
 9703: 			} elsif ( $internaltext =~ /\S/ ) {
 9704: 		  # something interesting inside the tag
 9705: 			    $metaentry{':'.$unikey}=$internaltext;
 9706: 			} else {
 9707: 		  # no interesting values, don't set a default
 9708: 			}
 9709: # end of not-a-package not-a-library import
 9710: 		    }
 9711: # end of not-a-package start tag
 9712: 		}
 9713: # the next is the end of "start tag"
 9714: 	    }
 9715: 	}
 9716: 	my ($extension) = ($uri =~ /\.(\w+)$/);
 9717: 	$extension = lc($extension);
 9718: 	if ($extension eq 'htm') { $extension='html'; }
 9719: 
 9720: 	foreach my $key (keys(%packagetab)) {
 9721: 	    #no specific packages #how's our extension
 9722: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
 9723: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
 9724: 					 \%metathesekeys);
 9725: 	}
 9726: 
 9727: 	if (!exists($metaentry{':packages'})
 9728: 	    || $packagetab{"import_defaults&extension_$extension"}) {
 9729: 	    foreach my $key (keys(%packagetab)) {
 9730: 		#no specific packages well let's get default then
 9731: 		if ($key!~/^default&/) { next; }
 9732: 		&metadata_create_package_def($uri,$key,'default',
 9733: 					     \%metathesekeys);
 9734: 	    }
 9735: 	}
 9736: # are there custom rights to evaluate
 9737: 	if ($metaentry{':copyright'} eq 'custom') {
 9738: 
 9739:     #
 9740:     # Importing a rights file here
 9741:     #
 9742: 	    unless ($depthcount) {
 9743: 		my $location=$metaentry{':customdistributionfile'};
 9744: 		my $dir=$filename;
 9745: 		$dir=~s|[^/]*$||;
 9746: 		$location=&filelocation($dir,$location);
 9747: 		my $rights_metadata =
 9748: 		    &metadata($uri,'keys',$location,'_rights',
 9749: 			      $depthcount+1);
 9750: 		foreach my $rights (split(',',$rights_metadata)) {
 9751: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
 9752: 		    $metathesekeys{$rights}=1;
 9753: 		}
 9754: 	    }
 9755: 	}
 9756: 	# uniqifiy package listing
 9757: 	my %seen;
 9758: 	my @uniq_packages =
 9759: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
 9760: 	$metaentry{':packages'} = join(',',@uniq_packages);
 9761: 
 9762:         if ($importedparts) {
 9763: # We had imported parts and need to rebuild partorder
 9764:            $metaentry{':partorder'}='';
 9765:            $metathesekeys{'partorder'}=1;
 9766:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
 9767:                if ($origfileimportpartids[$index] eq 'part') {
 9768: # original part, part of the problem
 9769:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
 9770:                } else {
 9771: # we have imported parts at this position
 9772:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
 9773:                }
 9774:            }
 9775:            $metaentry{':partorder'}=~s/^\,//;
 9776:         }
 9777: 
 9778: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
 9779: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
 9780: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
 9781: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
 9782: # this is the end of "was not already recently cached
 9783:     }
 9784:     return $metaentry{':'.$what};
 9785: }
 9786: 
 9787: sub metadata_create_package_def {
 9788:     my ($uri,$key,$package,$metathesekeys)=@_;
 9789:     my ($pack,$name,$subp)=split(/\&/,$key);
 9790:     if ($subp eq 'default') { next; }
 9791:     
 9792:     if (defined($metaentry{':packages'})) {
 9793: 	$metaentry{':packages'}.=','.$package;
 9794:     } else {
 9795: 	$metaentry{':packages'}=$package;
 9796:     }
 9797:     my $value=$packagetab{$key};
 9798:     my $unikey;
 9799:     $unikey='parameter_0_'.$name;
 9800:     $metaentry{':'.$unikey.'.part'}=0;
 9801:     $$metathesekeys{$unikey}=1;
 9802:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 9803: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
 9804:     }
 9805:     if (defined($metaentry{':'.$unikey.'.default'})) {
 9806: 	$metaentry{':'.$unikey}=
 9807: 	    $metaentry{':'.$unikey.'.default'};
 9808:     }
 9809: }
 9810: 
 9811: sub metadata_generate_part0 {
 9812:     my ($metadata,$metacache,$uri) = @_;
 9813:     my %allnames;
 9814:     foreach my $metakey (keys(%$metadata)) {
 9815: 	if ($metakey=~/^parameter\_(.*)/) {
 9816: 	  my $part=$$metacache{':'.$metakey.'.part'};
 9817: 	  my $name=$$metacache{':'.$metakey.'.name'};
 9818: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
 9819: 	    $allnames{$name}=$part;
 9820: 	  }
 9821: 	}
 9822:     }
 9823:     foreach my $name (keys(%allnames)) {
 9824:       $$metadata{"parameter_0_$name"}=1;
 9825:       my $key=":parameter_0_$name";
 9826:       $$metacache{"$key.part"}='0';
 9827:       $$metacache{"$key.name"}=$name;
 9828:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
 9829: 					   $allnames{$name}.'_'.$name.
 9830: 					   '.type'};
 9831:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
 9832: 			     '.display'};
 9833:       my $expr='[Part: '.$allnames{$name}.']';
 9834:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
 9835:       $$metacache{"$key.display"}=$olddis;
 9836:     }
 9837: }
 9838: 
 9839: # ------------------------------------------------------ Devalidate title cache
 9840: 
 9841: sub devalidate_title_cache {
 9842:     my ($url)=@_;
 9843:     if (!$env{'request.course.id'}) { return; }
 9844:     my $symb=&symbread($url);
 9845:     if (!$symb) { return; }
 9846:     my $key=$env{'request.course.id'}."\0".$symb;
 9847:     &devalidate_cache_new('title',$key);
 9848: }
 9849: 
 9850: # ------------------------------------------------- Get the title of a course
 9851: 
 9852: sub current_course_title {
 9853:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
 9854: }
 9855: # ------------------------------------------------- Get the title of a resource
 9856: 
 9857: sub gettitle {
 9858:     my $urlsymb=shift;
 9859:     my $symb=&symbread($urlsymb);
 9860:     if ($symb) {
 9861: 	my $key=$env{'request.course.id'}."\0".$symb;
 9862: 	my ($result,$cached)=&is_cached_new('title',$key);
 9863: 	if (defined($cached)) { 
 9864: 	    return $result;
 9865: 	}
 9866: 	my ($map,$resid,$url)=&decode_symb($symb);
 9867: 	my $title='';
 9868: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
 9869: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
 9870: 	} else {
 9871: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9872: 		    &GDBM_READER(),0640)) {
 9873: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
 9874: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
 9875: 		untie(%bighash);
 9876: 	    }
 9877: 	}
 9878: 	$title=~s/\&colon\;/\:/gs;
 9879: 	if ($title) {
 9880: # Remember both $symb and $title for dynamic metadata
 9881:             $accesshash{$symb.'___crstitle'}=$title;
 9882:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
 9883: # Cache this title and then return it
 9884: 	    return &do_cache_new('title',$key,$title,600);
 9885: 	}
 9886: 	$urlsymb=$url;
 9887:     }
 9888:     my $title=&metadata($urlsymb,'title');
 9889:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
 9890:     return $title;
 9891: }
 9892: 
 9893: sub get_slot {
 9894:     my ($which,$cnum,$cdom)=@_;
 9895:     if (!$cnum || !$cdom) {
 9896: 	(undef,my $courseid)=&whichuser();
 9897: 	$cdom=$env{'course.'.$courseid.'.domain'};
 9898: 	$cnum=$env{'course.'.$courseid.'.num'};
 9899:     }
 9900:     my $key=join("\0",'slots',$cdom,$cnum,$which);
 9901:     my %slotinfo;
 9902:     if (exists($remembered{$key})) {
 9903: 	$slotinfo{$which} = $remembered{$key};
 9904:     } else {
 9905: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
 9906: 	&Apache::lonhomework::showhash(%slotinfo);
 9907: 	my ($tmp)=keys(%slotinfo);
 9908: 	if ($tmp=~/^error:/) { return (); }
 9909: 	$remembered{$key} = $slotinfo{$which};
 9910:     }
 9911:     if (ref($slotinfo{$which}) eq 'HASH') {
 9912: 	return %{$slotinfo{$which}};
 9913:     }
 9914:     return $slotinfo{$which};
 9915: }
 9916: 
 9917: sub get_reservable_slots {
 9918:     my ($cnum,$cdom,$uname,$udom) = @_;
 9919:     my $now = time;
 9920:     my $reservable_info;
 9921:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
 9922:     if (exists($remembered{$key})) {
 9923:         $reservable_info = $remembered{$key};
 9924:     } else {
 9925:         my %resv;
 9926:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
 9927:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
 9928:         $reservable_info = \%resv;
 9929:         $remembered{$key} = $reservable_info;
 9930:     }
 9931:     return $reservable_info;
 9932: }
 9933: 
 9934: sub get_course_slots {
 9935:     my ($cnum,$cdom) = @_;
 9936:     my $hashid=$cnum.':'.$cdom;
 9937:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
 9938:     if (defined($cached)) {
 9939:         if (ref($result) eq 'HASH') {
 9940:             return %{$result};
 9941:         }
 9942:     } else {
 9943:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
 9944:         my ($tmp) = keys(%slots);
 9945:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 9946:             &Apache::lonnet::do_cache_new('allslots',$hashid,\%slots,600);
 9947:             return %slots;
 9948:         }
 9949:     }
 9950:     return;
 9951: }
 9952: 
 9953: sub devalidate_slots_cache {
 9954:     my ($cnum,$cdom)=@_;
 9955:     my $hashid=$cnum.':'.$cdom;
 9956:     &devalidate_cache_new('allslots',$hashid);
 9957: }
 9958: 
 9959: sub get_coursechange {
 9960:     my ($cdom,$cnum) = @_;
 9961:     if ($cdom eq '' || $cnum eq '') {
 9962:         return unless ($env{'request.course.id'});
 9963:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9964:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9965:     }
 9966:     my $hashid=$cdom.'_'.$cnum;
 9967:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
 9968:     if ((defined($cached)) && ($change ne '')) {
 9969:         return $change;
 9970:     } else {
 9971:         my %crshash;
 9972:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
 9973:         if ($crshash{'internal.contentchange'} eq '') {
 9974:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
 9975:             if ($change eq '') {
 9976:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
 9977:                 $change = $crshash{'internal.created'};
 9978:             }
 9979:         } else {
 9980:             $change = $crshash{'internal.contentchange'};
 9981:         }
 9982:         my $cachetime = 600;
 9983:         &do_cache_new('crschange',$hashid,$change,$cachetime);
 9984:     }
 9985:     return $change;
 9986: }
 9987: 
 9988: sub devalidate_coursechange_cache {
 9989:     my ($cnum,$cdom)=@_;
 9990:     my $hashid=$cnum.':'.$cdom;
 9991:     &devalidate_cache_new('crschange',$hashid);
 9992: }
 9993: 
 9994: # ------------------------------------------------- Update symbolic store links
 9995: 
 9996: sub symblist {
 9997:     my ($mapname,%newhash)=@_;
 9998:     $mapname=&deversion(&declutter($mapname));
 9999:     my %hash;
10000:     if (($env{'request.course.fn'}) && (%newhash)) {
10001:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
10002:                       &GDBM_WRCREAT(),0640)) {
10003: 	    foreach my $url (keys(%newhash)) {
10004: 		next if ($url eq 'last_known'
10005: 			 && $env{'form.no_update_last_known'});
10006: 		$hash{declutter($url)}=&encode_symb($mapname,
10007: 						    $newhash{$url}->[1],
10008: 						    $newhash{$url}->[0]);
10009:             }
10010:             if (untie(%hash)) {
10011: 		return 'ok';
10012:             }
10013:         }
10014:     }
10015:     return 'error';
10016: }
10017: 
10018: # --------------------------------------------------------------- Verify a symb
10019: 
10020: sub symbverify {
10021:     my ($symb,$thisurl)=@_;
10022:     my $thisfn=$thisurl;
10023:     $thisfn=&declutter($thisfn);
10024: # direct jump to resource in page or to a sequence - will construct own symbs
10025:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
10026: # check URL part
10027:     my ($map,$resid,$url)=&decode_symb($symb);
10028: 
10029:     unless ($url eq $thisfn) { return 0; }
10030: 
10031:     $symb=&symbclean($symb);
10032:     $thisurl=&deversion($thisurl);
10033:     $thisfn=&deversion($thisfn);
10034: 
10035:     my %bighash;
10036:     my $okay=0;
10037: 
10038:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10039:                             &GDBM_READER(),0640)) {
10040:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
10041:             $thisurl =~ s/\?.+$//;
10042:         }
10043:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
10044:         unless ($ids) {
10045:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
10046:             $ids=$bighash{$idkey};
10047:         }
10048:         if ($ids) {
10049: # ------------------------------------------------------------------- Has ID(s)
10050: 	    foreach my $id (split(/\,/,$ids)) {
10051: 	       my ($mapid,$resid)=split(/\./,$id);
10052:                if ($thisfn =~ m{^/adm/wrapper/ext/}) {
10053:                    $symb =~ s/\?.+$//;
10054:                }
10055:                if (
10056:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
10057:    eq $symb) { 
10058: 		   if (($env{'request.role.adv'}) ||
10059: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
10060:                        ($thisurl eq '/adm/navmaps')) {
10061: 		       $okay=1; 
10062: 		   }
10063: 	       }
10064: 	   }
10065:         }
10066: 	untie(%bighash);
10067:     }
10068:     return $okay;
10069: }
10070: 
10071: # --------------------------------------------------------------- Clean-up symb
10072: 
10073: sub symbclean {
10074:     my $symb=shift;
10075:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10076: # remove version from map
10077:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
10078: 
10079: # remove version from URL
10080:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
10081: 
10082: # remove wrapper
10083: 
10084:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
10085:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
10086:     return $symb;
10087: }
10088: 
10089: # ---------------------------------------------- Split symb to find map and url
10090: 
10091: sub encode_symb {
10092:     my ($map,$resid,$url)=@_;
10093:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
10094: }
10095: 
10096: sub decode_symb {
10097:     my $symb=shift;
10098:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10099:     my ($map,$resid,$url)=split(/___/,$symb);
10100:     return (&fixversion($map),$resid,&fixversion($url));
10101: }
10102: 
10103: sub fixversion {
10104:     my $fn=shift;
10105:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
10106:     my %bighash;
10107:     my $uri=&clutter($fn);
10108:     my $key=$env{'request.course.id'}.'_'.$uri;
10109: # is this cached?
10110:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
10111:     if (defined($cached)) { return $result; }
10112: # unfortunately not cached, or expired
10113:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10114: 	    &GDBM_READER(),0640)) {
10115:  	if ($bighash{'version_'.$uri}) {
10116:  	    my $version=$bighash{'version_'.$uri};
10117:  	    unless (($version eq 'mostrecent') || 
10118: 		    ($version==&getversion($uri))) {
10119:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
10120:  	    }
10121:  	}
10122:  	untie %bighash;
10123:     }
10124:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
10125: }
10126: 
10127: sub deversion {
10128:     my $url=shift;
10129:     $url=~s/\.\d+\.(\w+)$/\.$1/;
10130:     return $url;
10131: }
10132: 
10133: # ------------------------------------------------------ Return symb list entry
10134: 
10135: sub symbread {
10136:     my ($thisfn,$donotrecurse)=@_;
10137:     my $cache_str='request.symbread.cached.'.$thisfn;
10138:     if (defined($env{$cache_str})) {
10139:         if (($thisfn) || ($env{$cache_str} ne '')) {
10140:             return $env{$cache_str};
10141:         }
10142:     }
10143: # no filename provided? try from environment
10144:     unless ($thisfn) {
10145:         if ($env{'request.symb'}) {
10146: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
10147: 	}
10148: 	$thisfn=$env{'request.filename'};
10149:     }
10150:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
10151: # is that filename actually a symb? Verify, clean, and return
10152:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
10153: 	if (&symbverify($thisfn,$1)) {
10154: 	    return $env{$cache_str}=&symbclean($thisfn);
10155: 	}
10156:     }
10157:     $thisfn=declutter($thisfn);
10158:     my %hash;
10159:     my %bighash;
10160:     my $syval='';
10161:     if (($env{'request.course.fn'}) && ($thisfn)) {
10162:         my $targetfn = $thisfn;
10163:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
10164:             $targetfn = 'adm/wrapper/'.$thisfn;
10165:         }
10166: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
10167: 	    $targetfn=$1;
10168: 	}
10169:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
10170:                       &GDBM_READER(),0640)) {
10171: 	    $syval=$hash{$targetfn};
10172:             untie(%hash);
10173:         }
10174: # ---------------------------------------------------------- There was an entry
10175:         if ($syval) {
10176: 	    #unless ($syval=~/\_\d+$/) {
10177: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
10178: 		    #&appenv({'request.ambiguous' => $thisfn});
10179: 		    #return $env{$cache_str}='';
10180: 		#}    
10181: 		#$syval.=$1;
10182: 	    #}
10183:         } else {
10184: # ------------------------------------------------------- Was not in symb table
10185:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10186:                             &GDBM_READER(),0640)) {
10187: # ---------------------------------------------- Get ID(s) for current resource
10188:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
10189:               unless ($ids) { 
10190:                  $ids=$bighash{'ids_/'.$thisfn};
10191:               }
10192:               unless ($ids) {
10193: # alias?
10194: 		  $ids=$bighash{'mapalias_'.$thisfn};
10195:               }
10196:               if ($ids) {
10197: # ------------------------------------------------------------------- Has ID(s)
10198:                  my @possibilities=split(/\,/,$ids);
10199:                  if ($#possibilities==0) {
10200: # ----------------------------------------------- There is only one possibility
10201: 		     my ($mapid,$resid)=split(/\./,$ids);
10202: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
10203: 						    $resid,$thisfn);
10204:                  } elsif (!$donotrecurse) {
10205: # ------------------------------------------ There is more than one possibility
10206:                      my $realpossible=0;
10207:                      foreach my $id (@possibilities) {
10208: 			 my $file=$bighash{'src_'.$id};
10209:                          if (&allowed('bre',$file)) {
10210:          		    my ($mapid,$resid)=split(/\./,$id);
10211:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
10212: 				$realpossible++;
10213:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
10214: 						    $resid,$thisfn);
10215:                             }
10216: 			 }
10217:                      }
10218: 		     if ($realpossible!=1) { $syval=''; }
10219:                  } else {
10220:                      $syval='';
10221:                  }
10222: 	      }
10223:               untie(%bighash)
10224:            }
10225:         }
10226:         if ($syval) {
10227: 	    return $env{$cache_str}=$syval;
10228:         }
10229:     }
10230:     &appenv({'request.ambiguous' => $thisfn});
10231:     return $env{$cache_str}='';
10232: }
10233: 
10234: # ---------------------------------------------------------- Return random seed
10235: 
10236: sub numval {
10237:     my $txt=shift;
10238:     $txt=~tr/A-J/0-9/;
10239:     $txt=~tr/a-j/0-9/;
10240:     $txt=~tr/K-T/0-9/;
10241:     $txt=~tr/k-t/0-9/;
10242:     $txt=~tr/U-Z/0-5/;
10243:     $txt=~tr/u-z/0-5/;
10244:     $txt=~s/\D//g;
10245:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
10246:     return int($txt);
10247: }
10248: 
10249: sub numval2 {
10250:     my $txt=shift;
10251:     $txt=~tr/A-J/0-9/;
10252:     $txt=~tr/a-j/0-9/;
10253:     $txt=~tr/K-T/0-9/;
10254:     $txt=~tr/k-t/0-9/;
10255:     $txt=~tr/U-Z/0-5/;
10256:     $txt=~tr/u-z/0-5/;
10257:     $txt=~s/\D//g;
10258:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10259:     my $total;
10260:     foreach my $val (@txts) { $total+=$val; }
10261:     if ($_64bit) { if ($total > 2**32) { return -1; } }
10262:     return int($total);
10263: }
10264: 
10265: sub numval3 {
10266:     use integer;
10267:     my $txt=shift;
10268:     $txt=~tr/A-J/0-9/;
10269:     $txt=~tr/a-j/0-9/;
10270:     $txt=~tr/K-T/0-9/;
10271:     $txt=~tr/k-t/0-9/;
10272:     $txt=~tr/U-Z/0-5/;
10273:     $txt=~tr/u-z/0-5/;
10274:     $txt=~s/\D//g;
10275:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10276:     my $total;
10277:     foreach my $val (@txts) { $total+=$val; }
10278:     if ($_64bit) { $total=(($total<<32)>>32); }
10279:     return $total;
10280: }
10281: 
10282: sub digest {
10283:     my ($data)=@_;
10284:     my $digest=&Digest::MD5::md5($data);
10285:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
10286:     my ($e,$f);
10287:     {
10288:         use integer;
10289:         $e=($a+$b);
10290:         $f=($c+$d);
10291:         if ($_64bit) {
10292:             $e=(($e<<32)>>32);
10293:             $f=(($f<<32)>>32);
10294:         }
10295:     }
10296:     if (wantarray) {
10297: 	return ($e,$f);
10298:     } else {
10299: 	my $g;
10300: 	{
10301: 	    use integer;
10302: 	    $g=($e+$f);
10303: 	    if ($_64bit) {
10304: 		$g=(($g<<32)>>32);
10305: 	    }
10306: 	}
10307: 	return $g;
10308:     }
10309: }
10310: 
10311: sub latest_rnd_algorithm_id {
10312:     return '64bit5';
10313: }
10314: 
10315: sub get_rand_alg {
10316:     my ($courseid)=@_;
10317:     if (!$courseid) { $courseid=(&whichuser())[1]; }
10318:     if ($courseid) {
10319: 	return $env{"course.$courseid.rndseed"};
10320:     }
10321:     return &latest_rnd_algorithm_id();
10322: }
10323: 
10324: sub validCODE {
10325:     my ($CODE)=@_;
10326:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
10327:     return 0;
10328: }
10329: 
10330: sub getCODE {
10331:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
10332:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
10333: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
10334: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
10335: 	return $Apache::lonhomework::history{'resource.CODE'};
10336:     }
10337:     return undef;
10338: }
10339: #
10340: #  Determines the random seed for a specific context:
10341: #
10342: # parameters:
10343: #   symb      - in course context the symb for the seed.
10344: #   course_id - The course id of the form domain_coursenum.
10345: #   domain    - Domain for the user.
10346: #   course    - Course for the user.
10347: #   cenv      - environment of the course.
10348: #
10349: # NOTE:
10350: #   All parameters are picked out of the environment if missing
10351: #   or not defined.
10352: #   If a symb cannot be determined the current time is used instead.
10353: #
10354: #  For a given well defined symb, courside, domain, username,
10355: #  and course environment, the seed is reproducible.
10356: #
10357: sub rndseed {
10358:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
10359:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
10360:     if (!defined($symb)) {
10361: 	unless ($symb=$wsymb) { return time; }
10362:     }
10363:     if (!defined $courseid) { 
10364: 	$courseid=$wcourseid; 
10365:     }
10366:     if (!defined $domain) { $domain=$wdomain; }
10367:     if (!defined $username) { $username=$wusername }
10368: 
10369:     my $which;
10370:     if (defined($cenv->{'rndseed'})) {
10371: 	$which = $cenv->{'rndseed'};
10372:     } else {
10373: 	$which =&get_rand_alg($courseid);
10374:     }
10375:     if (defined(&getCODE())) {
10376: 
10377: 	if ($which eq '64bit5') {
10378: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
10379: 	} elsif ($which eq '64bit4') {
10380: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
10381: 	} else {
10382: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
10383: 	}
10384:     } elsif ($which eq '64bit5') {
10385: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
10386:     } elsif ($which eq '64bit4') {
10387: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
10388:     } elsif ($which eq '64bit3') {
10389: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
10390:     } elsif ($which eq '64bit2') {
10391: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
10392:     } elsif ($which eq '64bit') {
10393: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
10394:     }
10395:     return &rndseed_32bit($symb,$courseid,$domain,$username);
10396: }
10397: 
10398: sub rndseed_32bit {
10399:     my ($symb,$courseid,$domain,$username)=@_;
10400:     {
10401: 	use integer;
10402: 	my $symbchck=unpack("%32C*",$symb) << 27;
10403: 	my $symbseed=numval($symb) << 22;
10404: 	my $namechck=unpack("%32C*",$username) << 17;
10405: 	my $nameseed=numval($username) << 12;
10406: 	my $domainseed=unpack("%32C*",$domain) << 7;
10407: 	my $courseseed=unpack("%32C*",$courseid);
10408: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
10409: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10410: 	#&logthis("rndseed :$num:$symb");
10411: 	if ($_64bit) { $num=(($num<<32)>>32); }
10412: 	return $num;
10413:     }
10414: }
10415: 
10416: sub rndseed_64bit {
10417:     my ($symb,$courseid,$domain,$username)=@_;
10418:     {
10419: 	use integer;
10420: 	my $symbchck=unpack("%32S*",$symb) << 21;
10421: 	my $symbseed=numval($symb) << 10;
10422: 	my $namechck=unpack("%32S*",$username);
10423: 	
10424: 	my $nameseed=numval($username) << 21;
10425: 	my $domainseed=unpack("%32S*",$domain) << 10;
10426: 	my $courseseed=unpack("%32S*",$courseid);
10427: 	
10428: 	my $num1=$symbchck+$symbseed+$namechck;
10429: 	my $num2=$nameseed+$domainseed+$courseseed;
10430: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10431: 	#&logthis("rndseed :$num:$symb");
10432: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10433: 	return "$num1,$num2";
10434:     }
10435: }
10436: 
10437: sub rndseed_64bit2 {
10438:     my ($symb,$courseid,$domain,$username)=@_;
10439:     {
10440: 	use integer;
10441: 	# strings need to be an even # of cahracters long, it it is odd the
10442:         # last characters gets thrown away
10443: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
10444: 	my $symbseed=numval($symb) << 10;
10445: 	my $namechck=unpack("%32S*",$username.' ');
10446: 	
10447: 	my $nameseed=numval($username) << 21;
10448: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
10449: 	my $courseseed=unpack("%32S*",$courseid.' ');
10450: 	
10451: 	my $num1=$symbchck+$symbseed+$namechck;
10452: 	my $num2=$nameseed+$domainseed+$courseseed;
10453: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10454: 	#&logthis("rndseed :$num:$symb");
10455: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10456: 	return "$num1,$num2";
10457:     }
10458: }
10459: 
10460: sub rndseed_64bit3 {
10461:     my ($symb,$courseid,$domain,$username)=@_;
10462:     {
10463: 	use integer;
10464: 	# strings need to be an even # of cahracters long, it it is odd the
10465:         # last characters gets thrown away
10466: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
10467: 	my $symbseed=numval2($symb) << 10;
10468: 	my $namechck=unpack("%32S*",$username.' ');
10469: 	
10470: 	my $nameseed=numval2($username) << 21;
10471: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
10472: 	my $courseseed=unpack("%32S*",$courseid.' ');
10473: 	
10474: 	my $num1=$symbchck+$symbseed+$namechck;
10475: 	my $num2=$nameseed+$domainseed+$courseseed;
10476: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10477: 	#&logthis("rndseed :$num1:$num2:$_64bit");
10478: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10479: 	
10480: 	return "$num1:$num2";
10481:     }
10482: }
10483: 
10484: sub rndseed_64bit4 {
10485:     my ($symb,$courseid,$domain,$username)=@_;
10486:     {
10487: 	use integer;
10488: 	# strings need to be an even # of cahracters long, it it is odd the
10489:         # last characters gets thrown away
10490: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
10491: 	my $symbseed=numval3($symb) << 10;
10492: 	my $namechck=unpack("%32S*",$username.' ');
10493: 	
10494: 	my $nameseed=numval3($username) << 21;
10495: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
10496: 	my $courseseed=unpack("%32S*",$courseid.' ');
10497: 	
10498: 	my $num1=$symbchck+$symbseed+$namechck;
10499: 	my $num2=$nameseed+$domainseed+$courseseed;
10500: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10501: 	#&logthis("rndseed :$num1:$num2:$_64bit");
10502: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10503: 	
10504: 	return "$num1:$num2";
10505:     }
10506: }
10507: 
10508: sub rndseed_64bit5 {
10509:     my ($symb,$courseid,$domain,$username)=@_;
10510:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
10511:     return "$num1:$num2";
10512: }
10513: 
10514: sub rndseed_CODE_64bit {
10515:     my ($symb,$courseid,$domain,$username)=@_;
10516:     {
10517: 	use integer;
10518: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
10519: 	my $symbseed=numval2($symb);
10520: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
10521: 	my $CODEseed=numval(&getCODE());
10522: 	my $courseseed=unpack("%32S*",$courseid.' ');
10523: 	my $num1=$symbseed+$CODEchck;
10524: 	my $num2=$CODEseed+$courseseed+$symbchck;
10525: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
10526: 	#&logthis("rndseed :$num1:$num2:$symb");
10527: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
10528: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
10529: 	return "$num1:$num2";
10530:     }
10531: }
10532: 
10533: sub rndseed_CODE_64bit4 {
10534:     my ($symb,$courseid,$domain,$username)=@_;
10535:     {
10536: 	use integer;
10537: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
10538: 	my $symbseed=numval3($symb);
10539: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
10540: 	my $CODEseed=numval3(&getCODE());
10541: 	my $courseseed=unpack("%32S*",$courseid.' ');
10542: 	my $num1=$symbseed+$CODEchck;
10543: 	my $num2=$CODEseed+$courseseed+$symbchck;
10544: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
10545: 	#&logthis("rndseed :$num1:$num2:$symb");
10546: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
10547: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
10548: 	return "$num1:$num2";
10549:     }
10550: }
10551: 
10552: sub rndseed_CODE_64bit5 {
10553:     my ($symb,$courseid,$domain,$username)=@_;
10554:     my $code = &getCODE();
10555:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
10556:     return "$num1:$num2";
10557: }
10558: 
10559: sub setup_random_from_rndseed {
10560:     my ($rndseed)=@_;
10561:     if ($rndseed =~/([,:])/) {
10562: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
10563: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
10564:     } else {
10565: 	&Math::Random::random_set_seed_from_phrase($rndseed);
10566:     }
10567: }
10568: 
10569: sub latest_receipt_algorithm_id {
10570:     return 'receipt3';
10571: }
10572: 
10573: sub recunique {
10574:     my $fucourseid=shift;
10575:     my $unique;
10576:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
10577: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
10578: 	$unique=$env{"course.$fucourseid.internal.encseed"};
10579:     } else {
10580: 	$unique=$perlvar{'lonReceipt'};
10581:     }
10582:     return unpack("%32C*",$unique);
10583: }
10584: 
10585: sub recprefix {
10586:     my $fucourseid=shift;
10587:     my $prefix;
10588:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
10589: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
10590: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
10591:     } else {
10592: 	$prefix=$perlvar{'lonHostID'};
10593:     }
10594:     return unpack("%32C*",$prefix);
10595: }
10596: 
10597: sub ireceipt {
10598:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
10599: 
10600:     my $return =&recprefix($fucourseid).'-';
10601: 
10602:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
10603: 	$env{'request.state'} eq 'construct') {
10604: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
10605: 	return $return;
10606:     }
10607: 
10608:     my $cuname=unpack("%32C*",$funame);
10609:     my $cudom=unpack("%32C*",$fudom);
10610:     my $cucourseid=unpack("%32C*",$fucourseid);
10611:     my $cusymb=unpack("%32C*",$fusymb);
10612:     my $cunique=&recunique($fucourseid);
10613:     my $cpart=unpack("%32S*",$part);
10614:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
10615: 
10616: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
10617: 			       
10618: 	$return.= ($cunique%$cuname+
10619: 		   $cunique%$cudom+
10620: 		   $cusymb%$cuname+
10621: 		   $cusymb%$cudom+
10622: 		   $cucourseid%$cuname+
10623: 		   $cucourseid%$cudom+
10624: 		   $cpart%$cuname+
10625: 		   $cpart%$cudom);
10626:     } else {
10627: 	$return.= ($cunique%$cuname+
10628: 		   $cunique%$cudom+
10629: 		   $cusymb%$cuname+
10630: 		   $cusymb%$cudom+
10631: 		   $cucourseid%$cuname+
10632: 		   $cucourseid%$cudom);
10633:     }
10634:     return $return;
10635: }
10636: 
10637: sub receipt {
10638:     my ($part)=@_;
10639:     my ($symb,$courseid,$domain,$name) = &whichuser();
10640:     return &ireceipt($name,$domain,$courseid,$symb,$part);
10641: }
10642: 
10643: sub whichuser {
10644:     my ($passedsymb)=@_;
10645:     my ($symb,$courseid,$domain,$name,$publicuser);
10646:     if (defined($env{'form.grade_symb'})) {
10647: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
10648: 	my $allowed=&allowed('vgr',$tmp_courseid);
10649: 	if (!$allowed &&
10650: 	    exists($env{'request.course.sec'}) &&
10651: 	    $env{'request.course.sec'} !~ /^\s*$/) {
10652: 	    $allowed=&allowed('vgr',$tmp_courseid.
10653: 			      '/'.$env{'request.course.sec'});
10654: 	}
10655: 	if ($allowed) {
10656: 	    ($symb)=&get_env_multiple('form.grade_symb');
10657: 	    $courseid=$tmp_courseid;
10658: 	    ($domain)=&get_env_multiple('form.grade_domain');
10659: 	    ($name)=&get_env_multiple('form.grade_username');
10660: 	    return ($symb,$courseid,$domain,$name,$publicuser);
10661: 	}
10662:     }
10663:     if (!$passedsymb) {
10664: 	$symb=&symbread();
10665:     } else {
10666: 	$symb=$passedsymb;
10667:     }
10668:     $courseid=$env{'request.course.id'};
10669:     $domain=$env{'user.domain'};
10670:     $name=$env{'user.name'};
10671:     if ($name eq 'public' && $domain eq 'public') {
10672: 	if (!defined($env{'form.username'})) {
10673: 	    $env{'form.username'}.=time.rand(10000000);
10674: 	}
10675: 	$name.=$env{'form.username'};
10676:     }
10677:     return ($symb,$courseid,$domain,$name,$publicuser);
10678: 
10679: }
10680: 
10681: # ------------------------------------------------------------ Serves up a file
10682: # returns either the contents of the file or 
10683: # -1 if the file doesn't exist
10684: #
10685: # if the target is a file that was uploaded via DOCS, 
10686: # a check will be made to see if a current copy exists on the local server,
10687: # if it does this will be served, otherwise a copy will be retrieved from
10688: # the home server for the course and stored in /home/httpd/html/userfiles on
10689: # the local server.   
10690: 
10691: sub getfile {
10692:     my ($file) = @_;
10693:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
10694:     &repcopy($file);
10695:     return &readfile($file);
10696: }
10697: 
10698: sub repcopy_userfile {
10699:     my ($file)=@_;
10700:     my $londocroot = $perlvar{'lonDocRoot'};
10701:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
10702:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
10703:     my ($cdom,$cnum,$filename) = 
10704: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
10705:     my $uri="/uploaded/$cdom/$cnum/$filename";
10706:     if (-e "$file") {
10707: # we already have a local copy, check it out
10708: 	my @fileinfo = stat($file);
10709: 	my $rtncode;
10710: 	my $info;
10711: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
10712: 	if ($lwpresp ne 'ok') {
10713: # there is no such file anymore, even though we had a local copy
10714: 	    if ($rtncode eq '404') {
10715: 		unlink($file);
10716: 	    }
10717: 	    return -1;
10718: 	}
10719: 	if ($info < $fileinfo[9]) {
10720: # nice, the file we have is up-to-date, just say okay
10721: 	    return 'ok';
10722: 	} else {
10723: # the file is outdated, get rid of it
10724: 	    unlink($file);
10725: 	}
10726:     }
10727: # one way or the other, at this point, we don't have the file
10728: # construct the correct path for the file
10729:     my @parts = ($cdom,$cnum); 
10730:     if ($filename =~ m|^(.+)/[^/]+$|) {
10731: 	push @parts, split(/\//,$1);
10732:     }
10733:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
10734:     foreach my $part (@parts) {
10735: 	$path .= '/'.$part;
10736: 	if (!-e $path) {
10737: 	    mkdir($path,0770);
10738: 	}
10739:     }
10740: # now the path exists for sure
10741: # get a user agent
10742:     my $ua=new LWP::UserAgent;
10743:     my $transferfile=$file.'.in.transfer';
10744: # FIXME: this should flock
10745:     if (-e $transferfile) { return 'ok'; }
10746:     my $request;
10747:     $uri=~s/^\///;
10748:     my $homeserver = &homeserver($cnum,$cdom);
10749:     my $protocol = $protocol{$homeserver};
10750:     $protocol = 'http' if ($protocol ne 'https');
10751:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
10752:     my $response=$ua->request($request,$transferfile);
10753: # did it work?
10754:     if ($response->is_error()) {
10755: 	unlink($transferfile);
10756: 	&logthis("Userfile repcopy failed for $uri");
10757: 	return -1;
10758:     }
10759: # worked, rename the transfer file
10760:     rename($transferfile,$file);
10761:     return 'ok';
10762: }
10763: 
10764: sub tokenwrapper {
10765:     my $uri=shift;
10766:     $uri=~s|^https?\://([^/]+)||;
10767:     $uri=~s|^/||;
10768:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
10769:     my $token=$1;
10770:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
10771:     if ($udom && $uname && $file) {
10772: 	$file=~s|(\?\.*)*$||;
10773:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
10774:         my $homeserver = &homeserver($uname,$udom);
10775:         my $protocol = $protocol{$homeserver};
10776:         $protocol = 'http' if ($protocol ne 'https');
10777:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
10778:                (($uri=~/\?/)?'&':'?').'token='.$token.
10779:                                '&tokenissued='.$perlvar{'lonHostID'};
10780:     } else {
10781:         return '/adm/notfound.html';
10782:     }
10783: }
10784: 
10785: # call with reqtype HEAD: get last modification time
10786: # call with reqtype GET: get the file contents
10787: # Do not call this with reqtype GET for large files! It loads everything into memory
10788: #
10789: sub getuploaded {
10790:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
10791:     $uri=~s/^\///;
10792:     my $homeserver = &homeserver($cnum,$cdom);
10793:     my $protocol = $protocol{$homeserver};
10794:     $protocol = 'http' if ($protocol ne 'https');
10795:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
10796:     my $ua=new LWP::UserAgent;
10797:     my $request=new HTTP::Request($reqtype,$uri);
10798:     my $response=$ua->request($request);
10799:     $$rtncode = $response->code;
10800:     if (! $response->is_success()) {
10801: 	return 'failed';
10802:     }      
10803:     if ($reqtype eq 'HEAD') {
10804: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
10805:     } elsif ($reqtype eq 'GET') {
10806: 	$$info = $response->content;
10807:     }
10808:     return 'ok';
10809: }
10810: 
10811: sub readfile {
10812:     my $file = shift;
10813:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
10814:     my $fh;
10815:     open($fh,"<$file");
10816:     my $a='';
10817:     while (my $line = <$fh>) { $a .= $line; }
10818:     return $a;
10819: }
10820: 
10821: sub filelocation {
10822:     my ($dir,$file) = @_;
10823:     my $location;
10824:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
10825: 
10826:     if ($file =~ m-^/adm/-) {
10827: 	$file=~s-^/adm/wrapper/-/-;
10828: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
10829:     }
10830: 
10831:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
10832:         $location = $file;
10833:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
10834:         my ($udom,$uname,$filename)=
10835:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
10836:         my $home=&homeserver($uname,$udom);
10837:         my $is_me=0;
10838:         my @ids=&current_machine_ids();
10839:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
10840:         if ($is_me) {
10841:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
10842:         } else {
10843:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
10844:   	      $udom.'/'.$uname.'/'.$filename;
10845:         }
10846:     } elsif ($file =~ m-^/adm/-) {
10847: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
10848:     } else {
10849:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
10850:         $file=~s:^/(res|priv)/:/:;
10851:         my $space=$1;
10852:         if ( !( $file =~ m:^/:) ) {
10853:             $location = $dir. '/'.$file;
10854:         } else {
10855:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
10856:         }
10857:     }
10858:     $location=~s://+:/:g; # remove duplicate /
10859:     while ($location=~m{/\.\./}) {
10860: 	if ($location =~ m{/[^/]+/\.\./}) {
10861: 	    $location=~ s{/[^/]+/\.\./}{/}g;
10862: 	} else {
10863: 	    $location=~ s{/\.\./}{/}g;
10864: 	}
10865:     } #remove dir/..
10866:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
10867:     return $location;
10868: }
10869: 
10870: sub hreflocation {
10871:     my ($dir,$file)=@_;
10872:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
10873: 	$file=filelocation($dir,$file);
10874:     } elsif ($file=~m-^/adm/-) {
10875: 	$file=~s-^/adm/wrapper/-/-;
10876: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
10877:     }
10878:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
10879: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
10880:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
10881: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
10882: 	        {/uploaded/$1/$2/}x;
10883:     }
10884:     if ($file=~ m{^/userfiles/}) {
10885: 	$file =~ s{^/userfiles/}{/uploaded/};
10886:     }
10887:     return $file;
10888: }
10889: 
10890: 
10891: 
10892: 
10893: 
10894: sub current_machine_domains {
10895:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
10896: }
10897: 
10898: sub machine_domains {
10899:     my ($hostname) = @_;
10900:     my @domains;
10901:     my %hostname = &all_hostnames();
10902:     while( my($id, $name) = each(%hostname)) {
10903: #	&logthis("-$id-$name-$hostname-");
10904: 	if ($hostname eq $name) {
10905: 	    push(@domains,&host_domain($id));
10906: 	}
10907:     }
10908:     return @domains;
10909: }
10910: 
10911: sub current_machine_ids {
10912:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
10913: }
10914: 
10915: sub machine_ids {
10916:     my ($hostname) = @_;
10917:     $hostname ||= &hostname($perlvar{'lonHostID'});
10918:     my @ids;
10919:     my %name_to_host = &all_names();
10920:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
10921: 	return @{ $name_to_host{$hostname} };
10922:     }
10923:     return;
10924: }
10925: 
10926: sub additional_machine_domains {
10927:     my @domains;
10928:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
10929:     while( my $line = <$fh>) {
10930:         $line =~ s/\s//g;
10931:         push(@domains,$line);
10932:     }
10933:     return @domains;
10934: }
10935: 
10936: sub default_login_domain {
10937:     my $domain = $perlvar{'lonDefDomain'};
10938:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
10939:     foreach my $posdom (&current_machine_domains(),
10940:                         &additional_machine_domains()) {
10941:         if (lc($posdom) eq lc($testdomain)) {
10942:             $domain=$posdom;
10943:             last;
10944:         }
10945:     }
10946:     return $domain;
10947: }
10948: 
10949: # ------------------------------------------------------------- Declutters URLs
10950: 
10951: sub declutter {
10952:     my $thisfn=shift;
10953:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
10954:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
10955:     $thisfn=~s/^\///;
10956:     $thisfn=~s|^adm/wrapper/||;
10957:     $thisfn=~s|^adm/coursedocs/showdoc/||;
10958:     $thisfn=~s/^res\///;
10959:     $thisfn=~s/^priv\///;
10960:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
10961:         $thisfn=~s/\?.+$//;
10962:     }
10963:     return $thisfn;
10964: }
10965: 
10966: # ------------------------------------------------------------- Clutter up URLs
10967: 
10968: sub clutter {
10969:     my $thisfn='/'.&declutter(shift);
10970:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
10971: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
10972:        $thisfn='/res'.$thisfn; 
10973:     }
10974:     if ($thisfn !~m|^/adm|) {
10975: 	if ($thisfn =~ m|^/ext/|) {
10976: 	    $thisfn='/adm/wrapper'.$thisfn;
10977: 	} else {
10978: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
10979: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
10980: 	    if ($embstyle eq 'ssi'
10981: 		|| ($embstyle eq 'hdn')
10982: 		|| ($embstyle eq 'rat')
10983: 		|| ($embstyle eq 'prv')
10984: 		|| ($embstyle eq 'ign')) {
10985: 		#do nothing with these
10986: 	    } elsif (($embstyle eq 'img') 
10987: 		|| ($embstyle eq 'emb')
10988: 		|| ($embstyle eq 'wrp')) {
10989: 		$thisfn='/adm/wrapper'.$thisfn;
10990: 	    } elsif ($embstyle eq 'unk'
10991: 		     && $thisfn!~/\.(sequence|page)$/) {
10992: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
10993: 	    } else {
10994: #		&logthis("Got a blank emb style");
10995: 	    }
10996: 	}
10997:     }
10998:     return $thisfn;
10999: }
11000: 
11001: sub clutter_with_no_wrapper {
11002:     my $uri = &clutter(shift);
11003:     if ($uri =~ m-^/adm/-) {
11004: 	$uri =~ s-^/adm/wrapper/-/-;
11005: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
11006:     }
11007:     return $uri;
11008: }
11009: 
11010: sub freeze_escape {
11011:     my ($value)=@_;
11012:     if (ref($value)) {
11013: 	$value=&nfreeze($value);
11014: 	return '__FROZEN__'.&escape($value);
11015:     }
11016:     return &escape($value);
11017: }
11018: 
11019: 
11020: sub thaw_unescape {
11021:     my ($value)=@_;
11022:     if ($value =~ /^__FROZEN__/) {
11023: 	substr($value,0,10,undef);
11024: 	$value=&unescape($value);
11025: 	return &thaw($value);
11026:     }
11027:     return &unescape($value);
11028: }
11029: 
11030: sub correct_line_ends {
11031:     my ($result)=@_;
11032:     $$result =~s/\r\n/\n/mg;
11033:     $$result =~s/\r/\n/mg;
11034: }
11035: # ================================================================ Main Program
11036: 
11037: sub goodbye {
11038:    &logthis("Starting Shut down");
11039: #not converted to using infrastruture and probably shouldn't be
11040:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
11041: #converted
11042: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
11043:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
11044: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
11045: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
11046: #1.1 only
11047: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
11048: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
11049: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
11050: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
11051:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
11052:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
11053:    &logthis(sprintf("%-20s is %s",'hits',$hits));
11054:    &flushcourselogs();
11055:    &logthis("Shutting down");
11056: }
11057: 
11058: sub get_dns {
11059:     my ($url,$func,$ignore_cache) = @_;
11060:     if (!$ignore_cache) {
11061: 	my ($content,$cached)=
11062: 	    &Apache::lonnet::is_cached_new('dns',$url);
11063: 	if ($cached) {
11064: 	    &$func($content);
11065: 	    return;
11066: 	}
11067:     }
11068: 
11069:     my %alldns;
11070:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11071:     foreach my $dns (<$config>) {
11072: 	next if ($dns !~ /^\^(\S*)/x);
11073:         my $line = $1;
11074:         my ($host,$protocol) = split(/:/,$line);
11075:         if ($protocol ne 'https') {
11076:             $protocol = 'http';
11077:         }
11078: 	$alldns{$host} = $protocol;
11079:     }
11080:     while (%alldns) {
11081: 	my ($dns) = keys(%alldns);
11082: 	my $ua=new LWP::UserAgent;
11083:         $ua->timeout(30);
11084: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
11085: 	my $response=$ua->request($request);
11086:         delete($alldns{$dns});
11087: 	next if ($response->is_error());
11088: 	my @content = split("\n",$response->content);
11089: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
11090: 	&$func(\@content);
11091: 	return;
11092:     }
11093:     close($config);
11094:     my $which = (split('/',$url))[3];
11095:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
11096:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
11097:     my @content = <$config>;
11098:     &$func(\@content);
11099:     return;
11100: }
11101: # ------------------------------------------------------------ Read domain file
11102: {
11103:     my $loaded;
11104:     my %domain;
11105: 
11106:     sub parse_domain_tab {
11107: 	my ($lines) = @_;
11108: 	foreach my $line (@$lines) {
11109: 	    next if ($line =~ /^(\#|\s*$ )/x);
11110: 
11111: 	    chomp($line);
11112: 	    my ($name,@elements) = split(/:/,$line,9);
11113: 	    my %this_domain;
11114: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
11115: 			       'lang_def', 'city', 'longi', 'lati',
11116: 			       'primary') {
11117: 		$this_domain{$field} = shift(@elements);
11118: 	    }
11119: 	    $domain{$name} = \%this_domain;
11120: 	}
11121:     }
11122: 
11123:     sub reset_domain_info {
11124: 	undef($loaded);
11125: 	undef(%domain);
11126:     }
11127: 
11128:     sub load_domain_tab {
11129: 	my ($ignore_cache) = @_;
11130: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
11131: 	my $fh;
11132: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
11133: 	    my @lines = <$fh>;
11134: 	    &parse_domain_tab(\@lines);
11135: 	}
11136: 	close($fh);
11137: 	$loaded = 1;
11138:     }
11139: 
11140:     sub domain {
11141: 	&load_domain_tab() if (!$loaded);
11142: 
11143: 	my ($name,$what) = @_;
11144: 	return if ( !exists($domain{$name}) );
11145: 
11146: 	if (!$what) {
11147: 	    return $domain{$name}{'description'};
11148: 	}
11149: 	return $domain{$name}{$what};
11150:     }
11151: 
11152:     sub domain_info {
11153:         &load_domain_tab() if (!$loaded);
11154:         return %domain;
11155:     }
11156: 
11157: }
11158: 
11159: 
11160: # ------------------------------------------------------------- Read hosts file
11161: {
11162:     my %hostname;
11163:     my %hostdom;
11164:     my %libserv;
11165:     my $loaded;
11166:     my %name_to_host;
11167:     my %internetdom;
11168:     my %LC_dns_serv;
11169: 
11170:     sub parse_hosts_tab {
11171: 	my ($file) = @_;
11172: 	foreach my $configline (@$file) {
11173: 	    next if ($configline =~ /^(\#|\s*$ )/x);
11174:             chomp($configline);
11175: 	    if ($configline =~ /^\^/) {
11176:                 if ($configline =~ /^\^([\w.\-]+)/) {
11177:                     $LC_dns_serv{$1} = 1;
11178:                 }
11179:                 next;
11180:             }
11181: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
11182: 	    $name=~s/\s//g;
11183: 	    if ($id && $domain && $role && $name) {
11184: 		$hostname{$id}=$name;
11185: 		push(@{$name_to_host{$name}}, $id);
11186: 		$hostdom{$id}=$domain;
11187: 		if ($role eq 'library') { $libserv{$id}=$name; }
11188:                 if (defined($protocol)) {
11189:                     if ($protocol eq 'https') {
11190:                         $protocol{$id} = $protocol;
11191:                     } else {
11192:                         $protocol{$id} = 'http'; 
11193:                     }
11194:                 } else {
11195:                     $protocol{$id} = 'http';
11196:                 }
11197:                 if (defined($intdom)) {
11198:                     $internetdom{$id} = $intdom;
11199:                 }
11200: 	    }
11201: 	}
11202:     }
11203:     
11204:     sub reset_hosts_info {
11205: 	&purge_remembered();
11206: 	&reset_domain_info();
11207: 	&reset_hosts_ip_info();
11208: 	undef(%name_to_host);
11209: 	undef(%hostname);
11210: 	undef(%hostdom);
11211: 	undef(%libserv);
11212: 	undef($loaded);
11213:     }
11214: 
11215:     sub load_hosts_tab {
11216: 	my ($ignore_cache) = @_;
11217: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
11218: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11219: 	my @config = <$config>;
11220: 	&parse_hosts_tab(\@config);
11221: 	close($config);
11222: 	$loaded=1;
11223:     }
11224: 
11225:     sub hostname {
11226: 	&load_hosts_tab() if (!$loaded);
11227: 
11228: 	my ($lonid) = @_;
11229: 	return $hostname{$lonid};
11230:     }
11231: 
11232:     sub all_hostnames {
11233: 	&load_hosts_tab() if (!$loaded);
11234: 
11235: 	return %hostname;
11236:     }
11237: 
11238:     sub all_names {
11239: 	&load_hosts_tab() if (!$loaded);
11240: 
11241: 	return %name_to_host;
11242:     }
11243: 
11244:     sub all_host_domain {
11245:         &load_hosts_tab() if (!$loaded);
11246:         return %hostdom;
11247:     }
11248: 
11249:     sub is_library {
11250: 	&load_hosts_tab() if (!$loaded);
11251: 
11252: 	return exists($libserv{$_[0]});
11253:     }
11254: 
11255:     sub all_library {
11256: 	&load_hosts_tab() if (!$loaded);
11257: 
11258: 	return %libserv;
11259:     }
11260: 
11261:     sub unique_library {
11262: 	#2x reverse removes all hostnames that appear more than once
11263:         my %unique = reverse &all_library();
11264:         return reverse %unique;
11265:     }
11266: 
11267:     sub get_servers {
11268: 	&load_hosts_tab() if (!$loaded);
11269: 
11270: 	my ($domain,$type) = @_;
11271: 	my %possible_hosts = ($type eq 'library') ? %libserv
11272: 	                                          : %hostname;
11273: 	my %result;
11274: 	if (ref($domain) eq 'ARRAY') {
11275: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
11276: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
11277: 		    $result{$host} = $hostname;
11278: 		}
11279: 	    }
11280: 	} else {
11281: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
11282: 		if ($hostdom{$host} eq $domain) {
11283: 		    $result{$host} = $hostname;
11284: 		}
11285: 	    }
11286: 	}
11287: 	return %result;
11288:     }
11289: 
11290:     sub get_unique_servers {
11291:         my %unique = reverse &get_servers(@_);
11292: 	return reverse %unique;
11293:     }
11294: 
11295:     sub host_domain {
11296: 	&load_hosts_tab() if (!$loaded);
11297: 
11298: 	my ($lonid) = @_;
11299: 	return $hostdom{$lonid};
11300:     }
11301: 
11302:     sub all_domains {
11303: 	&load_hosts_tab() if (!$loaded);
11304: 
11305: 	my %seen;
11306: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
11307: 	return @uniq;
11308:     }
11309: 
11310:     sub internet_dom {
11311:         &load_hosts_tab() if (!$loaded);
11312: 
11313:         my ($lonid) = @_;
11314:         return $internetdom{$lonid};
11315:     }
11316: 
11317:     sub is_LC_dns {
11318:         &load_hosts_tab() if (!$loaded);
11319: 
11320:         my ($hostname) = @_;
11321:         return exists($LC_dns_serv{$hostname});
11322:     }
11323: 
11324: }
11325: 
11326: { 
11327:     my %iphost;
11328:     my %name_to_ip;
11329:     my %lonid_to_ip;
11330: 
11331:     sub get_hosts_from_ip {
11332: 	my ($ip) = @_;
11333: 	my %iphosts = &get_iphost();
11334: 	if (ref($iphosts{$ip})) {
11335: 	    return @{$iphosts{$ip}};
11336: 	}
11337: 	return;
11338:     }
11339:     
11340:     sub reset_hosts_ip_info {
11341: 	undef(%iphost);
11342: 	undef(%name_to_ip);
11343: 	undef(%lonid_to_ip);
11344:     }
11345: 
11346:     sub get_host_ip {
11347: 	my ($lonid) = @_;
11348: 	if (exists($lonid_to_ip{$lonid})) {
11349: 	    return $lonid_to_ip{$lonid};
11350: 	}
11351: 	my $name=&hostname($lonid);
11352:    	my $ip = gethostbyname($name);
11353: 	return if (!$ip || length($ip) ne 4);
11354: 	$ip=inet_ntoa($ip);
11355: 	$name_to_ip{$name}   = $ip;
11356: 	$lonid_to_ip{$lonid} = $ip;
11357: 	return $ip;
11358:     }
11359:     
11360:     sub get_iphost {
11361: 	my ($ignore_cache) = @_;
11362: 
11363: 	if (!$ignore_cache) {
11364: 	    if (%iphost) {
11365: 		return %iphost;
11366: 	    }
11367: 	    my ($ip_info,$cached)=
11368: 		&Apache::lonnet::is_cached_new('iphost','iphost');
11369: 	    if ($cached) {
11370: 		%iphost      = %{$ip_info->[0]};
11371: 		%name_to_ip  = %{$ip_info->[1]};
11372: 		%lonid_to_ip = %{$ip_info->[2]};
11373: 		return %iphost;
11374: 	    }
11375: 	}
11376: 
11377: 	# get yesterday's info for fallback
11378: 	my %old_name_to_ip;
11379: 	my ($ip_info,$cached)=
11380: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
11381: 	if ($cached) {
11382: 	    %old_name_to_ip = %{$ip_info->[1]};
11383: 	}
11384: 
11385: 	my %name_to_host = &all_names();
11386: 	foreach my $name (keys(%name_to_host)) {
11387: 	    my $ip;
11388: 	    if (!exists($name_to_ip{$name})) {
11389: 		$ip = gethostbyname($name);
11390: 		if (!$ip || length($ip) ne 4) {
11391: 		    if (defined($old_name_to_ip{$name})) {
11392: 			$ip = $old_name_to_ip{$name};
11393: 			&logthis("Can't find $name defaulting to old $ip");
11394: 		    } else {
11395: 			&logthis("Name $name no IP found");
11396: 			next;
11397: 		    }
11398: 		} else {
11399: 		    $ip=inet_ntoa($ip);
11400: 		}
11401: 		$name_to_ip{$name} = $ip;
11402: 	    } else {
11403: 		$ip = $name_to_ip{$name};
11404: 	    }
11405: 	    foreach my $id (@{ $name_to_host{$name} }) {
11406: 		$lonid_to_ip{$id} = $ip;
11407: 	    }
11408: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
11409: 	}
11410: 	&Apache::lonnet::do_cache_new('iphost','iphost',
11411: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
11412: 				      48*60*60);
11413: 
11414: 	return %iphost;
11415:     }
11416: 
11417:     #
11418:     #  Given a DNS returns the loncapa host name for that DNS 
11419:     # 
11420:     sub host_from_dns {
11421:         my ($dns) = @_;
11422:         my @hosts;
11423:         my $ip;
11424: 
11425:         if (exists($name_to_ip{$dns})) {
11426:             $ip = $name_to_ip{$dns};
11427:         }
11428:         if (!$ip) {
11429:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
11430:             if (length($ip) == 4) { 
11431: 	        $ip   = &IO::Socket::inet_ntoa($ip);
11432:             }
11433:         }
11434:         if ($ip) {
11435: 	    @hosts = get_hosts_from_ip($ip);
11436: 	    return $hosts[0];
11437:         }
11438:         return undef;
11439:     }
11440: 
11441:     sub get_internet_names {
11442:         my ($lonid) = @_;
11443:         return if ($lonid eq '');
11444:         my ($idnref,$cached)=
11445:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
11446:         if ($cached) {
11447:             return $idnref;
11448:         }
11449:         my $ip = &get_host_ip($lonid);
11450:         my @hosts = &get_hosts_from_ip($ip);
11451:         my %iphost = &get_iphost();
11452:         my (@idns,%seen);
11453:         foreach my $id (@hosts) {
11454:             my $dom = &host_domain($id);
11455:             my $prim_id = &domain($dom,'primary');
11456:             my $prim_ip = &get_host_ip($prim_id);
11457:             next if ($seen{$prim_ip});
11458:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
11459:                 foreach my $id (@{$iphost{$prim_ip}}) {
11460:                     my $intdom = &internet_dom($id);
11461:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
11462:                         push(@idns,$intdom);
11463:                     }
11464:                 }
11465:             }
11466:             $seen{$prim_ip} = 1;
11467:         }
11468:         return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
11469:     }
11470: 
11471: }
11472: 
11473: sub all_loncaparevs {
11474:     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);
11475: }
11476: 
11477: BEGIN {
11478: 
11479: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
11480:     unless ($readit) {
11481: {
11482:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
11483:     %perlvar = (%perlvar,%{$configvars});
11484: }
11485: 
11486: 
11487: # ------------------------------------------------------ Read spare server file
11488: {
11489:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
11490: 
11491:     while (my $configline=<$config>) {
11492:        chomp($configline);
11493:        if ($configline) {
11494: 	   my ($host,$type) = split(':',$configline,2);
11495: 	   if (!defined($type) || $type eq '') { $type = 'default' };
11496: 	   push(@{ $spareid{$type} }, $host);
11497:        }
11498:     }
11499:     close($config);
11500: }
11501: # ------------------------------------------------------------ Read permissions
11502: {
11503:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
11504: 
11505:     while (my $configline=<$config>) {
11506: 	chomp($configline);
11507: 	if ($configline) {
11508: 	    my ($role,$perm)=split(/ /,$configline);
11509: 	    if ($perm ne '') { $pr{$role}=$perm; }
11510: 	}
11511:     }
11512:     close($config);
11513: }
11514: 
11515: # -------------------------------------------- Read plain texts for permissions
11516: {
11517:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
11518: 
11519:     while (my $configline=<$config>) {
11520: 	chomp($configline);
11521: 	if ($configline) {
11522: 	    my ($short,@plain)=split(/:/,$configline);
11523:             %{$prp{$short}} = ();
11524: 	    if (@plain > 0) {
11525:                 $prp{$short}{'std'} = $plain[0];
11526:                 for (my $i=1; $i<@plain; $i++) {
11527:                     $prp{$short}{'alt'.$i} = $plain[$i];  
11528:                 }
11529:             }
11530: 	}
11531:     }
11532:     close($config);
11533: }
11534: 
11535: # ---------------------------------------------------------- Read package table
11536: {
11537:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
11538: 
11539:     while (my $configline=<$config>) {
11540: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
11541: 	chomp($configline);
11542: 	my ($short,$plain)=split(/:/,$configline);
11543: 	my ($pack,$name)=split(/\&/,$short);
11544: 	if ($plain ne '') {
11545: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
11546: 	    $packagetab{$short}=$plain; 
11547: 	}
11548:     }
11549:     close($config);
11550: }
11551: 
11552: # ---------------------------------------------------------- Read loncaparev table
11553: {
11554:     if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
11555:         if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
11556:             while (my $configline=<$config>) {
11557:                 chomp($configline);
11558:                 my ($hostid,$loncaparev)=split(/:/,$configline);
11559:                 $loncaparevs{$hostid}=$loncaparev;
11560:             }
11561:             close($config);
11562:         }
11563:     }
11564: }
11565: 
11566: # ---------------------------------------------------------- Read serverhostID table
11567: {
11568:     if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
11569:         if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
11570:             while (my $configline=<$config>) {
11571:                 chomp($configline);
11572:                 my ($name,$id)=split(/:/,$configline);
11573:                 $serverhomeIDs{$name}=$id;
11574:             }
11575:             close($config);
11576:         }
11577:     }
11578: }
11579: 
11580: {
11581:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
11582:     if (-e $file) {
11583:         my $parser = HTML::LCParser->new($file);
11584:         while (my $token = $parser->get_token()) {
11585:             if ($token->[0] eq 'S') {
11586:                 my $item = $token->[1];
11587:                 my $name = $token->[2]{'name'};
11588:                 my $value = $token->[2]{'value'};
11589:                 if ($item ne '' && $name ne '' && $value ne '') {
11590:                     my $release = $parser->get_text();
11591:                     $release =~ s/(^\s*|\s*$ )//gx;
11592:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
11593:                 }
11594:             }
11595:         }
11596:     }
11597: }
11598: 
11599: # ---------------------------------------------------------- Read managers table
11600: {
11601:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
11602:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
11603:             while (my $configline=<$config>) {
11604:                 chomp($configline);
11605:                 next if ($configline =~ /^\#/);
11606:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
11607:                     $managerstab{$configline} = 1;
11608:                 }
11609:             }
11610:             close($config);
11611:         }
11612:     }
11613: }
11614: 
11615: # ------------- set up temporary directory
11616: {
11617:     $tmpdir = LONCAPA::tempdir();
11618: 
11619: }
11620: 
11621: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
11622: 				'compress_threshold'=> 20_000,
11623:  			        });
11624: 
11625: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
11626: $dumpcount=0;
11627: $locknum=0;
11628: 
11629: &logtouch();
11630: &logthis('<font color="yellow">INFO: Read configuration</font>');
11631: $readit=1;
11632:     {
11633: 	use integer;
11634: 	my $test=(2**32)+1;
11635: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
11636: 	&logthis(" Detected 64bit platform ($_64bit)");
11637:     }
11638: }
11639: }
11640: 
11641: 1;
11642: __END__
11643: 
11644: =pod
11645: 
11646: =head1 NAME
11647: 
11648: Apache::lonnet - Subroutines to ask questions about things in the network.
11649: 
11650: =head1 SYNOPSIS
11651: 
11652: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
11653: 
11654:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
11655: 
11656: Common parameters:
11657: 
11658: =over 4
11659: 
11660: =item *
11661: 
11662: $uname : an internal username (if $cname expecting a course Id specifically)
11663: 
11664: =item *
11665: 
11666: $udom : a domain (if $cdom expecting a course's domain specifically)
11667: 
11668: =item *
11669: 
11670: $symb : a resource instance identifier
11671: 
11672: =item *
11673: 
11674: $namespace : the name of a .db file that contains the data needed or
11675: being set.
11676: 
11677: =back
11678: 
11679: =head1 OVERVIEW
11680: 
11681: lonnet provides subroutines which interact with the
11682: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
11683: about classes, users, and resources.
11684: 
11685: For many of these objects you can also use this to store data about
11686: them or modify them in various ways.
11687: 
11688: =head2 Symbs
11689: 
11690: To identify a specific instance of a resource, LON-CAPA uses symbols
11691: or "symbs"X<symb>. These identifiers are built from the URL of the
11692: map, the resource number of the resource in the map, and the URL of
11693: the resource itself. The latter is somewhat redundant, but might help
11694: if maps change.
11695: 
11696: An example is
11697: 
11698:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
11699: 
11700: The respective map entry is
11701: 
11702:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
11703:   title="Problem 2">
11704:  </resource>
11705: 
11706: Symbs are used by the random number generator, as well as to store and
11707: restore data specific to a certain instance of for example a problem.
11708: 
11709: =head2 Storing And Retrieving Data
11710: 
11711: X<store()>X<cstore()>X<restore()>Three of the most important functions
11712: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
11713: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
11714: is is the non-critical message twin of cstore. These functions are for
11715: handlers to store a perl hash to a user's permanent data space in an
11716: easy manner, and to retrieve it again on another call. It is expected
11717: that a handler would use this once at the beginning to retrieve data,
11718: and then again once at the end to send only the new data back.
11719: 
11720: The data is stored in the user's data directory on the user's
11721: homeserver under the ID of the course.
11722: 
11723: The hash that is returned by restore will have all of the previous
11724: value for all of the elements of the hash.
11725: 
11726: Example:
11727: 
11728:  #creating a hash
11729:  my %hash;
11730:  $hash{'foo'}='bar';
11731: 
11732:  #storing it
11733:  &Apache::lonnet::cstore(\%hash);
11734: 
11735:  #changing a value
11736:  $hash{'foo'}='notbar';
11737: 
11738:  #adding a new value
11739:  $hash{'bar'}='foo';
11740:  &Apache::lonnet::cstore(\%hash);
11741: 
11742:  #retrieving the hash
11743:  my %history=&Apache::lonnet::restore();
11744: 
11745:  #print the hash
11746:  foreach my $key (sort(keys(%history))) {
11747:    print("\%history{$key} = $history{$key}");
11748:  }
11749: 
11750: Will print out:
11751: 
11752:  %history{1:foo} = bar
11753:  %history{1:keys} = foo:timestamp
11754:  %history{1:timestamp} = 990455579
11755:  %history{2:bar} = foo
11756:  %history{2:foo} = notbar
11757:  %history{2:keys} = foo:bar:timestamp
11758:  %history{2:timestamp} = 990455580
11759:  %history{bar} = foo
11760:  %history{foo} = notbar
11761:  %history{timestamp} = 990455580
11762:  %history{version} = 2
11763: 
11764: Note that the special hash entries C<keys>, C<version> and
11765: C<timestamp> were added to the hash. C<version> will be equal to the
11766: total number of versions of the data that have been stored. The
11767: C<timestamp> attribute will be the UNIX time the hash was
11768: stored. C<keys> is available in every historical section to list which
11769: keys were added or changed at a specific historical revision of a
11770: hash.
11771: 
11772: B<Warning>: do not store the hash that restore returns directly. This
11773: will cause a mess since it will restore the historical keys as if the
11774: were new keys. I.E. 1:foo will become 1:1:foo etc.
11775: 
11776: Calling convention:
11777: 
11778:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
11779:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
11780: 
11781: For more detailed information, see lonnet specific documentation.
11782: 
11783: =head1 RETURN MESSAGES
11784: 
11785: =over 4
11786: 
11787: =item * B<con_lost>: unable to contact remote host
11788: 
11789: =item * B<con_delayed>: unable to contact remote host, message will be delivered
11790: when the connection is brought back up
11791: 
11792: =item * B<con_failed>: unable to contact remote host and unable to save message
11793: for later delivery
11794: 
11795: =item * B<error:>: an error a occurred, a description of the error follows the :
11796: 
11797: =item * B<no_such_host>: unable to fund a host associated with the user/domain
11798: that was requested
11799: 
11800: =back
11801: 
11802: =head1 PUBLIC SUBROUTINES
11803: 
11804: =head2 Session Environment Functions
11805: 
11806: =over 4
11807: 
11808: =item * 
11809: X<appenv()>
11810: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
11811: the user envirnoment file, and will be restored for each access this
11812: user makes during this session, also modifies the %env for the current
11813: process. Optional rolesarrayref - if defined contains a reference to an array
11814: of roles which are exempt from the restriction on modifying user.role entries 
11815: in the user's environment.db and in %env.    
11816: 
11817: =item *
11818: X<delenv()>
11819: B<delenv($delthis,$regexp)>: removes all items from the session
11820: environment file that begin with $delthis. If the 
11821: optional second arg - $regexp - is true, $delthis is treated as a 
11822: regular expression, otherwise \Q$delthis\E is used. 
11823: The values are also deleted from the current processes %env.
11824: 
11825: =item * get_env_multiple($name) 
11826: 
11827: gets $name from the %env hash, it seemlessly handles the cases where multiple
11828: values may be defined and end up as an array ref.
11829: 
11830: returns an array of values
11831: 
11832: =back
11833: 
11834: =head2 User Information
11835: 
11836: =over 4
11837: 
11838: =item *
11839: X<queryauthenticate()>
11840: B<queryauthenticate($uname,$udom)>: try to determine user's current 
11841: authentication scheme
11842: 
11843: =item *
11844: X<authenticate()>
11845: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
11846: authenticate user from domain's lib servers (first use the current
11847: one). C<$upass> should be the users password.
11848: $checkdefauth is optional (value is 1 if a check should be made to
11849:    authenticate user using default authentication method, and allow
11850:    account creation if username does not have account in the domain).
11851: $clientcancheckhost is optional (value is 1 if checking whether the
11852:    server can host will occur on the client side in lonauth.pm).   
11853: 
11854: =item *
11855: X<homeserver()>
11856: B<homeserver($uname,$udom)>: find the server which has
11857: the user's directory and files (there must be only one), this caches
11858: the answer, and also caches if there is a borken connection.
11859: 
11860: =item *
11861: X<idget()>
11862: B<idget($udom,@ids)>: find the usernames behind a list of IDs
11863: (IDs are a unique resource in a domain, there must be only 1 ID per
11864: username, and only 1 username per ID in a specific domain) (returns
11865: hash: id=>name,id=>name)
11866: 
11867: =item *
11868: X<idrget()>
11869: B<idrget($udom,@unames)>: find the IDs behind a list of
11870: usernames (returns hash: name=>id,name=>id)
11871: 
11872: =item *
11873: X<idput()>
11874: B<idput($udom,%ids)>: store away a list of names and associated IDs
11875: 
11876: =item *
11877: X<rolesinit()>
11878: B<rolesinit($udom,$username)>: get user privileges.
11879: returns user role, first access and timer interval hashes
11880: 
11881: =item *
11882: X<privileged()>
11883: B<privileged($username,$domain)>: returns a true if user has a
11884: privileged and active role (i.e. su or dc), false otherwise.
11885: 
11886: =item *
11887: X<getsection()>
11888: B<getsection($udom,$uname,$cname)>: finds the section of student in the
11889: course $cname, return section name/number or '' for "not in course"
11890: and '-1' for "no section"
11891: 
11892: =item *
11893: X<userenvironment()>
11894: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
11895: passed in @what from the requested user's environment, returns a hash
11896: 
11897: =item * 
11898: X<userlog_query()>
11899: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
11900: activity.log file. %filters defines filters applied when parsing the
11901: log file. These can be start or end timestamps, or the type of action
11902: - log to look for Login or Logout events, check for Checkin or
11903: Checkout, role for role selection. The response is in the form
11904: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
11905: escaped strings of the action recorded in the activity.log file.
11906: 
11907: =back
11908: 
11909: =head2 User Roles
11910: 
11911: =over 4
11912: 
11913: =item *
11914: 
11915: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
11916:  F: full access
11917:  U,I,K: authentication modes (cxx only)
11918:  '': forbidden
11919:  1: user needs to choose course
11920:  2: browse allowed
11921:  A: passphrase authentication needed
11922: 
11923: =item *
11924: 
11925: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
11926: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
11927: and course level
11928: 
11929: =item *
11930: 
11931: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
11932: (rolesplain.tab); plain text explanation of a user role term.
11933: $type is Course (default) or Community.
11934: If $forcedefault evaluates to true, text returned will be default 
11935: text for $type. Otherwise, if this is a course, the text returned 
11936: will be a custom name for the role (if defined in the course's 
11937: environment).  If no custom name is defined the default is returned.
11938:    
11939: =item *
11940: 
11941: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
11942: All arguments are optional. Returns a hash of a roles, either for
11943: co-author/assistant author roles for a user's Construction Space
11944: (default), or if $context is 'userroles', roles for the user himself,
11945: In the hash, keys are set to colon-separated $uname,$udom,$role, and
11946: (optionally) if $withsec is true, a fourth colon-separated item - $section.
11947: For each key, value is set to colon-separated start and end times for
11948: the role.  If no username and domain are specified, will default to
11949: current user/domain. Types, roles, and roledoms are references to arrays
11950: of role statuses (active, future or previous), roles 
11951: (e.g., cc,in, st etc.) and domains of the roles which can be used
11952: to restrict the list of roles reported. If no array ref is 
11953: provided for types, will default to return only active roles.
11954: 
11955: =back
11956: 
11957: =head2 User Modification
11958: 
11959: =over 4
11960: 
11961: =item *
11962: 
11963: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
11964: user for the level given by URL.  Optional start and end dates (leave empty
11965: string or zero for "no date")
11966: 
11967: =item *
11968: 
11969: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
11970: change a users, password, possible return values are: ok,
11971: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
11972: refused
11973: 
11974: =item *
11975: 
11976: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
11977: 
11978: =item *
11979: 
11980: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
11981:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
11982: 
11983: will update user information (firstname,middlename,lastname,generation,
11984: permanentemail), and if forceid is true, student/employee ID also.
11985: A user's institutional affiliation(s) can also be updated.
11986: User information fields will not be overwritten with empty entries 
11987: unless the field is included in the $candelete array reference.
11988: This array is included when a single user is modified via "Manage Users",
11989: or when Autoupdate.pl is run by cron in a domain.
11990: 
11991: =item *
11992: 
11993: modifystudent
11994: 
11995: modify a student's enrollment and identification information.
11996: The course id is resolved based on the current users environment.  
11997: This means the envoking user must be a course coordinator or otherwise
11998: associated with a course.
11999: 
12000: This call is essentially a wrapper for lonnet::modifyuser and
12001: lonnet::modify_student_enrollment
12002: 
12003: Inputs: 
12004: 
12005: =over 4
12006: 
12007: =item B<$udom> Student's loncapa domain
12008: 
12009: =item B<$uname> Student's loncapa login name
12010: 
12011: =item B<$uid> Student/Employee ID
12012: 
12013: =item B<$umode> Student's authentication mode
12014: 
12015: =item B<$upass> Student's password
12016: 
12017: =item B<$first> Student's first name
12018: 
12019: =item B<$middle> Student's middle name
12020: 
12021: =item B<$last> Student's last name
12022: 
12023: =item B<$gene> Student's generation
12024: 
12025: =item B<$usec> Student's section in course
12026: 
12027: =item B<$end> Unix time of the roles expiration
12028: 
12029: =item B<$start> Unix time of the roles start date
12030: 
12031: =item B<$forceid> If defined, allow $uid to be changed
12032: 
12033: =item B<$desiredhome> server to use as home server for student
12034: 
12035: =item B<$email> Student's permanent e-mail address
12036: 
12037: =item B<$type> Type of enrollment (auto or manual)
12038: 
12039: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
12040: 
12041: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
12042: 
12043: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
12044: 
12045: =item B<$context> role change context (shown in User Management Logs display in a course)
12046: 
12047: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
12048: 
12049: =back
12050: 
12051: =item *
12052: 
12053: modify_student_enrollment
12054: 
12055: Change a students enrollment status in a class.  The environment variable
12056: 'role.request.course' must be defined for this function to proceed.
12057: 
12058: Inputs:
12059: 
12060: =over 4
12061: 
12062: =item $udom, students domain
12063: 
12064: =item $uname, students name
12065: 
12066: =item $uid, students user id
12067: 
12068: =item $first, students first name
12069: 
12070: =item $middle
12071: 
12072: =item $last
12073: 
12074: =item $gene
12075: 
12076: =item $usec
12077: 
12078: =item $end
12079: 
12080: =item $start
12081: 
12082: =item $type
12083: 
12084: =item $locktype
12085: 
12086: =item $cid
12087: 
12088: =item $selfenroll
12089: 
12090: =item $context
12091: 
12092: =back
12093: 
12094: 
12095: =item *
12096: 
12097: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
12098: custom role; give a custom role to a user for the level given by URL.  Specify
12099: name and domain of role author, and role name
12100: 
12101: =item *
12102: 
12103: revokerole($udom,$uname,$url,$role) : revoke a role for url
12104: 
12105: =item *
12106: 
12107: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
12108: 
12109: =back
12110: 
12111: =head2 Course Infomation
12112: 
12113: =over 4
12114: 
12115: =item *
12116: 
12117: coursedescription($courseid,$options) : returns a hash of information about the
12118: specified course id, including all environment settings for the
12119: course, the description of the course will be in the hash under the
12120: key 'description'
12121: 
12122: $options is an optional parameter that if supplied is a hash reference that controls
12123: what how this function works.  It has the following key/values:
12124: 
12125: =over 4
12126: 
12127: =item freshen_cache
12128: 
12129: If defined, and the environment cache for the course is valid, it is 
12130: returned in the returned hash.
12131: 
12132: =item one_time
12133: 
12134: If defined, the last cache time is set to _now_
12135: 
12136: =item user
12137: 
12138: If defined, the supplied username is used instead of the current user.
12139: 
12140: 
12141: =back
12142: 
12143: =item *
12144: 
12145: resdata($name,$domain,$type,@which) : request for current parameter
12146: setting for a specific $type, where $type is either 'course' or 'user',
12147: @what should be a list of parameters to ask about. This routine caches
12148: answers for 5 minutes.
12149: 
12150: =item *
12151: 
12152: get_courseresdata($courseid, $domain) : dump the entire course resource
12153: data base, returning a hash that is keyed by the resource name and has
12154: values that are the resource value.  I believe that the timestamps and
12155: versions are also returned.
12156: 
12157: 
12158: =back
12159: 
12160: =head2 Course Modification
12161: 
12162: =over 4
12163: 
12164: =item *
12165: 
12166: writecoursepref($courseid,%prefs) : write preferences (environment
12167: database) for a course
12168: 
12169: =item *
12170: 
12171: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
12172: 
12173: =item *
12174: 
12175: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
12176: 
12177: =item *
12178: 
12179: is_course($courseid), is_course($cdom, $cnum)
12180: 
12181: Accepts either a combined $courseid (in the form of domain_courseid) or the
12182: two component version $cdom, $cnum. It checks if the specified course exists.
12183: 
12184: Returns:
12185:     undef if the course doesn't exist, otherwise
12186:     in scalar context the combined courseid.
12187:     in list context the two components of the course identifier, domain and 
12188:     courseid.    
12189: 
12190: =back
12191: 
12192: =head2 Resource Subroutines
12193: 
12194: =over 4
12195: 
12196: =item *
12197: 
12198: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
12199: 
12200: =item *
12201: 
12202: repcopy($filename) : subscribes to the requested file, and attempts to
12203: replicate from the owning library server, Might return
12204: 'unavailable', 'not_found', 'forbidden', 'ok', or
12205: 'bad_request', also attempts to grab the metadata for the
12206: resource. Expects the local filesystem pathname
12207: (/home/httpd/html/res/....)
12208: 
12209: =back
12210: 
12211: =head2 Resource Information
12212: 
12213: =over 4
12214: 
12215: =item *
12216: 
12217: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
12218: a vairety of different possible values, $varname should be a request
12219: string, and the other parameters can be used to specify who and what
12220: one is asking about.
12221: 
12222: Possible values for $varname are environment.lastname (or other item
12223: from the envirnment hash), user.name (or someother aspect about the
12224: user), resource.0.maxtries (or some other part and parameter of a
12225: resource)
12226: 
12227: =item *
12228: 
12229: directcondval($number) : get current value of a condition; reads from a state
12230: string
12231: 
12232: =item *
12233: 
12234: condval($condidx) : value of condition index based on state
12235: 
12236: =item *
12237: 
12238: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
12239: resource's metadata, $what should be either a specific key, or either
12240: 'keys' (to get a list of possible keys) or 'packages' to get a list of
12241: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
12242: 
12243: this function automatically caches all requests
12244: 
12245: =item *
12246: 
12247: metadata_query($query,$custom,$customshow) : make a metadata query against the
12248: network of library servers; returns file handle of where SQL and regex results
12249: will be stored for query
12250: 
12251: =item *
12252: 
12253: symbread($filename) : return symbolic list entry (filename argument optional);
12254: returns the data handle
12255: 
12256: =item *
12257: 
12258: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
12259: a possible symb for the URL in $thisfn, and if is an encryypted
12260: resource that the user accessed using /enc/ returns a 1 on success, 0
12261: on failure, user must be in a course, as it assumes the existance of
12262: the course initial hash, and uses $env('request.course.id'}
12263: 
12264: 
12265: =item *
12266: 
12267: symbclean($symb) : removes versions numbers from a symb, returns the
12268: cleaned symb
12269: 
12270: =item *
12271: 
12272: is_on_map($uri) : checks if the $uri is somewhere on the current
12273: course map, user must be in a course for it to work.
12274: 
12275: =item *
12276: 
12277: numval($salt) : return random seed value (addend for rndseed)
12278: 
12279: =item *
12280: 
12281: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
12282: a random seed, all arguments are optional, if they aren't sent it uses the
12283: environment to derive them. Note: if symb isn't sent and it can't get one
12284: from &symbread it will use the current time as its return value
12285: 
12286: =item *
12287: 
12288: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
12289: unfakeable, receipt
12290: 
12291: =item *
12292: 
12293: receipt() : API to ireceipt working off of env values; given out to users
12294: 
12295: =item *
12296: 
12297: countacc($url) : count the number of accesses to a given URL
12298: 
12299: =item *
12300: 
12301: 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
12302: 
12303: =item *
12304: 
12305: 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)
12306: 
12307: =item *
12308: 
12309: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
12310: 
12311: =item *
12312: 
12313: devalidate($symb) : devalidate temporary spreadsheet calculations,
12314: forcing spreadsheet to reevaluate the resource scores next time.
12315: 
12316: =back
12317: 
12318: =head2 Storing/Retreiving Data
12319: 
12320: =over 4
12321: 
12322: =item *
12323: 
12324: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
12325: for this url; hashref needs to be given and should be a \%hashname; the
12326: remaining args aren't required and if they aren't passed or are '' they will
12327: be derived from the env
12328: 
12329: =item *
12330: 
12331: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
12332: uses critical subroutine
12333: 
12334: =item *
12335: 
12336: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
12337: all args are optional
12338: 
12339: =item *
12340: 
12341: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
12342: dumps the complete (or key matching regexp) namespace into a hash
12343: ($udom, $uname, $regexp, $range are optional) for a namespace that is
12344: normally &store()ed into
12345: 
12346: $range should be either an integer '100' (give me the first 100
12347:                                            matching records)
12348:               or be  two integers sperated by a - with no spaces
12349:                  '30-50' (give me the 30th through the 50th matching
12350:                           records)
12351: 
12352: 
12353: =item *
12354: 
12355: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
12356: replaces a &store() version of data with a replacement set of data
12357: for a particular resource in a namespace passed in the $storehash hash 
12358: reference
12359: 
12360: =item *
12361: 
12362: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
12363: works very similar to store/cstore, but all data is stored in a
12364: temporary location and can be reset using tmpreset, $storehash should
12365: be a hash reference, returns nothing on success
12366: 
12367: =item *
12368: 
12369: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
12370: similar to restore, but all data is stored in a temporary location and
12371: can be reset using tmpreset. Returns a hash of values on success,
12372: error string otherwise.
12373: 
12374: =item *
12375: 
12376: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
12377: deltes all keys for $symb form the temporary storage hash.
12378: 
12379: =item *
12380: 
12381: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
12382: reference filled in from namesp ($udom and $uname are optional)
12383: 
12384: =item *
12385: 
12386: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
12387: namesp ($udom and $uname are optional)
12388: 
12389: =item *
12390: 
12391: dump($namespace,$udom,$uname,$regexp,$range) : 
12392: dumps the complete (or key matching regexp) namespace into a hash
12393: ($udom, $uname, $regexp, $range are optional)
12394: 
12395: $range should be either an integer '100' (give me the first 100
12396:                                            matching records)
12397:               or be  two integers sperated by a - with no spaces
12398:                  '30-50' (give me the 30th through the 50th matching
12399:                           records)
12400: =item *
12401: 
12402: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
12403: $store can be a scalar, an array reference, or if the amount to be 
12404: incremented is > 1, a hash reference.
12405: 
12406: ($udom and $uname are optional)
12407: 
12408: =item *
12409: 
12410: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
12411: ($udom and $uname are optional)
12412: 
12413: =item *
12414: 
12415: cput($namespace,$storehash,$udom,$uname) : critical put
12416: ($udom and $uname are optional)
12417: 
12418: =item *
12419: 
12420: newput($namespace,$storehash,$udom,$uname) :
12421: 
12422: Attempts to store the items in the $storehash, but only if they don't
12423: currently exist, if this succeeds you can be certain that you have 
12424: successfully created a new key value pair in the $namespace db.
12425: 
12426: 
12427: Args:
12428:  $namespace: name of database to store values to
12429:  $storehash: hashref to store to the db
12430:  $udom: (optional) domain of user containing the db
12431:  $uname: (optional) name of user caontaining the db
12432: 
12433: Returns:
12434:  'ok' -> succeeded in storing all keys of $storehash
12435:  'key_exists: <key>' -> failed to anything out of $storehash, as at
12436:                         least <key> already existed in the db (other
12437:                         requested keys may also already exist)
12438:  'error: <msg>' -> unable to tie the DB or other error occurred
12439:  'con_lost' -> unable to contact request server
12440:  'refused' -> action was not allowed by remote machine
12441: 
12442: 
12443: =item *
12444: 
12445: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
12446: reference filled in from namesp (encrypts the return communication)
12447: ($udom and $uname are optional)
12448: 
12449: =item *
12450: 
12451: log($udom,$name,$home,$message) : write to permanent log for user; use
12452: critical subroutine
12453: 
12454: =item *
12455: 
12456: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
12457: array reference filled in from namespace found in domain level on either
12458: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
12459: 
12460: =item *
12461: 
12462: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
12463: domain level either on specified domain server ($uhome) or primary domain 
12464: server ($udom and $uhome are optional)
12465: 
12466: =item * 
12467: 
12468: get_domain_defaults($target_domain) : returns hash with defaults for
12469: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
12470: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
12471: or localauth), initial password or a kerberos realm, language (e.g., en-us).
12472: Values are retrieved from cache (if current), or from domain's configuration.db
12473: (if available), or lastly from values in lonTabs/dns_domain,tab, 
12474: or lonTabs/domain.tab. 
12475: 
12476: %domdefaults = &get_auth_defaults($target_domain);
12477: 
12478: =back
12479: 
12480: =head2 Network Status Functions
12481: 
12482: =over 4
12483: 
12484: =item *
12485: 
12486: dirlist() : return directory list based on URI (first arg).
12487: 
12488: Inputs: 1 required, 5 optional.
12489: 
12490: =over
12491: 
12492: =item 
12493: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
12494: 
12495: =item
12496: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
12497: 
12498: =item
12499: $username -  username of user/course to be listed. Extracted from $uri if absent. 
12500: 
12501: =item
12502: $getpropath - boolean: 1 if prepend path using &propath(). 
12503: 
12504: =item
12505: $getuserdir - boolean: 1 if prepend path for "userfiles".
12506: 
12507: =item 
12508: $alternateRoot - path to prepend in place of path from $uri.
12509: 
12510: =back
12511: 
12512: Returns: Array of up to two items.
12513: 
12514: =over
12515: 
12516: a reference to an array of files/subdirectories
12517: 
12518: =over
12519: 
12520: Each element in the array of files/subdirectories is a & separated list of
12521: item name and the result of running stat on the item.  If dirlist was requested
12522: for a file instead of a directory, the item name will be ''. For a directory 
12523: listing, if the item is a metadata file, the element will end &N&M 
12524: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
12525: default copyright set (1).  
12526: 
12527: =back
12528: 
12529: a scalar containing error condition (if encountered).
12530: 
12531: =over
12532: 
12533: =item 
12534: no_host (no homeserver identified for $username:$domain).
12535: 
12536: =item 
12537: no_such_host (server contacted for listing not identified as valid host).
12538: 
12539: =item 
12540: con_lost (connection to remote server failed).
12541: 
12542: =item 
12543: refused (invalid $username:$domain received on lond side).
12544: 
12545: =item 
12546: no_such_dir (directory at specified path on lond side does not exist). 
12547: 
12548: =item 
12549: empty (directory at specified path on lond side is empty).
12550: 
12551: =over
12552: 
12553: This is currently not encountered because the &ls3, &ls2, 
12554: &ls (_handler) routines on the lond side do not filter out
12555: . and .. from a directory listing. 
12556: 
12557: =back
12558: 
12559: =back
12560: 
12561: =back
12562: 
12563: =item *
12564: 
12565: spareserver() : find server with least workload from spare.tab
12566: 
12567: 
12568: =item *
12569: 
12570: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
12571: if there is no corresponding loncapa host.
12572: 
12573: =back
12574: 
12575: 
12576: =head2 Apache Request
12577: 
12578: =over 4
12579: 
12580: =item *
12581: 
12582: ssi($url,%hash) : server side include, does a complete request cycle on url to
12583: localhost, posts hash
12584: 
12585: =back
12586: 
12587: =head2 Data to String to Data
12588: 
12589: =over 4
12590: 
12591: =item *
12592: 
12593: hash2str(%hash) : convert a hash into a string complete with escaping and '='
12594: and '&' separators, supports elements that are arrayrefs and hashrefs
12595: 
12596: =item *
12597: 
12598: hashref2str($hashref) : convert a hashref into a string complete with
12599: escaping and '=' and '&' separators, supports elements that are
12600: arrayrefs and hashrefs
12601: 
12602: =item *
12603: 
12604: arrayref2str($arrayref) : convert an arrayref into a string complete
12605: with escaping and '&' separators, supports elements that are arrayrefs
12606: and hashrefs
12607: 
12608: =item *
12609: 
12610: str2hash($string) : convert string to hash using unescaping and
12611: splitting on '=' and '&', supports elements that are arrayrefs and
12612: hashrefs
12613: 
12614: =item *
12615: 
12616: str2array($string) : convert string to hash using unescaping and
12617: splitting on '&', supports elements that are arrayrefs and hashrefs
12618: 
12619: =back
12620: 
12621: =head2 Logging Routines
12622: 
12623: 
12624: These routines allow one to make log messages in the lonnet.log and
12625: lonnet.perm logfiles.
12626: 
12627: =over 4
12628: 
12629: =item *
12630: 
12631: logtouch() : make sure the logfile, lonnet.log, exists
12632: 
12633: =item *
12634: 
12635: logthis() : append message to the normal lonnet.log file, it gets
12636: preiodically rolled over and deleted.
12637: 
12638: =item *
12639: 
12640: logperm() : append a permanent message to lonnet.perm.log, this log
12641: file never gets deleted by any automated portion of the system, only
12642: messages of critical importance should go in here.
12643: 
12644: 
12645: =back
12646: 
12647: =head2 General File Helper Routines
12648: 
12649: =over 4
12650: 
12651: =item *
12652: 
12653: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
12654: (a) files in /uploaded
12655:   (i) If a local copy of the file exists - 
12656:       compares modification date of local copy with last-modified date for 
12657:       definitive version stored on home server for course. If local copy is 
12658:       stale, requests a new version from the home server and stores it. 
12659:       If the original has been removed from the home server, then local copy 
12660:       is unlinked.
12661:   (ii) If local copy does not exist -
12662:       requests the file from the home server and stores it. 
12663:   
12664:   If $caller is 'uploadrep':  
12665:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
12666:     for request for files originally uploaded via DOCS. 
12667:      - returns 'ok' if fresh local copy now available, -1 otherwise.
12668:   
12669:   Otherwise:
12670:      This indicates a call from the content generation phase of the request.
12671:      -  returns the entire contents of the file or -1.
12672:      
12673: (b) files in /res
12674:    - returns the entire contents of a file or -1; 
12675:    it properly subscribes to and replicates the file if neccessary.
12676: 
12677: 
12678: =item *
12679: 
12680: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
12681:                   reference
12682: 
12683: returns either a stat() list of data about the file or an empty list
12684: if the file doesn't exist or couldn't find out about it (connection
12685: problems or user unknown)
12686: 
12687: =item *
12688: 
12689: filelocation($dir,$file) : returns file system location of a file
12690: based on URI; meant to be "fairly clean" absolute reference, $dir is a
12691: directory that relative $file lookups are to looked in ($dir of /a/dir
12692: and a file of ../bob will become /a/bob)
12693: 
12694: =item *
12695: 
12696: hreflocation($dir,$file) : returns file system location or a URL; same as
12697: filelocation except for hrefs
12698: 
12699: =item *
12700: 
12701: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
12702: 
12703: =back
12704: 
12705: =head2 Usererfile file routines (/uploaded*)
12706: 
12707: =over 4
12708: 
12709: =item *
12710: 
12711: userfileupload(): main rotine for putting a file in a user or course's
12712:                   filespace, arguments are,
12713: 
12714:  formname - required - this is the name of the element in $env where the
12715:            filename, and the contents of the file to create/modifed exist
12716:            the filename is in $env{'form.'.$formname.'.filename'} and the
12717:            contents of the file is located in $env{'form.'.$formname}
12718:  context - if coursedoc, store the file in the course of the active role
12719:              of the current user; 
12720:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
12721:            if 'canceloverwrite': delete file in tmp/overwrites directory
12722:  subdir - required - subdirectory to put the file in under ../userfiles/
12723:          if undefined, it will be placed in "unknown"
12724: 
12725:  (This routine calls clean_filename() to remove any dangerous
12726:  characters from the filename, and then calls finuserfileupload() to
12727:  complete the transaction)
12728: 
12729:  returns either the url of the uploaded file (/uploaded/....) if successful
12730:  and /adm/notfound.html if unsuccessful
12731: 
12732: =item *
12733: 
12734: clean_filename(): routine for cleaing a filename up for storage in
12735:                  userfile space, argument is:
12736: 
12737:  filename - proposed filename
12738: 
12739: returns: the new clean filename
12740: 
12741: =item *
12742: 
12743: finishuserfileupload(): routine that creates and sends the file to
12744: userspace, probably shouldn't be called directly
12745: 
12746:   docuname: username or courseid of destination for the file
12747:   docudom: domain of user/course of destination for the file
12748:   formname: same as for userfileupload()
12749:   fname: filename (including subdirectories) for the file
12750:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
12751:   allfiles: reference to hash used to store objects found by parser
12752:   codebase: reference to hash used for codebases of java objects found by parser
12753:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
12754:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
12755:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
12756:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
12757:   context: if 'overwrite', will move the uploaded file from its temporary location to
12758:             userfiles to facilitate overwriting a previously uploaded file with same name.
12759:   mimetype: reference to scalar to accommodate mime type determined
12760:             from File::MMagic if $parser = parse.
12761: 
12762:  returns either the url of the uploaded file (/uploaded/....) if successful
12763:  and /adm/notfound.html if unsuccessful (or an error message if context 
12764:  was 'overwrite').
12765:  
12766: 
12767: =item *
12768: 
12769: renameuserfile(): renames an existing userfile to a new name
12770: 
12771:   Args:
12772:    docuname: username or courseid of destination for the file
12773:    docudom: domain of user/course of destination for the file
12774:    old: current file name (including any subdirs under userfiles)
12775:    new: desired file name (including any subdirs under userfiles)
12776: 
12777: =item *
12778: 
12779: mkdiruserfile(): creates a directory is a userfiles dir
12780: 
12781:   Args:
12782:    docuname: username or courseid of destination for the file
12783:    docudom: domain of user/course of destination for the file
12784:    dir: dir to create (including any subdirs under userfiles)
12785: 
12786: =item *
12787: 
12788: removeuserfile(): removes a file that exists in userfiles
12789: 
12790:   Args:
12791:    docuname: username or courseid of destination for the file
12792:    docudom: domain of user/course of destination for the file
12793:    fname: filname to delete (including any subdirs under userfiles)
12794: 
12795: =item *
12796: 
12797: removeuploadedurl(): convience function for removeuserfile()
12798: 
12799:   Args:
12800:    url:  a full /uploaded/... url to delete
12801: 
12802: =item * 
12803: 
12804: get_portfile_permissions():
12805:   Args:
12806:     domain: domain of user or course contain the portfolio files
12807:     user: name of user or num of course contain the portfolio files
12808:   Returns:
12809:     hashref of a dump of the proper file_permissions.db
12810:    
12811: 
12812: =item * 
12813: 
12814: get_access_controls():
12815: 
12816: Args:
12817:   current_permissions: the hash ref returned from get_portfile_permissions()
12818:   group: (optional) the group you want the files associated with
12819:   file: (optional) the file you want access info on
12820: 
12821: Returns:
12822:     a hash (keys are file names) of hashes containing
12823:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
12824:         values are XML containing access control settings (see below) 
12825: 
12826: Internal notes:
12827: 
12828:  access controls are stored in file_permissions.db as key=value pairs.
12829:     key -> path to file/file_name\0uniqueID:scope_end_start
12830:         where scope -> public,guest,course,group,domains or users.
12831:               end -> UNIX time for end of access (0 -> no end date)
12832:               start -> UNIX time for start of access
12833: 
12834:     value -> XML description of access control
12835:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
12836:             <start></start>
12837:             <end></end>
12838: 
12839:             <password></password>  for scope type = guest
12840: 
12841:             <domain></domain>     for scope type = course or group
12842:             <number></number>
12843:             <roles id="">
12844:              <role></role>
12845:              <access></access>
12846:              <section></section>
12847:              <group></group>
12848:             </roles>
12849: 
12850:             <dom></dom>         for scope type = domains
12851: 
12852:             <users>             for scope type = users
12853:              <user>
12854:               <uname></uname>
12855:               <udom></udom>
12856:              </user>
12857:             </users>
12858:            </scope> 
12859:               
12860:  Access data is also aggregated for each file in an additional key=value pair:
12861:  key -> path to file/file_name\0accesscontrol 
12862:  value -> reference to hash
12863:           hash contains key = value pairs
12864:           where key = uniqueID:scope_end_start
12865:                 value = UNIX time record was last updated
12866: 
12867:           Used to improve speed of look-ups of access controls for each file.  
12868:  
12869:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
12870: 
12871: modify_access_controls():
12872: 
12873: Modifies access controls for a portfolio file
12874: Args
12875: 1. file name
12876: 2. reference to hash of required changes,
12877: 3. domain
12878: 4. username
12879:   where domain,username are the domain of the portfolio owner 
12880:   (either a user or a course) 
12881: 
12882: Returns:
12883: 1. result of additions or updates ('ok' or 'error', with error message). 
12884: 2. result of deletions ('ok' or 'error', with error message).
12885: 3. reference to hash of any new or updated access controls.
12886: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
12887:    key = integer (inbound ID)
12888:    value = uniqueID  
12889: 
12890: =back
12891: 
12892: =head2 HTTP Helper Routines
12893: 
12894: =over 4
12895: 
12896: =item *
12897: 
12898: escape() : unpack non-word characters into CGI-compatible hex codes
12899: 
12900: =item *
12901: 
12902: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
12903: 
12904: =back
12905: 
12906: =head1 PRIVATE SUBROUTINES
12907: 
12908: =head2 Underlying communication routines (Shouldn't call)
12909: 
12910: =over 4
12911: 
12912: =item *
12913: 
12914: subreply() : tries to pass a message to lonc, returns con_lost if incapable
12915: 
12916: =item *
12917: 
12918: reply() : uses subreply to send a message to remote machine, logs all failures
12919: 
12920: =item *
12921: 
12922: critical() : passes a critical message to another server; if cannot
12923: get through then place message in connection buffer directory and
12924: returns con_delayed, if incapable of saving message, returns
12925: con_failed
12926: 
12927: =item *
12928: 
12929: reconlonc() : tries to reconnect lonc client processes.
12930: 
12931: =back
12932: 
12933: =head2 Resource Access Logging
12934: 
12935: =over 4
12936: 
12937: =item *
12938: 
12939: flushcourselogs() : flush (save) buffer logs and access logs
12940: 
12941: =item *
12942: 
12943: courselog($what) : save message for course in hash
12944: 
12945: =item *
12946: 
12947: courseacclog($what) : save message for course using &courselog().  Perform
12948: special processing for specific resource types (problems, exams, quizzes, etc).
12949: 
12950: =item *
12951: 
12952: goodbye() : flush course logs and log shutting down; it is called in srm.conf
12953: as a PerlChildExitHandler
12954: 
12955: =back
12956: 
12957: =head2 Other
12958: 
12959: =over 4
12960: 
12961: =item *
12962: 
12963: symblist($mapname,%newhash) : update symbolic storage links
12964: 
12965: =back
12966: 
12967: =cut
12968: 

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