File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1184: download - view: text, annotated - select for diffs
Fri Aug 17 22:43:58 2012 UTC (11 years, 11 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Logging of role changes for domain roles and co-author roles
  (who, what, when, context, and by whom).
- Access to appropriate log via submenu in Modify users in au or dc context
- Scripts used to make, add or expire DC role from command line also write
  to rolelog.db on same server (stored with domainconfig user).

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1184 2012/08/17 22:43:58 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: # ---------------------------------------------------------------- Role Logging
  117: {
  118:     my $logid;
  119:     sub write_rolelog {
  120: 	my ($context,$hash_name,$storehash,$delflag,$udom,$uname,$cdom,$cnum)=@_;
  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_rolelog('course',$namespace,\%storehash,$delflag,$domain,
 3559:                        $username,$cdom,$cnum);
 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_rolelog('domain',$namespace,\%storehash,$delflag,$domain,
 3580:                        $username,$cdom,$domconfiguser);
 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_rolelog('author',$namespace,\%storehash,$delflag,$domain,
 3599:                        $username,$audom,$auname);
 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) = split(/_/,$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:     if ($env{$cckey}) {
 5053:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 5054:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 5055:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 5056:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 5057:         }
 5058:     } else {
 5059:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 5060:     }
 5061: }
 5062: 
 5063: sub set_adhoc_privileges {
 5064: # role can be cc or ca
 5065:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
 5066:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 5067:     my $spec = $role.'.'.$area;
 5068:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 5069:                                   $env{'user.name'});
 5070:     my %ccrole = ();
 5071:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
 5072:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
 5073:     &appenv(\%userroles,[$role,'cm']);
 5074:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 5075:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
 5076:         &appenv( {'request.role'        => $spec,
 5077:                   'request.role.domain' => $dcdom,
 5078:                   'request.course.sec'  => ''
 5079:                  }
 5080:                );
 5081:         my $tadv=0;
 5082:         if (&allowed('adv') eq 'F') { $tadv=1; }
 5083:         &appenv({'request.role.adv'    => $tadv});
 5084:     }
 5085: }
 5086: 
 5087: # --------------------------------------------------------------- get interface
 5088: 
 5089: sub get {
 5090:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5091:    my $items='';
 5092:    foreach my $item (@$storearr) {
 5093:        $items.=&escape($item).'&';
 5094:    }
 5095:    $items=~s/\&$//;
 5096:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5097:    if (!$uname) { $uname=$env{'user.name'}; }
 5098:    my $uhome=&homeserver($uname,$udomain);
 5099: 
 5100:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 5101:    my @pairs=split(/\&/,$rep);
 5102:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 5103:      return @pairs;
 5104:    }
 5105:    my %returnhash=();
 5106:    my $i=0;
 5107:    foreach my $item (@$storearr) {
 5108:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 5109:       $i++;
 5110:    }
 5111:    return %returnhash;
 5112: }
 5113: 
 5114: # --------------------------------------------------------------- del interface
 5115: 
 5116: sub del {
 5117:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5118:    my $items='';
 5119:    foreach my $item (@$storearr) {
 5120:        $items.=&escape($item).'&';
 5121:    }
 5122: 
 5123:    $items=~s/\&$//;
 5124:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5125:    if (!$uname) { $uname=$env{'user.name'}; }
 5126:    my $uhome=&homeserver($uname,$udomain);
 5127:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 5128: }
 5129: 
 5130: # -------------------------------------------------------------- dump interface
 5131: 
 5132: sub unserialize {
 5133:     my ($rep, $escapedkeys) = @_;
 5134: 
 5135:     return {} if $rep =~ /^error/;
 5136: 
 5137:     my %returnhash=();
 5138: 	foreach my $item (split /\&/, $rep) {
 5139: 	    my ($key, $value) = split(/=/, $item, 2);
 5140: 	    $key = unescape($key) unless $escapedkeys;
 5141: 	    next if $key =~ /^error: 2 /;
 5142: 	    $returnhash{$key} = Apache::lonnet::thaw_unescape($value);
 5143: 	}
 5144:     #return %returnhash;
 5145:     return \%returnhash;
 5146: }        
 5147: 
 5148: # see Lond::dump_with_regexp
 5149: # if $escapedkeys hash keys won't get unescaped.
 5150: sub dump {
 5151:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
 5152:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5153:     if (!$uname) { $uname=$env{'user.name'}; }
 5154:     my $uhome=&homeserver($uname,$udomain);
 5155: 
 5156:     my $reply;
 5157:     if (grep { $_ eq $uhome } current_machine_ids()) {
 5158:         # user is hosted on this machine
 5159:         $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
 5160:                     $uname, $namespace, $regexp, $range)), $loncaparevs{$uhome});
 5161:         return %{unserialize($reply, $escapedkeys)};
 5162:     }
 5163:     if ($regexp) {
 5164: 	$regexp=&escape($regexp);
 5165:     } else {
 5166: 	$regexp='.';
 5167:     }
 5168:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 5169:     my @pairs=split(/\&/,$rep);
 5170:     my %returnhash=();
 5171:     if (!($rep =~ /^error/ )) {
 5172: 	foreach my $item (@pairs) {
 5173: 	    my ($key,$value)=split(/=/,$item,2);
 5174:         $key = unescape($key) unless $escapedkeys;
 5175:         #$key = &unescape($key);
 5176: 	    next if ($key =~ /^error: 2 /);
 5177: 	    $returnhash{$key}=&thaw_unescape($value);
 5178: 	}
 5179:     }
 5180:     return %returnhash;
 5181: }
 5182: 
 5183: 
 5184: # --------------------------------------------------------- dumpstore interface
 5185: 
 5186: sub dumpstore {
 5187:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 5188:    # same as dump but keys must be escaped. They may contain colon separated
 5189:    # lists of values that may themself contain colons (e.g. symbs).
 5190:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
 5191: }
 5192: 
 5193: # -------------------------------------------------------------- keys interface
 5194: 
 5195: sub getkeys {
 5196:    my ($namespace,$udomain,$uname)=@_;
 5197:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5198:    if (!$uname) { $uname=$env{'user.name'}; }
 5199:    my $uhome=&homeserver($uname,$udomain);
 5200:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 5201:    my @keyarray=();
 5202:    foreach my $key (split(/\&/,$rep)) {
 5203:       next if ($key =~ /^error: 2 /);
 5204:       push(@keyarray,&unescape($key));
 5205:    }
 5206:    return @keyarray;
 5207: }
 5208: 
 5209: # --------------------------------------------------------------- currentdump
 5210: sub currentdump {
 5211:    my ($courseid,$sdom,$sname)=@_;
 5212:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 5213:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 5214:    $sname    = $env{'user.name'}         if (! defined($sname));
 5215:    my $uhome = &homeserver($sname,$sdom);
 5216:    my $rep;
 5217: 
 5218:    if (grep { $_ eq $uhome } current_machine_ids()) {
 5219:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
 5220:                    $courseid)));
 5221:    } else {
 5222:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 5223:    }
 5224: 
 5225:    return if ($rep =~ /^(error:|no_such_host)/);
 5226:    #
 5227:    my %returnhash=();
 5228:    #
 5229:    if ($rep eq "unknown_cmd") { 
 5230:        # an old lond will not know currentdump
 5231:        # Do a dump and make it look like a currentdump
 5232:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 5233:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 5234:        my %hash = @tmp;
 5235:        @tmp=();
 5236:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 5237:    } else {
 5238:        my @pairs=split(/\&/,$rep);
 5239:        foreach my $pair (@pairs) {
 5240:            my ($key,$value)=split(/=/,$pair,2);
 5241:            my ($symb,$param) = split(/:/,$key);
 5242:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 5243:                                                         &thaw_unescape($value);
 5244:        }
 5245:    }
 5246:    return %returnhash;
 5247: }
 5248: 
 5249: sub convert_dump_to_currentdump{
 5250:     my %hash = %{shift()};
 5251:     my %returnhash;
 5252:     # Code ripped from lond, essentially.  The only difference
 5253:     # here is the unescaping done by lonnet::dump().  Conceivably
 5254:     # we might run in to problems with parameter names =~ /^v\./
 5255:     while (my ($key,$value) = each(%hash)) {
 5256:         my ($v,$symb,$param) = split(/:/,$key);
 5257: 	$symb  = &unescape($symb);
 5258: 	$param = &unescape($param);
 5259:         next if ($v eq 'version' || $symb eq 'keys');
 5260:         next if (exists($returnhash{$symb}) &&
 5261:                  exists($returnhash{$symb}->{$param}) &&
 5262:                  $returnhash{$symb}->{'v.'.$param} > $v);
 5263:         $returnhash{$symb}->{$param}=$value;
 5264:         $returnhash{$symb}->{'v.'.$param}=$v;
 5265:     }
 5266:     #
 5267:     # Remove all of the keys in the hashes which keep track of
 5268:     # the version of the parameter.
 5269:     while (my ($symb,$param_hash) = each(%returnhash)) {
 5270:         # use a foreach because we are going to delete from the hash.
 5271:         foreach my $key (keys(%$param_hash)) {
 5272:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 5273:         }
 5274:     }
 5275:     return \%returnhash;
 5276: }
 5277: 
 5278: # ------------------------------------------------------ critical inc interface
 5279: 
 5280: sub cinc {
 5281:     return &inc(@_,'critical');
 5282: }
 5283: 
 5284: # --------------------------------------------------------------- inc interface
 5285: 
 5286: sub inc {
 5287:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 5288:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5289:     if (!$uname) { $uname=$env{'user.name'}; }
 5290:     my $uhome=&homeserver($uname,$udomain);
 5291:     my $items='';
 5292:     if (! ref($store)) {
 5293:         # got a single value, so use that instead
 5294:         $items = &escape($store).'=&';
 5295:     } elsif (ref($store) eq 'SCALAR') {
 5296:         $items = &escape($$store).'=&';        
 5297:     } elsif (ref($store) eq 'ARRAY') {
 5298:         $items = join('=&',map {&escape($_);} @{$store});
 5299:     } elsif (ref($store) eq 'HASH') {
 5300:         while (my($key,$value) = each(%{$store})) {
 5301:             $items.= &escape($key).'='.&escape($value).'&';
 5302:         }
 5303:     }
 5304:     $items=~s/\&$//;
 5305:     if ($critical) {
 5306: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 5307:     } else {
 5308: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 5309:     }
 5310: }
 5311: 
 5312: # --------------------------------------------------------------- put interface
 5313: 
 5314: sub put {
 5315:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5316:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5317:    if (!$uname) { $uname=$env{'user.name'}; }
 5318:    my $uhome=&homeserver($uname,$udomain);
 5319:    my $items='';
 5320:    foreach my $item (keys(%$storehash)) {
 5321:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5322:    }
 5323:    $items=~s/\&$//;
 5324:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5325: }
 5326: 
 5327: # ------------------------------------------------------------ newput interface
 5328: 
 5329: sub newput {
 5330:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5331:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5332:    if (!$uname) { $uname=$env{'user.name'}; }
 5333:    my $uhome=&homeserver($uname,$udomain);
 5334:    my $items='';
 5335:    foreach my $key (keys(%$storehash)) {
 5336:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 5337:    }
 5338:    $items=~s/\&$//;
 5339:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 5340: }
 5341: 
 5342: # ---------------------------------------------------------  putstore interface
 5343: 
 5344: sub putstore {
 5345:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 5346:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5347:    if (!$uname) { $uname=$env{'user.name'}; }
 5348:    my $uhome=&homeserver($uname,$udomain);
 5349:    my $items='';
 5350:    foreach my $key (keys(%$storehash)) {
 5351:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 5352:    }
 5353:    $items=~s/\&$//;
 5354:    my $esc_symb=&escape($symb);
 5355:    my $esc_v=&escape($version);
 5356:    my $reply =
 5357:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 5358: 	      $uhome);
 5359:    if ($reply eq 'unknown_cmd') {
 5360:        # gfall back to way things use to be done
 5361:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 5362: 			    $uname);
 5363:    }
 5364:    return $reply;
 5365: }
 5366: 
 5367: sub old_putstore {
 5368:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 5369:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5370:     if (!$uname) { $uname=$env{'user.name'}; }
 5371:     my $uhome=&homeserver($uname,$udomain);
 5372:     my %newstorehash;
 5373:     foreach my $item (keys(%$storehash)) {
 5374: 	my $key = $version.':'.&escape($symb).':'.$item;
 5375: 	$newstorehash{$key} = $storehash->{$item};
 5376:     }
 5377:     my $items='';
 5378:     my %allitems = ();
 5379:     foreach my $item (keys(%newstorehash)) {
 5380: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 5381: 	    my $key = $1.':keys:'.$2;
 5382: 	    $allitems{$key} .= $3.':';
 5383: 	}
 5384: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 5385:     }
 5386:     foreach my $item (keys(%allitems)) {
 5387: 	$allitems{$item} =~ s/\:$//;
 5388: 	$items.= $item.'='.$allitems{$item}.'&';
 5389:     }
 5390:     $items=~s/\&$//;
 5391:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5392: }
 5393: 
 5394: # ------------------------------------------------------ critical put interface
 5395: 
 5396: sub cput {
 5397:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5398:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5399:    if (!$uname) { $uname=$env{'user.name'}; }
 5400:    my $uhome=&homeserver($uname,$udomain);
 5401:    my $items='';
 5402:    foreach my $item (keys(%$storehash)) {
 5403:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5404:    }
 5405:    $items=~s/\&$//;
 5406:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 5407: }
 5408: 
 5409: # -------------------------------------------------------------- eget interface
 5410: 
 5411: sub eget {
 5412:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5413:    my $items='';
 5414:    foreach my $item (@$storearr) {
 5415:        $items.=&escape($item).'&';
 5416:    }
 5417:    $items=~s/\&$//;
 5418:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5419:    if (!$uname) { $uname=$env{'user.name'}; }
 5420:    my $uhome=&homeserver($uname,$udomain);
 5421:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 5422:    my @pairs=split(/\&/,$rep);
 5423:    my %returnhash=();
 5424:    my $i=0;
 5425:    foreach my $item (@$storearr) {
 5426:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 5427:       $i++;
 5428:    }
 5429:    return %returnhash;
 5430: }
 5431: 
 5432: # ------------------------------------------------------------ tmpput interface
 5433: sub tmpput {
 5434:     my ($storehash,$server,$context)=@_;
 5435:     my $items='';
 5436:     foreach my $item (keys(%$storehash)) {
 5437: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5438:     }
 5439:     $items=~s/\&$//;
 5440:     if (defined($context)) {
 5441:         $items .= ':'.&escape($context);
 5442:     }
 5443:     return &reply("tmpput:$items",$server);
 5444: }
 5445: 
 5446: # ------------------------------------------------------------ tmpget interface
 5447: sub tmpget {
 5448:     my ($token,$server)=@_;
 5449:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 5450:     my $rep=&reply("tmpget:$token",$server);
 5451:     my %returnhash;
 5452:     foreach my $item (split(/\&/,$rep)) {
 5453: 	my ($key,$value)=split(/=/,$item);
 5454:         next if ($key =~ /^error: 2 /);
 5455: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 5456:     }
 5457:     return %returnhash;
 5458: }
 5459: 
 5460: # ------------------------------------------------------------ tmpdel interface
 5461: sub tmpdel {
 5462:     my ($token,$server)=@_;
 5463:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 5464:     return &reply("tmpdel:$token",$server);
 5465: }
 5466: 
 5467: # -------------------------------------------------- portfolio access checking
 5468: 
 5469: sub portfolio_access {
 5470:     my ($requrl) = @_;
 5471:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 5472:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 5473:     if ($result) {
 5474:         my %setters;
 5475:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 5476:             my ($startblock,$endblock) =
 5477:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 5478:             if ($startblock && $endblock) {
 5479:                 return 'B';
 5480:             }
 5481:         } else {
 5482:             my ($startblock,$endblock) =
 5483:                 &Apache::loncommon::blockcheck(\%setters,'port');
 5484:             if ($startblock && $endblock) {
 5485:                 return 'B';
 5486:             }
 5487:         }
 5488:     }
 5489:     if ($result eq 'ok') {
 5490:        return 'F';
 5491:     } elsif ($result =~ /^[^:]+:guest_/) {
 5492:        return 'A';
 5493:     }
 5494:     return '';
 5495: }
 5496: 
 5497: sub get_portfolio_access {
 5498:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 5499: 
 5500:     if (!ref($access_hash)) {
 5501: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 5502: 	my %access_controls = &get_access_controls($current_perms,$group,
 5503: 						   $file_name);
 5504: 	$access_hash = $access_controls{$file_name};
 5505:     }
 5506: 
 5507:     my ($public,$guest,@domains,@users,@courses,@groups);
 5508:     my $now = time;
 5509:     if (ref($access_hash) eq 'HASH') {
 5510:         foreach my $key (keys(%{$access_hash})) {
 5511:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 5512:             if ($start > $now) {
 5513:                 next;
 5514:             }
 5515:             if ($end && $end<$now) {
 5516:                 next;
 5517:             }
 5518:             if ($scope eq 'public') {
 5519:                 $public = $key;
 5520:                 last;
 5521:             } elsif ($scope eq 'guest') {
 5522:                 $guest = $key;
 5523:             } elsif ($scope eq 'domains') {
 5524:                 push(@domains,$key);
 5525:             } elsif ($scope eq 'users') {
 5526:                 push(@users,$key);
 5527:             } elsif ($scope eq 'course') {
 5528:                 push(@courses,$key);
 5529:             } elsif ($scope eq 'group') {
 5530:                 push(@groups,$key);
 5531:             }
 5532:         }
 5533:         if ($public) {
 5534:             return 'ok';
 5535:         }
 5536:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 5537:             if ($guest) {
 5538:                 return $guest;
 5539:             }
 5540:         } else {
 5541:             if (@domains > 0) {
 5542:                 foreach my $domkey (@domains) {
 5543:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 5544:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 5545:                             return 'ok';
 5546:                         }
 5547:                     }
 5548:                 }
 5549:             }
 5550:             if (@users > 0) {
 5551:                 foreach my $userkey (@users) {
 5552:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 5553:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 5554:                             if (ref($item) eq 'HASH') {
 5555:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 5556:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 5557:                                     return 'ok';
 5558:                                 }
 5559:                             }
 5560:                         }
 5561:                     } 
 5562:                 }
 5563:             }
 5564:             my %roleshash;
 5565:             my @courses_and_groups = @courses;
 5566:             push(@courses_and_groups,@groups); 
 5567:             if (@courses_and_groups > 0) {
 5568:                 my (%allgroups,%allroles); 
 5569:                 my ($start,$end,$role,$sec,$group);
 5570:                 foreach my $envkey (%env) {
 5571:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 5572:                         my $cid = $2.'_'.$3; 
 5573:                         if ($1 eq 'gr') {
 5574:                             $group = $4;
 5575:                             $allgroups{$cid}{$group} = $env{$envkey};
 5576:                         } else {
 5577:                             if ($4 eq '') {
 5578:                                 $sec = 'none';
 5579:                             } else {
 5580:                                 $sec = $4;
 5581:                             }
 5582:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 5583:                         }
 5584:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 5585:                         my $cid = $2.'_'.$3;
 5586:                         if ($4 eq '') {
 5587:                             $sec = 'none';
 5588:                         } else {
 5589:                             $sec = $4;
 5590:                         }
 5591:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 5592:                     }
 5593:                 }
 5594:                 if (keys(%allroles) == 0) {
 5595:                     return;
 5596:                 }
 5597:                 foreach my $key (@courses_and_groups) {
 5598:                     my %content = %{$$access_hash{$key}};
 5599:                     my $cnum = $content{'number'};
 5600:                     my $cdom = $content{'domain'};
 5601:                     my $cid = $cdom.'_'.$cnum;
 5602:                     if (!exists($allroles{$cid})) {
 5603:                         next;
 5604:                     }    
 5605:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 5606:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 5607:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 5608:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 5609:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 5610:                         foreach my $role (keys(%{$allroles{$cid}})) {
 5611:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 5612:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 5613:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 5614:                                         if (grep/^all$/,@sections) {
 5615:                                             return 'ok';
 5616:                                         } else {
 5617:                                             if (grep/^$sec$/,@sections) {
 5618:                                                 return 'ok';
 5619:                                             }
 5620:                                         }
 5621:                                     }
 5622:                                 }
 5623:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 5624:                                     if (grep/^none$/,@groups) {
 5625:                                         return 'ok';
 5626:                                     }
 5627:                                 } else {
 5628:                                     if (grep/^all$/,@groups) {
 5629:                                         return 'ok';
 5630:                                     } 
 5631:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 5632:                                         if (grep/^$group$/,@groups) {
 5633:                                             return 'ok';
 5634:                                         }
 5635:                                     }
 5636:                                 } 
 5637:                             }
 5638:                         }
 5639:                     }
 5640:                 }
 5641:             }
 5642:             if ($guest) {
 5643:                 return $guest;
 5644:             }
 5645:         }
 5646:     }
 5647:     return;
 5648: }
 5649: 
 5650: sub course_group_datechecker {
 5651:     my ($dates,$now,$status) = @_;
 5652:     my ($start,$end) = split(/\./,$dates);
 5653:     if (!$start && !$end) {
 5654:         return 'ok';
 5655:     }
 5656:     if (grep/^active$/,@{$status}) {
 5657:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 5658:             return 'ok';
 5659:         }
 5660:     }
 5661:     if (grep/^previous$/,@{$status}) {
 5662:         if ($end > $now ) {
 5663:             return 'ok';
 5664:         }
 5665:     }
 5666:     if (grep/^future$/,@{$status}) {
 5667:         if ($start > $now) {
 5668:             return 'ok';
 5669:         }
 5670:     }
 5671:     return; 
 5672: }
 5673: 
 5674: sub parse_portfolio_url {
 5675:     my ($url) = @_;
 5676: 
 5677:     my ($type,$udom,$unum,$group,$file_name);
 5678:     
 5679:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 5680: 	$type = 1;
 5681:         $udom = $1;
 5682:         $unum = $2;
 5683:         $file_name = $3;
 5684:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 5685: 	$type = 2;
 5686:         $udom = $1;
 5687:         $unum = $2;
 5688:         $group = $3;
 5689:         $file_name = $3.'/'.$4;
 5690:     }
 5691:     if (wantarray) {
 5692: 	return ($type,$udom,$unum,$file_name,$group);
 5693:     }
 5694:     return $type;
 5695: }
 5696: 
 5697: sub is_portfolio_url {
 5698:     my ($url) = @_;
 5699:     return scalar(&parse_portfolio_url($url));
 5700: }
 5701: 
 5702: sub is_portfolio_file {
 5703:     my ($file) = @_;
 5704:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 5705:         return 1;
 5706:     }
 5707:     return;
 5708: }
 5709: 
 5710: sub usertools_access {
 5711:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 5712:     my ($access,%tools);
 5713:     if ($context eq '') {
 5714:         $context = 'tools';
 5715:     }
 5716:     if ($context eq 'requestcourses') {
 5717:         %tools = (
 5718:                       official   => 1,
 5719:                       unofficial => 1,
 5720:                       community  => 1,
 5721:                  );
 5722:     } elsif ($context eq 'requestauthor') {
 5723:         %tools = (
 5724:                       requestauthor => 1,
 5725:                  );
 5726:     } else {
 5727:         %tools = (
 5728:                       aboutme   => 1,
 5729:                       blog      => 1,
 5730:                       webdav    => 1,
 5731:                       portfolio => 1,
 5732:                  );
 5733:     }
 5734:     return if (!defined($tools{$tool}));
 5735: 
 5736:     if ((!defined($udom)) || (!defined($uname))) {
 5737:         $udom = $env{'user.domain'};
 5738:         $uname = $env{'user.name'};
 5739:     }
 5740: 
 5741:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 5742:         if ($action ne 'reload') {
 5743:             if ($context eq 'requestcourses') {
 5744:                 return $env{'environment.canrequest.'.$tool};
 5745:             } elsif ($context eq 'requestauthor') {
 5746:                 return $env{'environment.canrequest.author'};
 5747:             } else {
 5748:                 return $env{'environment.availabletools.'.$tool};
 5749:             }
 5750:         }
 5751:     }
 5752: 
 5753:     my ($toolstatus,$inststatus,$envkey);
 5754:     if ($context eq 'requestauthor') {
 5755:         $envkey = $context; 
 5756:     } else {
 5757:         $envkey = $context.'.'.$tool;
 5758:     }
 5759: 
 5760:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 5761:          ($action ne 'reload')) {
 5762:         $toolstatus = $env{'environment.'.$envkey};
 5763:         $inststatus = $env{'environment.inststatus'};
 5764:     } else {
 5765:         if (ref($userenvref) eq 'HASH') {
 5766:             $toolstatus = $userenvref->{$envkey};
 5767:             $inststatus = $userenvref->{'inststatus'};
 5768:         } else {
 5769:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 5770:             $toolstatus = $userenv{$envkey};
 5771:             $inststatus = $userenv{'inststatus'};
 5772:         }
 5773:     }
 5774: 
 5775:     if ($toolstatus ne '') {
 5776:         if ($toolstatus) {
 5777:             $access = 1;
 5778:         } else {
 5779:             $access = 0;
 5780:         }
 5781:         return $access;
 5782:     }
 5783: 
 5784:     my ($is_adv,%domdef);
 5785:     if (ref($is_advref) eq 'HASH') {
 5786:         $is_adv = $is_advref->{'is_adv'};
 5787:     } else {
 5788:         $is_adv = &is_advanced_user($udom,$uname);
 5789:     }
 5790:     if (ref($domdefref) eq 'HASH') {
 5791:         %domdef = %{$domdefref};
 5792:     } else {
 5793:         %domdef = &get_domain_defaults($udom);
 5794:     }
 5795:     if (ref($domdef{$tool}) eq 'HASH') {
 5796:         if ($is_adv) {
 5797:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 5798:                 if ($domdef{$tool}{'_LC_adv'}) { 
 5799:                     $access = 1;
 5800:                 } else {
 5801:                     $access = 0;
 5802:                 }
 5803:                 return $access;
 5804:             }
 5805:         }
 5806:         if ($inststatus ne '') {
 5807:             my ($hasaccess,$hasnoaccess);
 5808:             foreach my $affiliation (split(/:/,$inststatus)) {
 5809:                 if ($domdef{$tool}{$affiliation} ne '') { 
 5810:                     if ($domdef{$tool}{$affiliation}) {
 5811:                         $hasaccess = 1;
 5812:                     } else {
 5813:                         $hasnoaccess = 1;
 5814:                     }
 5815:                 }
 5816:             }
 5817:             if ($hasaccess || $hasnoaccess) {
 5818:                 if ($hasaccess) {
 5819:                     $access = 1;
 5820:                 } elsif ($hasnoaccess) {
 5821:                     $access = 0; 
 5822:                 }
 5823:                 return $access;
 5824:             }
 5825:         } else {
 5826:             if ($domdef{$tool}{'default'} ne '') {
 5827:                 if ($domdef{$tool}{'default'}) {
 5828:                     $access = 1;
 5829:                 } elsif ($domdef{$tool}{'default'} == 0) {
 5830:                     $access = 0;
 5831:                 }
 5832:                 return $access;
 5833:             }
 5834:         }
 5835:     } else {
 5836:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 5837:             $access = 1;
 5838:         } else {
 5839:             $access = 0;
 5840:         }
 5841:         return $access;
 5842:     }
 5843: }
 5844: 
 5845: sub is_course_owner {
 5846:     my ($cdom,$cnum,$udom,$uname) = @_;
 5847:     if (($udom eq '') || ($uname eq '')) {
 5848:         $udom = $env{'user.domain'};
 5849:         $uname = $env{'user.name'};
 5850:     }
 5851:     unless (($udom eq '') || ($uname eq '')) {
 5852:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 5853:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 5854:                 return 1;
 5855:             } else {
 5856:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 5857:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 5858:                     return 1;
 5859:                 }
 5860:             }
 5861:         }
 5862:     }
 5863:     return;
 5864: }
 5865: 
 5866: sub is_advanced_user {
 5867:     my ($udom,$uname) = @_;
 5868:     if ($udom ne '' && $uname ne '') {
 5869:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 5870:             if (wantarray) {
 5871:                 return ($env{'user.adv'},$env{'user.author'});
 5872:             } else {
 5873:                 return $env{'user.adv'};
 5874:             }
 5875:         }
 5876:     }
 5877:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 5878:     my %allroles;
 5879:     my ($is_adv,$is_author);
 5880:     foreach my $role (keys(%roleshash)) {
 5881:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 5882:         my $area = '/'.$tdomain.'/'.$trest;
 5883:         if ($sec ne '') {
 5884:             $area .= '/'.$sec;
 5885:         }
 5886:         if (($area ne '') && ($trole ne '')) {
 5887:             my $spec=$trole.'.'.$area;
 5888:             if ($trole =~ /^cr\//) {
 5889:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 5890:             } elsif ($trole ne 'gr') {
 5891:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 5892:             }
 5893:             if ($trole eq 'au') {
 5894:                 $is_author = 1;
 5895:             }
 5896:         }
 5897:     }
 5898:     foreach my $role (keys(%allroles)) {
 5899:         last if ($is_adv);
 5900:         foreach my $item (split(/:/,$allroles{$role})) {
 5901:             if ($item ne '') {
 5902:                 my ($privilege,$restrictions)=split(/&/,$item);
 5903:                 if ($privilege eq 'adv') {
 5904:                     $is_adv = 1;
 5905:                     last;
 5906:                 }
 5907:             }
 5908:         }
 5909:     }
 5910:     if (wantarray) {
 5911:         return ($is_adv,$is_author);
 5912:     }
 5913:     return $is_adv;
 5914: }
 5915: 
 5916: sub check_can_request {
 5917:     my ($dom,$can_request,$request_domains) = @_;
 5918:     my $canreq = 0;
 5919:     my ($types,$typename) = &Apache::loncommon::course_types();
 5920:     my @options = ('approval','validate','autolimit');
 5921:     my $optregex = join('|',@options);
 5922:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 5923:         foreach my $type (@{$types}) {
 5924:             if (&usertools_access($env{'user.name'},
 5925:                                   $env{'user.domain'},
 5926:                                   $type,undef,'requestcourses')) {
 5927:                 $canreq ++;
 5928:                 if (ref($request_domains) eq 'HASH') {
 5929:                     push(@{$request_domains->{$type}},$env{'user.domain'});
 5930:                 }
 5931:                 if ($dom eq $env{'user.domain'}) {
 5932:                     $can_request->{$type} = 1;
 5933:                 }
 5934:             }
 5935:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
 5936:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 5937:                 if (@curr > 0) {
 5938:                     foreach my $item (@curr) {
 5939:                         if (ref($request_domains) eq 'HASH') {
 5940:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 5941:                             if ($otherdom ne '') {
 5942:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 5943:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 5944:                                         push(@{$request_domains->{$type}},$otherdom);
 5945:                                     }
 5946:                                 } else {
 5947:                                     push(@{$request_domains->{$type}},$otherdom);
 5948:                                 }
 5949:                             }
 5950:                         }
 5951:                     }
 5952:                     unless($dom eq $env{'user.domain'}) {
 5953:                         $canreq ++;
 5954:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 5955:                             $can_request->{$type} = 1;
 5956:                         }
 5957:                     }
 5958:                 }
 5959:             }
 5960:         }
 5961:     }
 5962:     return $canreq;
 5963: }
 5964: 
 5965: # ---------------------------------------------- Custom access rule evaluation
 5966: 
 5967: sub customaccess {
 5968:     my ($priv,$uri)=@_;
 5969:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 5970:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 5971:     $udom = &LONCAPA::clean_domain($udom);
 5972:     $ucrs = &LONCAPA::clean_username($ucrs);
 5973:     my $access=0;
 5974:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 5975: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 5976: 	if ($type eq 'user') {
 5977: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 5978: 		my ($tdom,$tuname)=split(m{/},$scope);
 5979: 		if ($tdom) {
 5980: 		    if ($tdom ne $env{'user.domain'}) { next; }
 5981: 		}
 5982: 		if ($tuname) {
 5983: 		    if ($tuname ne $env{'user.name'}) { next; }
 5984: 		}
 5985: 		$access=($effect eq 'allow');
 5986: 		last;
 5987: 	    }
 5988: 	} else {
 5989: 	    if ($role) {
 5990: 		if ($role ne $urole) { next; }
 5991: 	    }
 5992: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 5993: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 5994: 		if ($tdom) {
 5995: 		    if ($tdom ne $udom) { next; }
 5996: 		}
 5997: 		if ($tcrs) {
 5998: 		    if ($tcrs ne $ucrs) { next; }
 5999: 		}
 6000: 		if ($tsec) {
 6001: 		    if ($tsec ne $usec) { next; }
 6002: 		}
 6003: 		$access=($effect eq 'allow');
 6004: 		last;
 6005: 	    }
 6006: 	    if ($realm eq '' && $role eq '') {
 6007: 		$access=($effect eq 'allow');
 6008: 	    }
 6009: 	}
 6010:     }
 6011:     return $access;
 6012: }
 6013: 
 6014: # ------------------------------------------------- Check for a user privilege
 6015: 
 6016: sub allowed {
 6017:     my ($priv,$uri,$symb,$role)=@_;
 6018:     my $ver_orguri=$uri;
 6019:     $uri=&deversion($uri);
 6020:     my $orguri=$uri;
 6021:     $uri=&declutter($uri);
 6022: 
 6023:     if ($priv eq 'evb') {
 6024: # Evade communication block restrictions for specified role in a course
 6025:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 6026:             return $1;
 6027:         } else {
 6028:             return;
 6029:         }
 6030:     }
 6031: 
 6032:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 6033: # Free bre access to adm and meta resources
 6034:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 6035: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 6036: 	&& ($priv eq 'bre')) {
 6037: 	return 'F';
 6038:     }
 6039: 
 6040: # Free bre access to user's own portfolio contents
 6041:     my ($space,$domain,$name,@dir)=split('/',$uri);
 6042:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 6043: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 6044:         my %setters;
 6045:         my ($startblock,$endblock) = 
 6046:             &Apache::loncommon::blockcheck(\%setters,'port');
 6047:         if ($startblock && $endblock) {
 6048:             return 'B';
 6049:         } else {
 6050:             return 'F';
 6051:         }
 6052:     }
 6053: 
 6054: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 6055:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 6056:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 6057:         if (exists($env{'request.course.id'})) {
 6058:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6059:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6060:             if (($domain eq $cdom) && ($name eq $cnum)) {
 6061:                 my $courseprivid=$env{'request.course.id'};
 6062:                 $courseprivid=~s/\_/\//;
 6063:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 6064:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 6065:                     return $1; 
 6066:                 } else {
 6067:                     if ($env{'request.course.sec'}) {
 6068:                         $courseprivid.='/'.$env{'request.course.sec'};
 6069:                     }
 6070:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 6071:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 6072:                         return $2;
 6073:                     }
 6074:                 }
 6075:             }
 6076:         }
 6077:     }
 6078: 
 6079: # Free bre to public access
 6080: 
 6081:     if ($priv eq 'bre') {
 6082:         my $copyright=&metadata($uri,'copyright');
 6083: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 6084:            return 'F'; 
 6085:         }
 6086:         if ($copyright eq 'priv') {
 6087:             $uri=~/([^\/]+)\/([^\/]+)\//;
 6088: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 6089: 		return '';
 6090:             }
 6091:         }
 6092:         if ($copyright eq 'domain') {
 6093:             $uri=~/([^\/]+)\/([^\/]+)\//;
 6094: 	    unless (($env{'user.domain'} eq $1) ||
 6095:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 6096: 		return '';
 6097:             }
 6098:         }
 6099:         if ($env{'request.role'}=~ /li\.\//) {
 6100:             # Library role, so allow browsing of resources in this domain.
 6101:             return 'F';
 6102:         }
 6103:         if ($copyright eq 'custom') {
 6104: 	    unless (&customaccess($priv,$uri)) { return ''; }
 6105:         }
 6106:     }
 6107:     # Domain coordinator is trying to create a course
 6108:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 6109:         # uri is the requested domain in this case.
 6110:         # comparison to 'request.role.domain' shows if the user has selected
 6111:         # a role of dc for the domain in question.
 6112:         return 'F' if ($uri eq $env{'request.role.domain'});
 6113:     }
 6114: 
 6115:     my $thisallowed='';
 6116:     my $statecond=0;
 6117:     my $courseprivid='';
 6118: 
 6119:     my $ownaccess;
 6120:     # Community Coordinator or Assistant Co-author browsing resource space.
 6121:     if (($priv eq 'bro') && ($env{'user.author'})) {
 6122:         if ($uri eq '') {
 6123:             $ownaccess = 1;
 6124:         } else {
 6125:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 6126:                 my $udom = $env{'user.domain'};
 6127:                 my $uname = $env{'user.name'};
 6128:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 6129:                     $ownaccess = 1;
 6130:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 6131:                     unless ($uri =~ m{\.\./}) {
 6132:                         $ownaccess = 1;
 6133:                     }
 6134:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 6135:                     my $now = time;
 6136:                     if ($uri =~ m{^([^/]+)/?$}) {
 6137:                         my $adom = $1;
 6138:                         foreach my $key (keys(%env)) {
 6139:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 6140:                                 my ($start,$end) = split('.',$env{$key});
 6141:                                 if (($now >= $start) && (!$end || $end < $now)) {
 6142:                                     $ownaccess = 1;
 6143:                                     last;
 6144:                                 }
 6145:                             }
 6146:                         }
 6147:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 6148:                         my $adom = $1;
 6149:                         my $aname = $2;
 6150:                         foreach my $role ('ca','aa') { 
 6151:                             if ($env{"user.role.$role./$adom/$aname"}) {
 6152:                                 my ($start,$end) =
 6153:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 6154:                                 if (($now >= $start) && (!$end || $end < $now)) {
 6155:                                     $ownaccess = 1;
 6156:                                     last;
 6157:                                 }
 6158:                             }
 6159:                         }
 6160:                     }
 6161:                 }
 6162:             }
 6163:         }
 6164:     }
 6165: 
 6166: # Course
 6167: 
 6168:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 6169:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6170:             $thisallowed.=$1;
 6171:         }
 6172:     }
 6173: 
 6174: # Domain
 6175: 
 6176:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 6177:        =~/\Q$priv\E\&([^\:]*)/) {
 6178:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6179:             $thisallowed.=$1;
 6180:         }
 6181:     }
 6182: 
 6183: # User who is not author or co-author might still be able to edit
 6184: # resource of an author in the domain (e.g., if Domain Coordinator).
 6185:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 6186:         (&allowed('mdc',$env{'request.course.id'}))) {
 6187:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 6188:             $thisallowed.=$1;
 6189:         }
 6190:     }
 6191: 
 6192: # Course: uri itself is a course
 6193:     my $courseuri=$uri;
 6194:     $courseuri=~s/\_(\d)/\/$1/;
 6195:     $courseuri=~s/^([^\/])/\/$1/;
 6196: 
 6197:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 6198:        =~/\Q$priv\E\&([^\:]*)/) {
 6199:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6200:             $thisallowed.=$1;
 6201:         }
 6202:     }
 6203: 
 6204: # URI is an uploaded document for this course, default permissions don't matter
 6205: # not allowing 'edit' access (editupload) to uploaded course docs
 6206:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 6207: 	$thisallowed='';
 6208:         my ($match)=&is_on_map($uri);
 6209:         if ($match) {
 6210:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 6211:                   =~/\Q$priv\E\&([^\:]*)/) {
 6212:                 my @blockers = &has_comm_blocking($priv,$symb,$uri);
 6213:                 if (@blockers > 0) {
 6214:                     $thisallowed = 'B';
 6215:                 } else {
 6216:                     $thisallowed.=$1;
 6217:                 }
 6218:             }
 6219:         } else {
 6220:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 6221:             if ($refuri) {
 6222:                 if ($refuri =~ m|^/adm/|) {
 6223:                     $thisallowed='F';
 6224:                 } else {
 6225:                     $refuri=&declutter($refuri);
 6226:                     my ($match) = &is_on_map($refuri);
 6227:                     if ($match) {
 6228:                         my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 6229:                         if (@blockers > 0) {
 6230:                             $thisallowed = 'B';
 6231:                         } else {
 6232:                             $thisallowed='F';
 6233:                         }
 6234:                     }
 6235:                 }
 6236:             }
 6237:         }
 6238:     }
 6239: 
 6240:     if ($priv eq 'bre'
 6241: 	&& $thisallowed ne 'F' 
 6242: 	&& $thisallowed ne '2'
 6243: 	&& &is_portfolio_url($uri)) {
 6244: 	$thisallowed = &portfolio_access($uri);
 6245:     }
 6246:     
 6247: # Full access at system, domain or course-wide level? Exit.
 6248:     if ($thisallowed=~/F/) {
 6249: 	return 'F';
 6250:     }
 6251: 
 6252: # If this is generating or modifying users, exit with special codes
 6253: 
 6254:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 6255: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 6256: 	    my ($audom,$auname)=split('/',$uri);
 6257: # no author name given, so this just checks on the general right to make a co-author in this domain
 6258: 	    unless ($auname) { return $thisallowed; }
 6259: # an author name is given, so we are about to actually make a co-author for a certain account
 6260: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 6261: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 6262: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 6263: 	}
 6264: 	return $thisallowed;
 6265:     }
 6266: #
 6267: # Gathered so far: system, domain and course wide privileges
 6268: #
 6269: # Course: See if uri or referer is an individual resource that is part of 
 6270: # the course
 6271: 
 6272:     if ($env{'request.course.id'}) {
 6273: 
 6274:        $courseprivid=$env{'request.course.id'};
 6275:        if ($env{'request.course.sec'}) {
 6276:           $courseprivid.='/'.$env{'request.course.sec'};
 6277:        }
 6278:        $courseprivid=~s/\_/\//;
 6279:        my $checkreferer=1;
 6280:        my ($match,$cond)=&is_on_map($uri);
 6281:        if ($match) {
 6282:            $statecond=$cond;
 6283:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 6284:                =~/\Q$priv\E\&([^\:]*)/) {
 6285:                my $value = $1;
 6286:                if ($priv eq 'bre') {
 6287:                    my @blockers = &has_comm_blocking($priv,$symb,$uri);
 6288:                    if (@blockers > 0) {
 6289:                        $thisallowed = 'B';
 6290:                    } else {
 6291:                        $thisallowed.=$value;
 6292:                    }
 6293:                } else {
 6294:                    $thisallowed.=$value;
 6295:                }
 6296:                $checkreferer=0;
 6297:            }
 6298:        }
 6299:        
 6300:        if ($checkreferer) {
 6301: 	  my $refuri=$env{'httpref.'.$orguri};
 6302:             unless ($refuri) {
 6303:                 foreach my $key (keys(%env)) {
 6304: 		    if ($key=~/^httpref\..*\*/) {
 6305: 			my $pattern=$key;
 6306:                         $pattern=~s/^httpref\.\/res\///;
 6307:                         $pattern=~s/\*/\[\^\/\]\+/g;
 6308:                         $pattern=~s/\//\\\//g;
 6309:                         if ($orguri=~/$pattern/) {
 6310: 			    $refuri=$env{$key};
 6311:                         }
 6312:                     }
 6313:                 }
 6314:             }
 6315: 
 6316:          if ($refuri) { 
 6317: 	  $refuri=&declutter($refuri);
 6318:           my ($match,$cond)=&is_on_map($refuri);
 6319:             if ($match) {
 6320:               my $refstatecond=$cond;
 6321:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 6322:                   =~/\Q$priv\E\&([^\:]*)/) {
 6323:                   my $value = $1;
 6324:                   if ($priv eq 'bre') {
 6325:                       my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 6326:                       if (@blockers > 0) {
 6327:                           $thisallowed = 'B';
 6328:                       } else {
 6329:                           $thisallowed.=$value;
 6330:                       }
 6331:                   } else {
 6332:                       $thisallowed.=$value;
 6333:                   }
 6334:                   $uri=$refuri;
 6335:                   $statecond=$refstatecond;
 6336:               }
 6337:           }
 6338:         }
 6339:        }
 6340:    }
 6341: 
 6342: #
 6343: # Gathered now: all privileges that could apply, and condition number
 6344: # 
 6345: #
 6346: # Full or no access?
 6347: #
 6348: 
 6349:     if ($thisallowed=~/F/) {
 6350: 	return 'F';
 6351:     }
 6352: 
 6353:     unless ($thisallowed) {
 6354:         return '';
 6355:     }
 6356: 
 6357: # Restrictions exist, deal with them
 6358: #
 6359: #   C:according to course preferences
 6360: #   R:according to resource settings
 6361: #   L:unless locked
 6362: #   X:according to user session state
 6363: #
 6364: 
 6365: # Possibly locked functionality, check all courses
 6366: # Locks might take effect only after 10 minutes cache expiration for other
 6367: # courses, and 2 minutes for current course
 6368: 
 6369:     my $envkey;
 6370:     if ($thisallowed=~/L/) {
 6371:         foreach $envkey (keys(%env)) {
 6372:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 6373:                my $courseid=$2;
 6374:                my $roleid=$1.'.'.$2;
 6375:                $courseid=~s/^\///;
 6376:                my $expiretime=600;
 6377:                if ($env{'request.role'} eq $roleid) {
 6378: 		  $expiretime=120;
 6379:                }
 6380: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 6381:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 6382:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 6383: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 6384:                }
 6385:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 6386:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 6387: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 6388:                        &log($env{'user.domain'},$env{'user.name'},
 6389:                             $env{'user.home'},
 6390:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 6391:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 6392:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 6393: 		       return '';
 6394:                    }
 6395:                }
 6396:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 6397:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 6398: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 6399:                        &log($env{'user.domain'},$env{'user.name'},
 6400:                             $env{'user.home'},
 6401:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 6402:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 6403:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 6404: 		       return '';
 6405:                    }
 6406:                }
 6407: 	   }
 6408:        }
 6409:     }
 6410:    
 6411: #
 6412: # Rest of the restrictions depend on selected course
 6413: #
 6414: 
 6415:     unless ($env{'request.course.id'}) {
 6416: 	if ($thisallowed eq 'A') {
 6417: 	    return 'A';
 6418:         } elsif ($thisallowed eq 'B') {
 6419:             return 'B';
 6420: 	} else {
 6421: 	    return '1';
 6422: 	}
 6423:     }
 6424: 
 6425: #
 6426: # Now user is definitely in a course
 6427: #
 6428: 
 6429: 
 6430: # Course preferences
 6431: 
 6432:    if ($thisallowed=~/C/) {
 6433:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 6434:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 6435:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 6436: 	   =~/\Q$rolecode\E/) {
 6437: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6438: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 6439: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 6440: 			$env{'request.course.id'});
 6441: 	   }
 6442:            return '';
 6443:        }
 6444: 
 6445:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 6446: 	   =~/\Q$unamedom\E/) {
 6447: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6448: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 6449: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 6450: 			$env{'request.course.id'});
 6451: 	   }
 6452:            return '';
 6453:        }
 6454:    }
 6455: 
 6456: # Resource preferences
 6457: 
 6458:    if ($thisallowed=~/R/) {
 6459:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 6460:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 6461: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6462: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 6463: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 6464: 	   }
 6465: 	   return '';
 6466:        }
 6467:    }
 6468: 
 6469: # Restricted by state or randomout?
 6470: 
 6471:    if ($thisallowed=~/X/) {
 6472:       if ($env{'acc.randomout'}) {
 6473: 	 if (!$symb) { $symb=&symbread($uri,1); }
 6474:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 6475:             return ''; 
 6476:          }
 6477:       }
 6478:       if (&condval($statecond)) {
 6479: 	 return '2';
 6480:       } else {
 6481:          return '';
 6482:       }
 6483:    }
 6484: 
 6485:     if ($thisallowed eq 'A') {
 6486: 	return 'A';
 6487:     } elsif ($thisallowed eq 'B') {
 6488:         return 'B';
 6489:     }
 6490:    return 'F';
 6491: }
 6492: 
 6493: sub get_comm_blocks {
 6494:     my ($cdom,$cnum) = @_;
 6495:     if ($cdom eq '' || $cnum eq '') {
 6496:         return unless ($env{'request.course.id'});
 6497:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6498:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6499:     }
 6500:     my %commblocks;
 6501:     my $hashid=$cdom.'_'.$cnum;
 6502:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 6503:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 6504:         %commblocks = %{$blocksref};
 6505:     } else {
 6506:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 6507:         my $cachetime = 600;
 6508:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 6509:     }
 6510:     return %commblocks;
 6511: }
 6512: 
 6513: sub has_comm_blocking {
 6514:     my ($priv,$symb,$uri,$blocks) = @_;
 6515:     return unless ($env{'request.course.id'});
 6516:     return unless ($priv eq 'bre');
 6517:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 6518:     my %commblocks;
 6519:     if (ref($blocks) eq 'HASH') {
 6520:         %commblocks = %{$blocks};
 6521:     } else {
 6522:         %commblocks = &get_comm_blocks();
 6523:     }
 6524:     return unless (keys(%commblocks) > 0);
 6525:     if (!$symb) { $symb=&symbread($uri,1); }
 6526:     my ($map,$resid,undef)=&decode_symb($symb);
 6527:     my %tocheck = (
 6528:                     maps      => $map,
 6529:                     resources => $symb,
 6530:                   );
 6531:     my @blockers;
 6532:     my $now = time;
 6533:     my $navmap = Apache::lonnavmaps::navmap->new();
 6534:     foreach my $block (keys(%commblocks)) {
 6535:         if ($block =~ /^(\d+)____(\d+)$/) {
 6536:             my ($start,$end) = ($1,$2);
 6537:             if ($start <= $now && $end >= $now) {
 6538:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 6539:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 6540:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 6541:                             if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
 6542:                                 unless (grep(/^\Q$block\E$/,@blockers)) {
 6543:                                     push(@blockers,$block);
 6544:                                 }
 6545:                             }
 6546:                         }
 6547:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 6548:                             if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
 6549:                                 unless (grep(/^\Q$block\E$/,@blockers)) {  
 6550:                                     push(@blockers,$block);
 6551:                                 }
 6552:                             }
 6553:                         }
 6554:                     }
 6555:                 }
 6556:             }
 6557:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 6558:             my $item = $1;
 6559:             my @to_test;
 6560:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 6561:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 6562:                     my $check_interval;
 6563:                     if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
 6564:                         my @interval;
 6565:                         my $type = 'map';
 6566:                         if ($item eq 'course') {
 6567:                             $type = 'course';
 6568:                             @interval=&EXT("resource.0.interval");
 6569:                         } else {
 6570:                             if ($item =~ /___\d+___/) {
 6571:                                 $type = 'resource';
 6572:                                 @interval=&EXT("resource.0.interval",$item);
 6573:                                 if (ref($navmap)) {                        
 6574:                                     my $res = $navmap->getBySymb($item); 
 6575:                                     push(@to_test,$res);
 6576:                                 }
 6577:                             } else {
 6578:                                 my $mapsymb = &symbread($item,1);
 6579:                                 if ($mapsymb) {
 6580:                                     if (ref($navmap)) {
 6581:                                         my $mapres = $navmap->getBySymb($mapsymb);
 6582:                                         @to_test = $mapres->retrieveResources($mapres,undef,0,1);
 6583:                                         foreach my $res (@to_test) {
 6584:                                             my $symb = $res->symb();
 6585:                                             next if ($symb eq $mapsymb);
 6586:                                             if ($symb ne '') {
 6587:                                                 @interval=&EXT("resource.0.interval",$symb);
 6588:                                                 last;
 6589:                                             }
 6590:                                         }
 6591:                                     }
 6592:                                 }
 6593:                             }
 6594:                         }
 6595:                         if ($interval[0] =~ /\d+/) {
 6596:                             my $first_access;
 6597:                             if ($type eq 'resource') {
 6598:                                 $first_access=&get_first_access($interval[1],$item);
 6599:                             } elsif ($type eq 'map') {
 6600:                                 $first_access=&get_first_access($interval[1],undef,$item);
 6601:                             } else {
 6602:                                 $first_access=&get_first_access($interval[1]);
 6603:                             }
 6604:                             if ($first_access) {
 6605:                                 my $timesup = $first_access+$interval[0];
 6606:                                 if ($timesup > $now) {
 6607:                                     foreach my $res (@to_test) {
 6608:                                         if ($res->is_problem()) {
 6609:                                             if ($res->completable()) {
 6610:                                                 unless (grep(/^\Q$block\E$/,@blockers)) {
 6611:                                                     push(@blockers,$block);
 6612:                                                 }
 6613:                                                 last;
 6614:                                             }
 6615:                                         }
 6616:                                     }
 6617:                                 }
 6618:                             }
 6619:                         }
 6620:                     }
 6621:                 }
 6622:             }
 6623:         }
 6624:     }
 6625:     return @blockers;
 6626: }
 6627: 
 6628: sub check_docs_block {
 6629:     my ($docsblock,$tocheck) =@_;
 6630:     if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
 6631:         return;
 6632:     }
 6633:     if (ref($docsblock->{'maps'}) eq 'HASH') {
 6634:         if ($tocheck->{'maps'}) {
 6635:             if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
 6636:                 return 1;
 6637:             }
 6638:         }
 6639:     }
 6640:     if (ref($docsblock->{'resources'}) eq 'HASH') {
 6641:         if ($tocheck->{'resources'}) {
 6642:             if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
 6643:                 return 1;
 6644:             }
 6645:         }
 6646:     }
 6647:     return;
 6648: }
 6649: 
 6650: #
 6651: #   Removes the versino from a URI and
 6652: #   splits it in to its filename and path to the filename.
 6653: #   Seems like File::Basename could have done this more clearly.
 6654: #   Parameters:
 6655: #      $uri   - input URI
 6656: #   Returns:
 6657: #     Two element list consisting of 
 6658: #     $pathname  - the URI up to and excluding the trailing /
 6659: #     $filename  - The part of the URI following the last /
 6660: #  NOTE:
 6661: #    Another realization of this is simply:
 6662: #    use File::Basename;
 6663: #    ...
 6664: #    $uri = shift;
 6665: #    $filename = basename($uri);
 6666: #    $path     = dirname($uri);
 6667: #    return ($filename, $path);
 6668: #
 6669: #     The implementation below is probably faster however.
 6670: #
 6671: sub split_uri_for_cond {
 6672:     my $uri=&deversion(&declutter(shift));
 6673:     my @uriparts=split(/\//,$uri);
 6674:     my $filename=pop(@uriparts);
 6675:     my $pathname=join('/',@uriparts);
 6676:     return ($pathname,$filename);
 6677: }
 6678: # --------------------------------------------------- Is a resource on the map?
 6679: 
 6680: sub is_on_map {
 6681:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 6682:     #Trying to find the conditional for the file
 6683:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 6684: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 6685:     if ($match) {
 6686: 	return (1,$1);
 6687:     } else {
 6688: 	return (0,0);
 6689:     }
 6690: }
 6691: 
 6692: # --------------------------------------------------------- Get symb from alias
 6693: 
 6694: sub get_symb_from_alias {
 6695:     my $symb=shift;
 6696:     my ($map,$resid,$url)=&decode_symb($symb);
 6697: # Already is a symb
 6698:     if ($url) { return $symb; }
 6699: # Must be an alias
 6700:     my $aliassymb='';
 6701:     my %bighash;
 6702:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6703:                             &GDBM_READER(),0640)) {
 6704:         my $rid=$bighash{'mapalias_'.$symb};
 6705: 	if ($rid) {
 6706: 	    my ($mapid,$resid)=split(/\./,$rid);
 6707: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 6708: 				    $resid,$bighash{'src_'.$rid});
 6709: 	}
 6710:         untie %bighash;
 6711:     }
 6712:     return $aliassymb;
 6713: }
 6714: 
 6715: # ----------------------------------------------------------------- Define Role
 6716: 
 6717: sub definerole {
 6718:   if (allowed('mcr','/')) {
 6719:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 6720:     foreach my $role (split(':',$sysrole)) {
 6721: 	my ($crole,$cqual)=split(/\&/,$role);
 6722:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 6723:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 6724: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 6725:                return "refused:s:$crole&$cqual"; 
 6726:             }
 6727:         }
 6728:     }
 6729:     foreach my $role (split(':',$domrole)) {
 6730: 	my ($crole,$cqual)=split(/\&/,$role);
 6731:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 6732:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 6733: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 6734:                return "refused:d:$crole&$cqual"; 
 6735:             }
 6736:         }
 6737:     }
 6738:     foreach my $role (split(':',$courole)) {
 6739: 	my ($crole,$cqual)=split(/\&/,$role);
 6740:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 6741:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 6742: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 6743:                return "refused:c:$crole&$cqual"; 
 6744:             }
 6745:         }
 6746:     }
 6747:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 6748:                 "$env{'user.domain'}:$env{'user.name'}:".
 6749: 	        "rolesdef_$rolename=".
 6750:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 6751:     return reply($command,$env{'user.home'});
 6752:   } else {
 6753:     return 'refused';
 6754:   }
 6755: }
 6756: 
 6757: # ---------------- Make a metadata query against the network of library servers
 6758: 
 6759: sub metadata_query {
 6760:     my ($query,$custom,$customshow,$server_array)=@_;
 6761:     my %rhash;
 6762:     my %libserv = &all_library();
 6763:     my @server_list = (defined($server_array) ? @$server_array
 6764:                                               : keys(%libserv) );
 6765:     for my $server (@server_list) {
 6766: 	unless ($custom or $customshow) {
 6767: 	    my $reply=&reply("querysend:".&escape($query),$server);
 6768: 	    $rhash{$server}=$reply;
 6769: 	}
 6770: 	else {
 6771: 	    my $reply=&reply("querysend:".&escape($query).':'.
 6772: 			     &escape($custom).':'.&escape($customshow),
 6773: 			     $server);
 6774: 	    $rhash{$server}=$reply;
 6775: 	}
 6776:     }
 6777:     return \%rhash;
 6778: }
 6779: 
 6780: # ----------------------------------------- Send log queries and wait for reply
 6781: 
 6782: sub log_query {
 6783:     my ($uname,$udom,$query,%filters)=@_;
 6784:     my $uhome=&homeserver($uname,$udom);
 6785:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 6786:     my $uhost=&hostname($uhome);
 6787:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 6788:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 6789:                        $uhome);
 6790:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 6791:     return get_query_reply($queryid);
 6792: }
 6793: 
 6794: # -------------------------- Update MySQL table for portfolio file
 6795: 
 6796: sub update_portfolio_table {
 6797:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 6798:     if ($group ne '') {
 6799:         $file_name =~s /^\Q$group\E//;
 6800:     }
 6801:     my $homeserver = &homeserver($uname,$udom);
 6802:     my $queryid=
 6803:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 6804:                ':'.&escape($file_name).':'.$action,$homeserver);
 6805:     my $reply = &get_query_reply($queryid);
 6806:     return $reply;
 6807: }
 6808: 
 6809: # -------------------------- Update MySQL allusers table
 6810: 
 6811: sub update_allusers_table {
 6812:     my ($uname,$udom,$names) = @_;
 6813:     my $homeserver = &homeserver($uname,$udom);
 6814:     my $queryid=
 6815:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 6816:                'lastname='.&escape($names->{'lastname'}).'%%'.
 6817:                'firstname='.&escape($names->{'firstname'}).'%%'.
 6818:                'middlename='.&escape($names->{'middlename'}).'%%'.
 6819:                'generation='.&escape($names->{'generation'}).'%%'.
 6820:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 6821:                'id='.&escape($names->{'id'}),$homeserver);
 6822:     return;
 6823: }
 6824: 
 6825: # ------- Request retrieval of institutional classlists for course(s)
 6826: 
 6827: sub fetch_enrollment_query {
 6828:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 6829:     my $homeserver;
 6830:     my $maxtries = 1;
 6831:     if ($context eq 'automated') {
 6832:         $homeserver = $perlvar{'lonHostID'};
 6833:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 6834:     } else {
 6835:         $homeserver = &homeserver($cnum,$dom);
 6836:     }
 6837:     my $host=&hostname($homeserver);
 6838:     my $cmd = '';
 6839:     foreach my $affiliate (keys(%{$affiliatesref})) {
 6840:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 6841:     }
 6842:     $cmd =~ s/%%$//;
 6843:     $cmd = &escape($cmd);
 6844:     my $query = 'fetchenrollment';
 6845:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 6846:     unless ($queryid=~/^\Q$host\E\_/) { 
 6847:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 6848:         return 'error: '.$queryid;
 6849:     }
 6850:     my $reply = &get_query_reply($queryid);
 6851:     my $tries = 1;
 6852:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 6853:         $reply = &get_query_reply($queryid);
 6854:         $tries ++;
 6855:     }
 6856:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 6857:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 6858:     } else {
 6859:         my @responses = split(/:/,$reply);
 6860:         if ($homeserver eq $perlvar{'lonHostID'}) {
 6861:             foreach my $line (@responses) {
 6862:                 my ($key,$value) = split(/=/,$line,2);
 6863:                 $$replyref{$key} = $value;
 6864:             }
 6865:         } else {
 6866:             my $pathname = LONCAPA::tempdir();
 6867:             foreach my $line (@responses) {
 6868:                 my ($key,$value) = split(/=/,$line);
 6869:                 $$replyref{$key} = $value;
 6870:                 if ($value > 0) {
 6871:                     foreach my $item (@{$$affiliatesref{$key}}) {
 6872:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 6873:                         my $destname = $pathname.'/'.$filename;
 6874:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 6875:                         if ($xml_classlist =~ /^error/) {
 6876:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 6877:                         } else {
 6878:                             if ( open(FILE,">$destname") ) {
 6879:                                 print FILE &unescape($xml_classlist);
 6880:                                 close(FILE);
 6881:                             } else {
 6882:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 6883:                             }
 6884:                         }
 6885:                     }
 6886:                 }
 6887:             }
 6888:         }
 6889:         return 'ok';
 6890:     }
 6891:     return 'error';
 6892: }
 6893: 
 6894: sub get_query_reply {
 6895:     my $queryid=shift;
 6896:     my $replyfile=LONCAPA::tempdir().$queryid;
 6897:     my $reply='';
 6898:     for (1..100) {
 6899: 	sleep 2;
 6900:         if (-e $replyfile.'.end') {
 6901: 	    if (open(my $fh,$replyfile)) {
 6902: 		$reply = join('',<$fh>);
 6903: 		close($fh);
 6904: 	   } else { return 'error: reply_file_error'; }
 6905:            return &unescape($reply);
 6906: 	}
 6907:     }
 6908:     return 'timeout:'.$queryid;
 6909: }
 6910: 
 6911: sub courselog_query {
 6912: #
 6913: # possible filters:
 6914: # url: url or symb
 6915: # username
 6916: # domain
 6917: # action: view, submit, grade
 6918: # start: timestamp
 6919: # end: timestamp
 6920: #
 6921:     my (%filters)=@_;
 6922:     unless ($env{'request.course.id'}) { return 'no_course'; }
 6923:     if ($filters{'url'}) {
 6924: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 6925:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 6926:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 6927:     }
 6928:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6929:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6930:     return &log_query($cname,$cdom,'courselog',%filters);
 6931: }
 6932: 
 6933: sub userlog_query {
 6934: #
 6935: # possible filters:
 6936: # action: log check role
 6937: # start: timestamp
 6938: # end: timestamp
 6939: #
 6940:     my ($uname,$udom,%filters)=@_;
 6941:     return &log_query($uname,$udom,'userlog',%filters);
 6942: }
 6943: 
 6944: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 6945: 
 6946: sub auto_run {
 6947:     my ($cnum,$cdom) = @_;
 6948:     my $response = 0;
 6949:     my $settings;
 6950:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 6951:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 6952:         $settings = $domconfig{'autoenroll'};
 6953:         if ($settings->{'run'} eq '1') {
 6954:             $response = 1;
 6955:         }
 6956:     } else {
 6957:         my $homeserver;
 6958:         if (&is_course($cdom,$cnum)) {
 6959:             $homeserver = &homeserver($cnum,$cdom);
 6960:         } else {
 6961:             $homeserver = &domain($cdom,'primary');
 6962:         }
 6963:         if ($homeserver ne 'no_host') {
 6964:             $response = &reply('autorun:'.$cdom,$homeserver);
 6965:         }
 6966:     }
 6967:     return $response;
 6968: }
 6969: 
 6970: sub auto_get_sections {
 6971:     my ($cnum,$cdom,$inst_coursecode) = @_;
 6972:     my $homeserver;
 6973:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 6974:         $homeserver = &homeserver($cnum,$cdom);
 6975:     }
 6976:     if (!defined($homeserver)) { 
 6977:         if ($cdom =~ /^$match_domain$/) {
 6978:             $homeserver = &domain($cdom,'primary');
 6979:         }
 6980:     }
 6981:     my @secs;
 6982:     if (defined($homeserver)) {
 6983:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 6984:         unless ($response eq 'refused') {
 6985:             @secs = split(/:/,$response);
 6986:         }
 6987:     }
 6988:     return @secs;
 6989: }
 6990: 
 6991: sub auto_new_course {
 6992:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 6993:     my $homeserver = &homeserver($cnum,$cdom);
 6994:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 6995:     return $response;
 6996: }
 6997: 
 6998: sub auto_validate_courseID {
 6999:     my ($cnum,$cdom,$inst_course_id) = @_;
 7000:     my $homeserver = &homeserver($cnum,$cdom);
 7001:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 7002:     return $response;
 7003: }
 7004: 
 7005: sub auto_validate_instcode {
 7006:     my ($cnum,$cdom,$instcode,$owner) = @_;
 7007:     my ($homeserver,$response);
 7008:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 7009:         $homeserver = &homeserver($cnum,$cdom);
 7010:     }
 7011:     if (!defined($homeserver)) {
 7012:         if ($cdom =~ /^$match_domain$/) {
 7013:             $homeserver = &domain($cdom,'primary');
 7014:         }
 7015:     }
 7016:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 7017:                         &escape($instcode).':'.&escape($owner),$homeserver));
 7018:     my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
 7019:     return ($outcome,$description);
 7020: }
 7021: 
 7022: sub auto_create_password {
 7023:     my ($cnum,$cdom,$authparam,$udom) = @_;
 7024:     my ($homeserver,$response);
 7025:     my $create_passwd = 0;
 7026:     my $authchk = '';
 7027:     if ($udom =~ /^$match_domain$/) {
 7028:         $homeserver = &domain($udom,'primary');
 7029:     }
 7030:     if ($homeserver eq '') {
 7031:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 7032:             $homeserver = &homeserver($cnum,$cdom);
 7033:         }
 7034:     }
 7035:     if ($homeserver eq '') {
 7036:         $authchk = 'nodomain';
 7037:     } else {
 7038:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 7039:         if ($response eq 'refused') {
 7040:             $authchk = 'refused';
 7041:         } else {
 7042:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 7043:         }
 7044:     }
 7045:     return ($authparam,$create_passwd,$authchk);
 7046: }
 7047: 
 7048: sub auto_photo_permission {
 7049:     my ($cnum,$cdom,$students) = @_;
 7050:     my $homeserver = &homeserver($cnum,$cdom);
 7051:     my ($outcome,$perm_reqd,$conditions) = 
 7052: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 7053:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7054: 	return (undef,undef);
 7055:     }
 7056:     return ($outcome,$perm_reqd,$conditions);
 7057: }
 7058: 
 7059: sub auto_checkphotos {
 7060:     my ($uname,$udom,$pid) = @_;
 7061:     my $homeserver = &homeserver($uname,$udom);
 7062:     my ($result,$resulttype);
 7063:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 7064: 				   &escape($uname).':'.&escape($pid),
 7065: 				   $homeserver));
 7066:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7067: 	return (undef,undef);
 7068:     }
 7069:     if ($outcome) {
 7070:         ($result,$resulttype) = split(/:/,$outcome);
 7071:     } 
 7072:     return ($result,$resulttype);
 7073: }
 7074: 
 7075: sub auto_photochoice {
 7076:     my ($cnum,$cdom) = @_;
 7077:     my $homeserver = &homeserver($cnum,$cdom);
 7078:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 7079: 						       &escape($cdom),
 7080: 						       $homeserver)));
 7081:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7082: 	return (undef,undef);
 7083:     }
 7084:     return ($update,$comment);
 7085: }
 7086: 
 7087: sub auto_photoupdate {
 7088:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 7089:     my $homeserver = &homeserver($cnum,$dom);
 7090:     my $host=&hostname($homeserver);
 7091:     my $cmd = '';
 7092:     my $maxtries = 1;
 7093:     foreach my $affiliate (keys(%{$affiliatesref})) {
 7094:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 7095:     }
 7096:     $cmd =~ s/%%$//;
 7097:     $cmd = &escape($cmd);
 7098:     my $query = 'institutionalphotos';
 7099:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 7100:     unless ($queryid=~/^\Q$host\E\_/) {
 7101:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 7102:         return 'error: '.$queryid;
 7103:     }
 7104:     my $reply = &get_query_reply($queryid);
 7105:     my $tries = 1;
 7106:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 7107:         $reply = &get_query_reply($queryid);
 7108:         $tries ++;
 7109:     }
 7110:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 7111:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 7112:     } else {
 7113:         my @responses = split(/:/,$reply);
 7114:         my $outcome = shift(@responses); 
 7115:         foreach my $item (@responses) {
 7116:             my ($key,$value) = split(/=/,$item);
 7117:             $$photo{$key} = $value;
 7118:         }
 7119:         return $outcome;
 7120:     }
 7121:     return 'error';
 7122: }
 7123: 
 7124: sub auto_instcode_format {
 7125:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 7126: 	$cat_order) = @_;
 7127:     my $courses = '';
 7128:     my @homeservers;
 7129:     if ($caller eq 'global') {
 7130: 	my %servers = &get_servers($codedom,'library');
 7131: 	foreach my $tryserver (keys(%servers)) {
 7132: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7133: 		push(@homeservers,$tryserver);
 7134: 	    }
 7135:         }
 7136:     } elsif ($caller eq 'requests') {
 7137:         if ($codedom =~ /^$match_domain$/) {
 7138:             my $chome = &domain($codedom,'primary');
 7139:             unless ($chome eq 'no_host') {
 7140:                 push(@homeservers,$chome);
 7141:             }
 7142:         }
 7143:     } else {
 7144:         push(@homeservers,&homeserver($caller,$codedom));
 7145:     }
 7146:     foreach my $code (keys(%{$instcodes})) {
 7147:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 7148:     }
 7149:     chop($courses);
 7150:     my $ok_response = 0;
 7151:     my $response;
 7152:     while (@homeservers > 0 && $ok_response == 0) {
 7153:         my $server = shift(@homeservers); 
 7154:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 7155:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 7156:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 7157: 		split(/:/,$response);
 7158:             %{$codes} = (%{$codes},&str2hash($codes_str));
 7159:             push(@{$codetitles},&str2array($codetitles_str));
 7160:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 7161:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 7162:             $ok_response = 1;
 7163:         }
 7164:     }
 7165:     if ($ok_response) {
 7166:         return 'ok';
 7167:     } else {
 7168:         return $response;
 7169:     }
 7170: }
 7171: 
 7172: sub auto_instcode_defaults {
 7173:     my ($domain,$returnhash,$code_order) = @_;
 7174:     my @homeservers;
 7175: 
 7176:     my %servers = &get_servers($domain,'library');
 7177:     foreach my $tryserver (keys(%servers)) {
 7178: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7179: 	    push(@homeservers,$tryserver);
 7180: 	}
 7181:     }
 7182: 
 7183:     my $response;
 7184:     foreach my $server (@homeservers) {
 7185:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 7186:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 7187: 	
 7188: 	foreach my $pair (split(/\&/,$response)) {
 7189: 	    my ($name,$value)=split(/\=/,$pair);
 7190: 	    if ($name eq 'code_order') {
 7191: 		@{$code_order} = split(/\&/,&unescape($value));
 7192: 	    } else {
 7193: 		$returnhash->{&unescape($name)}=&unescape($value);
 7194: 	    }
 7195: 	}
 7196: 	return 'ok';
 7197:     }
 7198: 
 7199:     return $response;
 7200: }
 7201: 
 7202: sub auto_possible_instcodes {
 7203:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 7204:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 7205:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 7206:         return;
 7207:     }
 7208:     my (@homeservers,$uhome);
 7209:     if (defined(&domain($domain,'primary'))) {
 7210:         $uhome=&domain($domain,'primary');
 7211:         push(@homeservers,&domain($domain,'primary'));
 7212:     } else {
 7213:         my %servers = &get_servers($domain,'library');
 7214:         foreach my $tryserver (keys(%servers)) {
 7215:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7216:                 push(@homeservers,$tryserver);
 7217:             }
 7218:         }
 7219:     }
 7220:     my $response;
 7221:     foreach my $server (@homeservers) {
 7222:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 7223:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 7224:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 7225:             split(':',$response);
 7226:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 7227:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 7228:         foreach my $item (split('&',$cat_title)) {   
 7229:             my ($name,$value)=split('=',$item);
 7230:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 7231:         }
 7232:         foreach my $item (split('&',$cat_order)) {
 7233:             my ($name,$value)=split('=',$item);
 7234:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 7235:         }
 7236:         return 'ok';
 7237:     }
 7238:     return $response;
 7239: }
 7240: 
 7241: sub auto_courserequest_checks {
 7242:     my ($dom) = @_;
 7243:     my ($homeserver,%validations);
 7244:     if ($dom =~ /^$match_domain$/) {
 7245:         $homeserver = &domain($dom,'primary');
 7246:     }
 7247:     unless ($homeserver eq 'no_host') {
 7248:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 7249:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 7250:             my @items = split(/&/,$response);
 7251:             foreach my $item (@items) {
 7252:                 my ($key,$value) = split('=',$item);
 7253:                 $validations{&unescape($key)} = &thaw_unescape($value);
 7254:             }
 7255:         }
 7256:     }
 7257:     return %validations; 
 7258: }
 7259: 
 7260: sub auto_courserequest_validation {
 7261:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
 7262:     my ($homeserver,$response);
 7263:     if ($dom =~ /^$match_domain$/) {
 7264:         $homeserver = &domain($dom,'primary');
 7265:     }
 7266:     unless ($homeserver eq 'no_host') {  
 7267:           
 7268:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 7269:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 7270:                                     ':'.&escape($instcode).':'.&escape($instseclist),
 7271:                                     $homeserver));
 7272:     }
 7273:     return $response;
 7274: }
 7275: 
 7276: sub auto_validate_class_sec {
 7277:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 7278:     my $homeserver = &homeserver($cnum,$cdom);
 7279:     my $ownerlist;
 7280:     if (ref($owners) eq 'ARRAY') {
 7281:         $ownerlist = join(',',@{$owners});
 7282:     } else {
 7283:         $ownerlist = $owners;
 7284:     }
 7285:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 7286:                         &escape($ownerlist).':'.$cdom,$homeserver);
 7287:     return $response;
 7288: }
 7289: 
 7290: # ------------------------------------------------------- Course Group routines
 7291: 
 7292: sub get_coursegroups {
 7293:     my ($cdom,$cnum,$group,$namespace) = @_;
 7294:     return(&dump($namespace,$cdom,$cnum,$group));
 7295: }
 7296: 
 7297: sub modify_coursegroup {
 7298:     my ($cdom,$cnum,$groupsettings) = @_;
 7299:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 7300: }
 7301: 
 7302: sub toggle_coursegroup_status {
 7303:     my ($cdom,$cnum,$group,$action) = @_;
 7304:     my ($from_namespace,$to_namespace);
 7305:     if ($action eq 'delete') {
 7306:         $from_namespace = 'coursegroups';
 7307:         $to_namespace = 'deleted_groups';
 7308:     } else {
 7309:         $from_namespace = 'deleted_groups';
 7310:         $to_namespace = 'coursegroups';
 7311:     }
 7312:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 7313:     if (my $tmp = &error(%curr_group)) {
 7314:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 7315:         return ('read error',$tmp);
 7316:     } else {
 7317:         my %savedsettings = %curr_group; 
 7318:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 7319:         my $deloutcome;
 7320:         if ($result eq 'ok') {
 7321:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 7322:         } else {
 7323:             return ('write error',$result);
 7324:         }
 7325:         if ($deloutcome eq 'ok') {
 7326:             return 'ok';
 7327:         } else {
 7328:             return ('delete error',$deloutcome);
 7329:         }
 7330:     }
 7331: }
 7332: 
 7333: sub modify_group_roles {
 7334:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 7335:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 7336:     my $role = 'gr/'.&escape($userprivs);
 7337:     my ($uname,$udom) = split(/:/,$user);
 7338:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 7339:     if ($result eq 'ok') {
 7340:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 7341:     }
 7342:     return $result;
 7343: }
 7344: 
 7345: sub modify_coursegroup_membership {
 7346:     my ($cdom,$cnum,$membership) = @_;
 7347:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 7348:     return $result;
 7349: }
 7350: 
 7351: sub get_active_groups {
 7352:     my ($udom,$uname,$cdom,$cnum) = @_;
 7353:     my $now = time;
 7354:     my %groups = ();
 7355:     foreach my $key (keys(%env)) {
 7356:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 7357:             my ($start,$end) = split(/\./,$env{$key});
 7358:             if (($end!=0) && ($end<$now)) { next; }
 7359:             if (($start!=0) && ($start>$now)) { next; }
 7360:             if ($1 eq $cdom && $2 eq $cnum) {
 7361:                 $groups{$3} = $env{$key} ;
 7362:             }
 7363:         }
 7364:     }
 7365:     return %groups;
 7366: }
 7367: 
 7368: sub get_group_membership {
 7369:     my ($cdom,$cnum,$group) = @_;
 7370:     return(&dump('groupmembership',$cdom,$cnum,$group));
 7371: }
 7372: 
 7373: sub get_users_groups {
 7374:     my ($udom,$uname,$courseid) = @_;
 7375:     my @usersgroups;
 7376:     my $cachetime=1800;
 7377: 
 7378:     my $hashid="$udom:$uname:$courseid";
 7379:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 7380:     if (defined($cached)) {
 7381:         @usersgroups = split(/:/,$grouplist);
 7382:     } else {  
 7383:         $grouplist = '';
 7384:         my $courseurl = &courseid_to_courseurl($courseid);
 7385:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 7386:         my $access_end = $env{'course.'.$courseid.
 7387:                               '.default_enrollment_end_date'};
 7388:         my $now = time;
 7389:         foreach my $key (keys(%roleshash)) {
 7390:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 7391:                 my $group = $1;
 7392:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 7393:                     my $start = $2;
 7394:                     my $end = $1;
 7395:                     if ($start == -1) { next; } # deleted from group
 7396:                     if (($start!=0) && ($start>$now)) { next; }
 7397:                     if (($end!=0) && ($end<$now)) {
 7398:                         if ($access_end && $access_end < $now) {
 7399:                             if ($access_end - $end < 86400) {
 7400:                                 push(@usersgroups,$group);
 7401:                             }
 7402:                         }
 7403:                         next;
 7404:                     }
 7405:                     push(@usersgroups,$group);
 7406:                 }
 7407:             }
 7408:         }
 7409:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 7410:         $grouplist = join(':',@usersgroups);
 7411:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 7412:     }
 7413:     return @usersgroups;
 7414: }
 7415: 
 7416: sub devalidate_getgroups_cache {
 7417:     my ($udom,$uname,$cdom,$cnum)=@_;
 7418:     my $courseid = $cdom.'_'.$cnum;
 7419: 
 7420:     my $hashid="$udom:$uname:$courseid";
 7421:     &devalidate_cache_new('getgroups',$hashid);
 7422: }
 7423: 
 7424: # ------------------------------------------------------------------ Plain Text
 7425: 
 7426: sub plaintext {
 7427:     my ($short,$type,$cid,$forcedefault) = @_;
 7428:     if ($short =~ m{^cr/}) {
 7429: 	return (split('/',$short))[-1];
 7430:     }
 7431:     if (!defined($cid)) {
 7432:         $cid = $env{'request.course.id'};
 7433:     }
 7434:     my %rolenames = (
 7435:                       Course    => 'std',
 7436:                       Community => 'alt1',
 7437:                     );
 7438:     if ($cid ne '') {
 7439:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 7440:             unless ($forcedefault) {
 7441:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 7442:                 &Apache::lonlocal::mt_escape(\$roletext);
 7443:                 return &Apache::lonlocal::mt($roletext);
 7444:             }
 7445:         }
 7446:     }
 7447:     if ((defined($type)) && (defined($rolenames{$type})) &&
 7448:         (defined($rolenames{$type})) && 
 7449:         (defined($prp{$short}{$rolenames{$type}}))) {
 7450:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 7451:     } elsif ($cid ne '') {
 7452:         my $crstype = $env{'course.'.$cid.'.type'};
 7453:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
 7454:             (defined($prp{$short}{$rolenames{$crstype}}))) {
 7455:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
 7456:         }
 7457:     }
 7458:     return &Apache::lonlocal::mt($prp{$short}{'std'});
 7459: }
 7460: 
 7461: # ----------------------------------------------------------------- Assign Role
 7462: 
 7463: sub assignrole {
 7464:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 7465:         $context)=@_;
 7466:     my $mrole;
 7467:     if ($role =~ /^cr\//) {
 7468:         my $cwosec=$url;
 7469:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 7470: 	unless (&allowed('ccr',$cwosec)) {
 7471:            my $refused = 1;
 7472:            if ($context eq 'requestcourses') {
 7473:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 7474:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
 7475:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
 7476:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 7477:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 7478:                            if ($crsenv{'internal.courseowner'} eq
 7479:                                $env{'user.name'}.':'.$env{'user.domain'}) {
 7480:                                $refused = '';
 7481:                            }
 7482:                        }
 7483:                    }
 7484:                }
 7485:            }
 7486:            if ($refused) {
 7487:                &logthis('Refused custom assignrole: '.
 7488:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
 7489:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
 7490:                return 'refused';
 7491:            }
 7492:         }
 7493:         $mrole='cr';
 7494:     } elsif ($role =~ /^gr\//) {
 7495:         my $cwogrp=$url;
 7496:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 7497:         unless (&allowed('mdg',$cwogrp)) {
 7498:             &logthis('Refused group assignrole: '.
 7499:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 7500:                     $env{'user.name'}.' at '.$env{'user.domain'});
 7501:             return 'refused';
 7502:         }
 7503:         $mrole='gr';
 7504:     } else {
 7505:         my $cwosec=$url;
 7506:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 7507:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 7508:             my $refused;
 7509:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 7510:                 if (!(&allowed('c'.$role,$url))) {
 7511:                     $refused = 1;
 7512:                 }
 7513:             } else {
 7514:                 $refused = 1;
 7515:             }
 7516:             if ($refused) {
 7517:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 7518:                 if (!$selfenroll && $context eq 'course') {
 7519:                     my %crsenv;
 7520:                     if ($role eq 'cc' || $role eq 'co') {
 7521:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 7522:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
 7523:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
 7524:                                 if ($crsenv{'internal.courseowner'} eq 
 7525:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 7526:                                     $refused = '';
 7527:                                 }
 7528:                             }
 7529:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
 7530:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
 7531:                                 if ($crsenv{'internal.courseowner'} eq 
 7532:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 7533:                                     $refused = '';
 7534:                                 }
 7535:                             }
 7536:                         }
 7537:                     }
 7538:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7539:                     $refused = '';
 7540:                 } elsif ($context eq 'requestcourses') {
 7541:                     my @possroles = ('st','ta','ep','in','cc','co');
 7542:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
 7543:                         my $wrongcc;
 7544:                         if ($cnum =~ /^$match_community$/) {
 7545:                             $wrongcc = 1 if ($role eq 'cc');
 7546:                         } else {
 7547:                             $wrongcc = 1 if ($role eq 'co');
 7548:                         }
 7549:                         unless ($wrongcc) {
 7550:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 7551:                             if ($crsenv{'internal.courseowner'} eq 
 7552:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
 7553:                                 $refused = '';
 7554:                             }
 7555:                         }
 7556:                     }
 7557:                 } elsif ($context eq 'requestauthor') {
 7558:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
 7559:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
 7560:                         if ($env{'environment.requestauthor'} eq 'automatic') {
 7561:                             $refused = '';
 7562:                         } else {
 7563:                             my %domdefaults = &get_domain_defaults($udom);
 7564:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
 7565:                                 my $checkbystatus;
 7566:                                 if ($env{'user.adv'}) { 
 7567:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
 7568:                                     if ($disposition eq 'automatic') {
 7569:                                         $refused = '';
 7570:                                     } elsif ($disposition eq '') {
 7571:                                         $checkbystatus = 1;
 7572:                                     } 
 7573:                                 } else {
 7574:                                     $checkbystatus = 1;
 7575:                                 }
 7576:                                 if ($checkbystatus) {
 7577:                                     if ($env{'environment.inststatus'}) {
 7578:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
 7579:                                         foreach my $type (@inststatuses) {
 7580:                                             if (($type ne '') &&
 7581:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
 7582:                                                 $refused = '';
 7583:                                             }
 7584:                                         }
 7585:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
 7586:                                         $refused = '';
 7587:                                     }
 7588:                                 }
 7589:                             }
 7590:                         }
 7591:                     }
 7592:                 }
 7593:                 if ($refused) {
 7594:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 7595:                              ' '.$role.' '.$end.' '.$start.' by '.
 7596: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 7597:                     return 'refused';
 7598:                 }
 7599:             }
 7600:         } elsif ($role eq 'au') {
 7601:             if ($url ne '/'.$udom.'/') {
 7602:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
 7603:                          ' to assign author role for '.$uname.':'.$udom.
 7604:                          ' in domain: '.$url.' refused (wrong domain).');
 7605:                 return 'refused';
 7606:             }
 7607:         }
 7608:         $mrole=$role;
 7609:     }
 7610:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 7611:                 "$udom:$uname:$url".'_'."$mrole=$role";
 7612:     if ($end) { $command.='_'.$end; }
 7613:     if ($start) {
 7614: 	if ($end) { 
 7615:            $command.='_'.$start; 
 7616:         } else {
 7617:            $command.='_0_'.$start;
 7618:         }
 7619:     }
 7620:     my $origstart = $start;
 7621:     my $origend = $end;
 7622:     my $delflag;
 7623: # actually delete
 7624:     if ($deleteflag) {
 7625: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 7626: # modify command to delete the role
 7627:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 7628:                 "$udom:$uname:$url".'_'."$mrole";
 7629: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 7630: # set start and finish to negative values for userrolelog
 7631:            $start=-1;
 7632:            $end=-1;
 7633:            $delflag = 1;
 7634:         }
 7635:     }
 7636: # send command
 7637:     my $answer=&reply($command,&homeserver($uname,$udom));
 7638: # log new user role if status is ok
 7639:     if ($answer eq 'ok') {
 7640: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 7641: # for course roles, perform group memberships changes triggered by role change.
 7642:         unless ($role =~ /^gr/) {
 7643:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 7644:                                              $origstart,$selfenroll,$context);
 7645:         }
 7646:         if (($role eq 'cc') || ($role eq 'in') ||
 7647:             ($role eq 'ep') || ($role eq 'ad') ||
 7648:             ($role eq 'ta') || ($role eq 'st') ||
 7649:             ($role=~/^cr/) || ($role eq 'gr') ||
 7650:             ($role eq 'co')) {
 7651:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 7652:                            $selfenroll,$context);
 7653:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
 7654:                  ($role eq 'au') || ($role eq 'dc')) {
 7655:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 7656:                            $context);
 7657:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
 7658:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 7659:                              $context); 
 7660:         }
 7661:         if ($role eq 'cc') {
 7662:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
 7663:         }
 7664:     }
 7665:     return $answer;
 7666: }
 7667: 
 7668: sub autoupdate_coowners {
 7669:     my ($url,$end,$start,$uname,$udom) = @_;
 7670:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
 7671:     if (($cdom ne '') && ($cnum ne '')) {
 7672:         my $now = time;
 7673:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
 7674:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
 7675:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
 7676:             my $instcode = $coursehash{'internal.coursecode'};
 7677:             if ($instcode ne '') {
 7678:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
 7679:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
 7680:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
 7681:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
 7682:                         if ($result eq 'valid') {
 7683:                             if ($coursehash{'internal.co-owners'}) {
 7684:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 7685:                                     push(@newcoowners,$coowner);
 7686:                                 }
 7687:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
 7688:                                     push(@newcoowners,$uname.':'.$udom);
 7689:                                 }
 7690:                                 @newcoowners = sort(@newcoowners);
 7691:                             } else {
 7692:                                 push(@newcoowners,$uname.':'.$udom);
 7693:                             }
 7694:                         } else {
 7695:                             if ($coursehash{'internal.co-owners'}) {
 7696:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 7697:                                     unless ($coowner eq $uname.':'.$udom) {
 7698:                                         push(@newcoowners,$coowner);
 7699:                                     }
 7700:                                 }
 7701:                                 unless (@newcoowners > 0) {
 7702:                                     $delcoowners = 1;
 7703:                                     $coowners = '';
 7704:                                 }
 7705:                             }
 7706:                         }
 7707:                         if (@newcoowners || $delcoowners) {
 7708:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
 7709:                                             $delcoowners,@newcoowners);
 7710:                         }
 7711:                     }
 7712:                 }
 7713:             }
 7714:         }
 7715:     }
 7716: }
 7717: 
 7718: sub store_coowners {
 7719:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
 7720:     my $cid = $cdom.'_'.$cnum;
 7721:     my ($coowners,$delresult,$putresult);
 7722:     if (@newcoowners) {
 7723:         $coowners = join(',',@newcoowners);
 7724:         my %coownershash = (
 7725:                             'internal.co-owners' => $coowners,
 7726:                            );
 7727:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
 7728:         if ($putresult eq 'ok') {
 7729:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
 7730:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
 7731:             }
 7732:         }
 7733:     }
 7734:     if ($delcoowners) {
 7735:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
 7736:         if ($delresult eq 'ok') {
 7737:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
 7738:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
 7739:             }
 7740:         }
 7741:     }
 7742:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
 7743:         my %crsinfo =
 7744:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 7745:         if (ref($crsinfo{$cid}) eq 'HASH') {
 7746:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
 7747:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
 7748:         }
 7749:     }
 7750: }
 7751: 
 7752: # -------------------------------------------------- Modify user authentication
 7753: # Overrides without validation
 7754: 
 7755: sub modifyuserauth {
 7756:     my ($udom,$uname,$umode,$upass)=@_;
 7757:     my $uhome=&homeserver($uname,$udom);
 7758:     unless (&allowed('mau',$udom)) { return 'refused'; }
 7759:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 7760:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 7761:              ' in domain '.$env{'request.role.domain'});  
 7762:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 7763: 		     &escape($upass),$uhome);
 7764:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 7765:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 7766:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 7767:     &log($udom,,$uname,$uhome,
 7768:         'Authentication changed by '.$env{'user.domain'}.', '.
 7769:                                      $env{'user.name'}.', '.$umode.
 7770:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 7771:     unless ($reply eq 'ok') {
 7772:         &logthis('Authentication mode error: '.$reply);
 7773: 	return 'error: '.$reply;
 7774:     }   
 7775:     return 'ok';
 7776: }
 7777: 
 7778: # --------------------------------------------------------------- Modify a user
 7779: 
 7780: sub modifyuser {
 7781:     my ($udom,    $uname, $uid,
 7782:         $umode,   $upass, $first,
 7783:         $middle,  $last,  $gene,
 7784:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
 7785:     $udom= &LONCAPA::clean_domain($udom);
 7786:     $uname=&LONCAPA::clean_username($uname);
 7787:     my $showcandelete = 'none';
 7788:     if (ref($candelete) eq 'ARRAY') {
 7789:         if (@{$candelete} > 0) {
 7790:             $showcandelete = join(', ',@{$candelete});
 7791:         }
 7792:     }
 7793:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 7794:              $umode.', '.$first.', '.$middle.', '.
 7795: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
 7796:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 7797:                                      ' desiredhome not specified'). 
 7798:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 7799:              ' in domain '.$env{'request.role.domain'});
 7800:     my $uhome=&homeserver($uname,$udom,'true');
 7801:     my $newuser;
 7802:     if ($uhome eq 'no_host') {
 7803:         $newuser = 1;
 7804:     }
 7805: # ----------------------------------------------------------------- Create User
 7806:     if (($uhome eq 'no_host') && 
 7807: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 7808:         my $unhome='';
 7809:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 7810:             $unhome = $desiredhome;
 7811: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 7812: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 7813:         } else { # load balancing routine for determining $unhome
 7814:             my $loadm=10000000;
 7815: 	    my %servers = &get_servers($udom,'library');
 7816: 	    foreach my $tryserver (keys(%servers)) {
 7817: 		my $answer=reply('load',$tryserver);
 7818: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 7819: 		    $loadm=$answer;
 7820: 		    $unhome=$tryserver;
 7821: 		}
 7822: 	    }
 7823:         }
 7824:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 7825: 	    return 'error: unable to find a home server for '.$uname.
 7826:                    ' in domain '.$udom;
 7827:         }
 7828:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 7829:                          &escape($upass),$unhome);
 7830: 	unless ($reply eq 'ok') {
 7831:             return 'error: '.$reply;
 7832:         }   
 7833:         $uhome=&homeserver($uname,$udom,'true');
 7834:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 7835: 	    return 'error: unable verify users home machine.';
 7836:         }
 7837:     }   # End of creation of new user
 7838: # ---------------------------------------------------------------------- Add ID
 7839:     if ($uid) {
 7840:        $uid=~tr/A-Z/a-z/;
 7841:        my %uidhash=&idrget($udom,$uname);
 7842:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 7843:          && (!$forceid)) {
 7844: 	  unless ($uid eq $uidhash{$uname}) {
 7845: 	      return 'error: user id "'.$uid.'" does not match '.
 7846:                   'current user id "'.$uidhash{$uname}.'".';
 7847:           }
 7848:        } else {
 7849: 	  &idput($udom,($uname => $uid));
 7850:        }
 7851:     }
 7852: # -------------------------------------------------------------- Add names, etc
 7853:     my @tmp=&get('environment',
 7854: 		   ['firstname','middlename','lastname','generation','id',
 7855:                     'permanentemail','inststatus'],
 7856: 		   $udom,$uname);
 7857:     my (%names,%oldnames);
 7858:     if ($tmp[0] =~ m/^error:.*/) { 
 7859:         %names=(); 
 7860:     } else {
 7861:         %names = @tmp;
 7862:         %oldnames = %names;
 7863:     }
 7864: #
 7865: # If name, email and/or uid are blank (e.g., because an uploaded file
 7866: # of users did not contain them), do not overwrite existing values
 7867: # unless field is in $candelete array ref.  
 7868: #
 7869: 
 7870:     my @fields = ('firstname','middlename','lastname','generation',
 7871:                   'permanentemail','id');
 7872:     my %newvalues;
 7873:     if (ref($candelete) eq 'ARRAY') {
 7874:         foreach my $field (@fields) {
 7875:             if (grep(/^\Q$field\E$/,@{$candelete})) {
 7876:                 if ($field eq 'firstname') {
 7877:                     $names{$field} = $first;
 7878:                 } elsif ($field eq 'middlename') {
 7879:                     $names{$field} = $middle;
 7880:                 } elsif ($field eq 'lastname') {
 7881:                     $names{$field} = $last;
 7882:                 } elsif ($field eq 'generation') { 
 7883:                     $names{$field} = $gene;
 7884:                 } elsif ($field eq 'permanentemail') {
 7885:                     $names{$field} = $email;
 7886:                 } elsif ($field eq 'id') {
 7887:                     $names{$field}  = $uid;
 7888:                 }
 7889:             }
 7890:         }
 7891:     }
 7892:     if ($first)  { $names{'firstname'}  = $first; }
 7893:     if (defined($middle)) { $names{'middlename'} = $middle; }
 7894:     if ($last)   { $names{'lastname'}   = $last; }
 7895:     if (defined($gene))   { $names{'generation'} = $gene; }
 7896:     if ($email) {
 7897:        $email=~s/[^\w\@\.\-\,]//gs;
 7898:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 7899:     }
 7900:     if ($uid) { $names{'id'}  = $uid; }
 7901:     if (defined($inststatus)) {
 7902:         $names{'inststatus'} = '';
 7903:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
 7904:         if (ref($usertypes) eq 'HASH') {
 7905:             my @okstatuses; 
 7906:             foreach my $item (split(/:/,$inststatus)) {
 7907:                 if (defined($usertypes->{$item})) {
 7908:                     push(@okstatuses,$item);  
 7909:                 }
 7910:             }
 7911:             if (@okstatuses) {
 7912:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
 7913:             }
 7914:         }
 7915:     }
 7916:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
 7917:                  $umode.', '.$first.', '.$middle.', '.
 7918:                  $last.', '.$gene.', '.$email.', '.$inststatus;
 7919:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 7920:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 7921:     } else {
 7922:         $logmsg .= ' during self creation';
 7923:     }
 7924:     my $changed;
 7925:     if ($newuser) {
 7926:         $changed = 1;
 7927:     } else {
 7928:         foreach my $field (@fields) {
 7929:             if ($names{$field} ne $oldnames{$field}) {
 7930:                 $changed = 1;
 7931:                 last;
 7932:             }
 7933:         }
 7934:     }
 7935:     unless ($changed) {
 7936:         $logmsg = 'No changes in user information needed for: '.$logmsg;
 7937:         &logthis($logmsg);
 7938:         return 'ok';
 7939:     }
 7940:     my $reply = &put('environment', \%names, $udom,$uname);
 7941:     if ($reply ne 'ok') { 
 7942:         return 'error: '.$reply;
 7943:     }
 7944:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
 7945:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
 7946:     }
 7947:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 7948:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 7949:     $logmsg = 'Success modifying user '.$logmsg;
 7950:     &logthis($logmsg);
 7951:     return 'ok';
 7952: }
 7953: 
 7954: # -------------------------------------------------------------- Modify student
 7955: 
 7956: sub modifystudent {
 7957:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 7958:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 7959:         $selfenroll,$context,$inststatus)=@_;
 7960:     if (!$cid) {
 7961: 	unless ($cid=$env{'request.course.id'}) {
 7962: 	    return 'not_in_class';
 7963: 	}
 7964:     }
 7965: # --------------------------------------------------------------- Make the user
 7966:     my $reply=&modifyuser
 7967: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 7968:          $desiredhome,$email,$inststatus);
 7969:     unless ($reply eq 'ok') { return $reply; }
 7970:     # This will cause &modify_student_enrollment to get the uid from the
 7971:     # students environment
 7972:     $uid = undef if (!$forceid);
 7973:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 7974: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
 7975:     return $reply;
 7976: }
 7977: 
 7978: sub modify_student_enrollment {
 7979:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
 7980:     my ($cdom,$cnum,$chome);
 7981:     if (!$cid) {
 7982: 	unless ($cid=$env{'request.course.id'}) {
 7983: 	    return 'not_in_class';
 7984: 	}
 7985: 	$cdom=$env{'course.'.$cid.'.domain'};
 7986: 	$cnum=$env{'course.'.$cid.'.num'};
 7987:     } else {
 7988: 	($cdom,$cnum)=split(/_/,$cid);
 7989:     }
 7990:     $chome=$env{'course.'.$cid.'.home'};
 7991:     if (!$chome) {
 7992: 	$chome=&homeserver($cnum,$cdom);
 7993:     }
 7994:     if (!$chome) { return 'unknown_course'; }
 7995:     # Make sure the user exists
 7996:     my $uhome=&homeserver($uname,$udom);
 7997:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 7998: 	return 'error: no such user';
 7999:     }
 8000:     # Get student data if we were not given enough information
 8001:     if (!defined($first)  || $first  eq '' || 
 8002:         !defined($last)   || $last   eq '' || 
 8003:         !defined($uid)    || $uid    eq '' || 
 8004:         !defined($middle) || $middle eq '' || 
 8005:         !defined($gene)   || $gene   eq '') {
 8006:         # They did not supply us with enough data to enroll the student, so
 8007:         # we need to pick up more information.
 8008:         my %tmp = &get('environment',
 8009:                        ['firstname','middlename','lastname', 'generation','id']
 8010:                        ,$udom,$uname);
 8011: 
 8012:         #foreach my $key (keys(%tmp)) {
 8013:         #    &logthis("key $key = ".$tmp{$key});
 8014:         #}
 8015:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 8016:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 8017:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 8018:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 8019:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 8020:     }
 8021:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 8022:     my $user = "$uname:$udom";
 8023:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
 8024:     my $reply=cput('classlist',
 8025: 		   {$user => 
 8026: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
 8027: 		   $cdom,$cnum);
 8028:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
 8029:         &devalidate_getsection_cache($udom,$uname,$cid);
 8030:     } else { 
 8031: 	return 'error: '.$reply;
 8032:     }
 8033:     # Add student role to user
 8034:     my $uurl='/'.$cid;
 8035:     $uurl=~s/\_/\//g;
 8036:     if ($usec) {
 8037: 	$uurl.='/'.$usec;
 8038:     }
 8039:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
 8040:                              $selfenroll,$context);
 8041:     if ($result ne 'ok') {
 8042:         if ($old_entry{$user} ne '') {
 8043:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
 8044:         } else {
 8045:             $reply = &del('classlist',[$user],$cdom,$cnum);
 8046:         }
 8047:     }
 8048:     return $result; 
 8049: }
 8050: 
 8051: sub format_name {
 8052:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 8053:     my $name;
 8054:     if ($first ne 'lastname') {
 8055: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 8056:     } else {
 8057: 	if ($lastname=~/\S/) {
 8058: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 8059: 	    $name=~s/\s+,/,/;
 8060: 	} else {
 8061: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 8062: 	}
 8063:     }
 8064:     $name=~s/^\s+//;
 8065:     $name=~s/\s+$//;
 8066:     $name=~s/\s+/ /g;
 8067:     return $name;
 8068: }
 8069: 
 8070: # ------------------------------------------------- Write to course preferences
 8071: 
 8072: sub writecoursepref {
 8073:     my ($courseid,%prefs)=@_;
 8074:     $courseid=~s/^\///;
 8075:     $courseid=~s/\_/\//g;
 8076:     my ($cdomain,$cnum)=split(/\//,$courseid);
 8077:     my $chome=homeserver($cnum,$cdomain);
 8078:     if (($chome eq '') || ($chome eq 'no_host')) { 
 8079: 	return 'error: no such course';
 8080:     }
 8081:     my $cstring='';
 8082:     foreach my $pref (keys(%prefs)) {
 8083: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 8084:     }
 8085:     $cstring=~s/\&$//;
 8086:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 8087: }
 8088: 
 8089: # ---------------------------------------------------------- Make/modify course
 8090: 
 8091: sub createcourse {
 8092:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 8093:         $course_owner,$crstype,$cnum,$context,$category)=@_;
 8094:     $url=&declutter($url);
 8095:     my $cid='';
 8096:     if ($context eq 'requestcourses') {
 8097:         my $can_create = 0;
 8098:         my ($ownername,$ownerdom) = split(':',$course_owner);
 8099:         if ($udom eq $ownerdom) {
 8100:             if (&usertools_access($ownername,$ownerdom,$category,undef,
 8101:                                   $context)) {
 8102:                 $can_create = 1;
 8103:             }
 8104:         } else {
 8105:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
 8106:                                            $category);
 8107:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
 8108:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
 8109:                 if (@curr > 0) {
 8110:                     my @options = qw(approval validate autolimit);
 8111:                     my $optregex = join('|',@options);
 8112:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
 8113:                         $can_create = 1;
 8114:                     }
 8115:                 }
 8116:             }
 8117:         }
 8118:         if ($can_create) {
 8119:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
 8120:                 unless (&allowed('ccc',$udom)) {
 8121:                     return 'refused'; 
 8122:                 }
 8123:             }
 8124:         } else {
 8125:             return 'refused';
 8126:         }
 8127:     } elsif (!&allowed('ccc',$udom)) {
 8128:         return 'refused';
 8129:     }
 8130: # --------------------------------------------------------------- Get Unique ID
 8131:     my $uname;
 8132:     if ($cnum =~ /^$match_courseid$/) {
 8133:         my $chome=&homeserver($cnum,$udom,'true');
 8134:         if (($chome eq '') || ($chome eq 'no_host')) {
 8135:             $uname = $cnum;
 8136:         } else {
 8137:             $uname = &generate_coursenum($udom,$crstype);
 8138:         }
 8139:     } else {
 8140:         $uname = &generate_coursenum($udom,$crstype);
 8141:     }
 8142:     return $uname if ($uname =~ /^error/);
 8143: # -------------------------------------------------- Check supplied server name
 8144:     if (!defined($course_server)) {
 8145:         if (defined(&domain($udom,'primary'))) {
 8146:             $course_server = &domain($udom,'primary');
 8147:         } else {
 8148:             $course_server = $env{'user.home'}; 
 8149:         }
 8150:     }
 8151:     my %host_servers =
 8152:         &Apache::lonnet::get_servers($udom,'library');
 8153:     unless ($host_servers{$course_server}) {
 8154:         return 'error: invalid home server for course: '.$course_server;
 8155:     }
 8156: # ------------------------------------------------------------- Make the course
 8157:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 8158:                       $course_server);
 8159:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 8160:     my $uhome=&homeserver($uname,$udom,'true');
 8161:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 8162: 	return 'error: no such course';
 8163:     }
 8164: # ----------------------------------------------------------------- Course made
 8165: # log existence
 8166:     my $now = time;
 8167:     my $newcourse = {
 8168:                     $udom.'_'.$uname => {
 8169:                                      description => $description,
 8170:                                      inst_code   => $inst_code,
 8171:                                      owner       => $course_owner,
 8172:                                      type        => $crstype,
 8173:                                      creator     => $env{'user.name'}.':'.
 8174:                                                     $env{'user.domain'},
 8175:                                      created     => $now,
 8176:                                      context     => $context,
 8177:                                                 },
 8178:                     };
 8179:     &courseidput($udom,$newcourse,$uhome,'notime');
 8180: # set toplevel url
 8181:     my $topurl=$url;
 8182:     unless ($nonstandard) {
 8183: # ------------------------------------------ For standard courses, make top url
 8184:         my $mapurl=&clutter($url);
 8185:         if ($mapurl eq '/res/') { $mapurl=''; }
 8186:         $env{'form.initmap'}=(<<ENDINITMAP);
 8187: <map>
 8188: <resource id="1" type="start"></resource>
 8189: <resource id="2" src="$mapurl"></resource>
 8190: <resource id="3" type="finish"></resource>
 8191: <link index="1" from="1" to="2"></link>
 8192: <link index="2" from="2" to="3"></link>
 8193: </map>
 8194: ENDINITMAP
 8195:         $topurl=&declutter(
 8196:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 8197:                           );
 8198:     }
 8199: # ----------------------------------------------------------- Write preferences
 8200:     &writecoursepref($udom.'_'.$uname,
 8201:                      ('description'              => $description,
 8202:                       'url'                      => $topurl,
 8203:                       'internal.creator'         => $env{'user.name'}.':'.
 8204:                                                     $env{'user.domain'},
 8205:                       'internal.created'         => $now,
 8206:                       'internal.creationcontext' => $context)
 8207:                     );
 8208:     return '/'.$udom.'/'.$uname;
 8209: }
 8210: 
 8211: # ------------------------------------------------------------------- Create ID
 8212: sub generate_coursenum {
 8213:     my ($udom,$crstype) = @_;
 8214:     my $domdesc = &domain($udom);
 8215:     return 'error: invalid domain' if ($domdesc eq '');
 8216:     my $first;
 8217:     if ($crstype eq 'Community') {
 8218:         $first = '0';
 8219:     } else {
 8220:         $first = int(1+rand(9)); 
 8221:     } 
 8222:     my $uname=$first.
 8223:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 8224:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
 8225:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 8226: # ----------------------------------------------- Make sure that does not exist
 8227:     my $uhome=&homeserver($uname,$udom,'true');
 8228:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
 8229:         if ($crstype eq 'Community') {
 8230:             $first = '0';
 8231:         } else {
 8232:             $first = int(1+rand(9));
 8233:         }
 8234:         $uname=$first.
 8235:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 8236:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
 8237:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 8238:         $uhome=&homeserver($uname,$udom,'true');
 8239:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
 8240:             return 'error: unable to generate unique course-ID';
 8241:         }
 8242:     }
 8243:     return $uname;
 8244: }
 8245: 
 8246: sub is_course {
 8247:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
 8248:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
 8249: 
 8250:     return unless $cdom and $cnum;
 8251: 
 8252:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
 8253:         '.');
 8254: 
 8255:     return unless exists($courses{$cdom.'_'.$cnum});
 8256:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
 8257: }
 8258: 
 8259: sub store_userdata {
 8260:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
 8261:     my $result;
 8262:     if ($datakey ne '') {
 8263:         if (ref($storehash) eq 'HASH') {
 8264:             if ($udom eq '' || $uname eq '') {
 8265:                 $udom = $env{'user.domain'};
 8266:                 $uname = $env{'user.name'};
 8267:             }
 8268:             my $uhome=&homeserver($uname,$udom);
 8269:             if (($uhome eq '') || ($uhome eq 'no_host')) {
 8270:                 $result = 'error: no_host';
 8271:             } else {
 8272:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
 8273:                 $storehash->{'host'} = $perlvar{'lonHostID'};
 8274: 
 8275:                 my $namevalue='';
 8276:                 foreach my $key (keys(%{$storehash})) {
 8277:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 8278:                 }
 8279:                 $namevalue=~s/\&$//;
 8280:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
 8281:                                   $namevalue,$uhome);
 8282:             }
 8283:         } else {
 8284:             $result = 'error: data to store was not a hash reference'; 
 8285:         }
 8286:     } else {
 8287:         $result= 'error: invalid requestkey'; 
 8288:     }
 8289:     return $result;
 8290: }
 8291: 
 8292: # ---------------------------------------------------------- Assign Custom Role
 8293: 
 8294: sub assigncustomrole {
 8295:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
 8296:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 8297:                        $end,$start,$deleteflag,$selfenroll,$context);
 8298: }
 8299: 
 8300: # ----------------------------------------------------------------- Revoke Role
 8301: 
 8302: sub revokerole {
 8303:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
 8304:     my $now=time;
 8305:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
 8306: }
 8307: 
 8308: # ---------------------------------------------------------- Revoke Custom Role
 8309: 
 8310: sub revokecustomrole {
 8311:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
 8312:     my $now=time;
 8313:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 8314:            $deleteflag,$selfenroll,$context);
 8315: }
 8316: 
 8317: # ------------------------------------------------------------ Disk usage
 8318: sub diskusage {
 8319:     my ($udom,$uname,$directorypath,$getpropath)=@_;
 8320:     $directorypath =~ s/\/$//;
 8321:     my $listing=&reply('du2:'.&escape($directorypath).':'
 8322:                        .&escape($getpropath).':'.&escape($uname).':'
 8323:                        .&escape($udom),homeserver($uname,$udom));
 8324:     if ($listing eq 'unknown_cmd') {
 8325:         if ($getpropath) {
 8326:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
 8327:         }
 8328:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
 8329:     }
 8330:     return $listing;
 8331: }
 8332: 
 8333: sub is_locked {
 8334:     my ($file_name, $domain, $user, $which) = @_;
 8335:     my @check;
 8336:     my $is_locked;
 8337:     push (@check,$file_name);
 8338:     my %locked = &get('file_permissions',\@check,
 8339: 		      $env{'user.domain'},$env{'user.name'});
 8340:     my ($tmp)=keys(%locked);
 8341:     if ($tmp=~/^error:/) { undef(%locked); }
 8342:     
 8343:     if (ref($locked{$file_name}) eq 'ARRAY') {
 8344:         $is_locked = 'false';
 8345:         foreach my $entry (@{$locked{$file_name}}) {
 8346:            if (ref($entry) eq 'ARRAY') {
 8347:                $is_locked = 'true';
 8348:                if (ref($which) eq 'ARRAY') {
 8349:                    push(@{$which},$entry);
 8350:                } else {
 8351:                    last;
 8352:                }
 8353:            }
 8354:        }
 8355:     } else {
 8356:         $is_locked = 'false';
 8357:     }
 8358:     return $is_locked;
 8359: }
 8360: 
 8361: sub declutter_portfile {
 8362:     my ($file) = @_;
 8363:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 8364:     return $file;
 8365: }
 8366: 
 8367: # ------------------------------------------------------------- Mark as Read Only
 8368: 
 8369: sub mark_as_readonly {
 8370:     my ($domain,$user,$files,$what) = @_;
 8371:     my %current_permissions = &dump('file_permissions',$domain,$user);
 8372:     my ($tmp)=keys(%current_permissions);
 8373:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 8374:     foreach my $file (@{$files}) {
 8375: 	$file = &declutter_portfile($file);
 8376:         push(@{$current_permissions{$file}},$what);
 8377:     }
 8378:     &put('file_permissions',\%current_permissions,$domain,$user);
 8379:     return;
 8380: }
 8381: 
 8382: # ------------------------------------------------------------Save Selected Files
 8383: 
 8384: sub save_selected_files {
 8385:     my ($user, $path, @files) = @_;
 8386:     my $filename = $user."savedfiles";
 8387:     my @other_files = &files_not_in_path($user, $path);
 8388:     open (OUT, '>'.$tmpdir.$filename);
 8389:     foreach my $file (@files) {
 8390:         print (OUT $env{'form.currentpath'}.$file."\n");
 8391:     }
 8392:     foreach my $file (@other_files) {
 8393:         print (OUT $file."\n");
 8394:     }
 8395:     close (OUT);
 8396:     return 'ok';
 8397: }
 8398: 
 8399: sub clear_selected_files {
 8400:     my ($user) = @_;
 8401:     my $filename = $user."savedfiles";
 8402:     open (OUT, '>'.LONCAPA::tempdir().$filename);
 8403:     print (OUT undef);
 8404:     close (OUT);
 8405:     return ("ok");    
 8406: }
 8407: 
 8408: sub files_in_path {
 8409:     my ($user, $path) = @_;
 8410:     my $filename = $user."savedfiles";
 8411:     my %return_files;
 8412:     open (IN, '<'.LONCAPA::tempdir().$filename);
 8413:     while (my $line_in = <IN>) {
 8414:         chomp ($line_in);
 8415:         my @paths_and_file = split (m!/!, $line_in);
 8416:         my $file_part = pop (@paths_and_file);
 8417:         my $path_part = join ('/', @paths_and_file);
 8418:         $path_part.='/';
 8419:         my $path_and_file = $path_part.$file_part;
 8420:         if ($path_part eq $path) {
 8421:             $return_files{$file_part}= 'selected';
 8422:         }
 8423:     }
 8424:     close (IN);
 8425:     return (\%return_files);
 8426: }
 8427: 
 8428: # called in portfolio select mode, to show files selected NOT in current directory
 8429: sub files_not_in_path {
 8430:     my ($user, $path) = @_;
 8431:     my $filename = $user."savedfiles";
 8432:     my @return_files;
 8433:     my $path_part;
 8434:     open(IN, '<'.LONCAPA::.$filename);
 8435:     while (my $line = <IN>) {
 8436:         #ok, I know it's clunky, but I want it to work
 8437:         my @paths_and_file = split(m|/|, $line);
 8438:         my $file_part = pop(@paths_and_file);
 8439:         chomp($file_part);
 8440:         my $path_part = join('/', @paths_and_file);
 8441:         $path_part .= '/';
 8442:         my $path_and_file = $path_part.$file_part;
 8443:         if ($path_part ne $path) {
 8444:             push(@return_files, ($path_and_file));
 8445:         }
 8446:     }
 8447:     close(OUT);
 8448:     return (@return_files);
 8449: }
 8450: 
 8451: #----------------------------------------------Get portfolio file permissions
 8452: 
 8453: sub get_portfile_permissions {
 8454:     my ($domain,$user) = @_;
 8455:     my %current_permissions = &dump('file_permissions',$domain,$user);
 8456:     my ($tmp)=keys(%current_permissions);
 8457:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 8458:     return \%current_permissions;
 8459: }
 8460: 
 8461: #---------------------------------------------Get portfolio file access controls
 8462: 
 8463: sub get_access_controls {
 8464:     my ($current_permissions,$group,$file) = @_;
 8465:     my %access;
 8466:     my $real_file = $file;
 8467:     $file =~ s/\.meta$//;
 8468:     if (defined($file)) {
 8469:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 8470:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 8471:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 8472:             }
 8473:         }
 8474:     } else {
 8475:         foreach my $key (keys(%{$current_permissions})) {
 8476:             if ($key =~ /\0accesscontrol$/) {
 8477:                 if (defined($group)) {
 8478:                     if ($key !~ m-^\Q$group\E/-) {
 8479:                         next;
 8480:                     }
 8481:                 }
 8482:                 my ($fullpath) = split(/\0/,$key);
 8483:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 8484:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 8485:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 8486:                     }
 8487:                 }
 8488:             }
 8489:         }
 8490:     }
 8491:     return %access;
 8492: }
 8493: 
 8494: sub modify_access_controls {
 8495:     my ($file_name,$changes,$domain,$user)=@_;
 8496:     my ($outcome,$deloutcome);
 8497:     my %store_permissions;
 8498:     my %new_values;
 8499:     my %new_control;
 8500:     my %translation;
 8501:     my @deletions = ();
 8502:     my $now = time;
 8503:     if (exists($$changes{'activate'})) {
 8504:         if (ref($$changes{'activate'}) eq 'HASH') {
 8505:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 8506:             my $numnew = scalar(@newitems);
 8507:             for (my $i=0; $i<$numnew; $i++) {
 8508:                 my $newkey = $newitems[$i];
 8509:                 my $newid = &Apache::loncommon::get_cgi_id();
 8510:                 if ($newkey =~ /^\d+:/) { 
 8511:                     $newkey =~ s/^(\d+)/$newid/;
 8512:                     $translation{$1} = $newid;
 8513:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 8514:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 8515:                     $translation{$1} = $newid;
 8516:                 }
 8517:                 $new_values{$file_name."\0".$newkey} = 
 8518:                                           $$changes{'activate'}{$newitems[$i]};
 8519:                 $new_control{$newkey} = $now;
 8520:             }
 8521:         }
 8522:     }
 8523:     my %todelete;
 8524:     my %changed_items;
 8525:     foreach my $action ('delete','update') {
 8526:         if (exists($$changes{$action})) {
 8527:             if (ref($$changes{$action}) eq 'HASH') {
 8528:                 foreach my $key (keys(%{$$changes{$action}})) {
 8529:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 8530:                     if ($action eq 'delete') { 
 8531:                         $todelete{$itemnum} = 1;
 8532:                     } else {
 8533:                         $changed_items{$itemnum} = $key;
 8534:                     }
 8535:                 }
 8536:             }
 8537:         }
 8538:     }
 8539:     # get lock on access controls for file.
 8540:     my $lockhash = {
 8541:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 8542:                                                        ':'.$env{'user.domain'},
 8543:                    }; 
 8544:     my $tries = 0;
 8545:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 8546:    
 8547:     while (($gotlock ne 'ok') && $tries <3) {
 8548:         $tries ++;
 8549:         sleep 1;
 8550:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 8551:     }
 8552:     if ($gotlock eq 'ok') {
 8553:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 8554:         my ($tmp)=keys(%curr_permissions);
 8555:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 8556:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 8557:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 8558:             if (ref($curr_controls) eq 'HASH') {
 8559:                 foreach my $control_item (keys(%{$curr_controls})) {
 8560:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 8561:                     if (defined($todelete{$itemnum})) {
 8562:                         push(@deletions,$file_name."\0".$control_item);
 8563:                     } else {
 8564:                         if (defined($changed_items{$itemnum})) {
 8565:                             $new_control{$changed_items{$itemnum}} = $now;
 8566:                             push(@deletions,$file_name."\0".$control_item);
 8567:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 8568:                         } else {
 8569:                             $new_control{$control_item} = $$curr_controls{$control_item};
 8570:                         }
 8571:                     }
 8572:                 }
 8573:             }
 8574:         }
 8575:         my ($group);
 8576:         if (&is_course($domain,$user)) {
 8577:             ($group,my $file) = split(/\//,$file_name,2);
 8578:         }
 8579:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 8580:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 8581:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 8582:         #  remove lock
 8583:         my @del_lock = ($file_name."\0".'locked_access_records');
 8584:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 8585:         my $sqlresult =
 8586:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
 8587:                                     $group);
 8588:     } else {
 8589:         $outcome = "error: could not obtain lockfile\n";  
 8590:     }
 8591:     return ($outcome,$deloutcome,\%new_values,\%translation);
 8592: }
 8593: 
 8594: sub make_public_indefinitely {
 8595:     my ($requrl) = @_;
 8596:     my $now = time;
 8597:     my $action = 'activate';
 8598:     my $aclnum = 0;
 8599:     if (&is_portfolio_url($requrl)) {
 8600:         my (undef,$udom,$unum,$file_name,$group) =
 8601:             &parse_portfolio_url($requrl);
 8602:         my $current_perms = &get_portfile_permissions($udom,$unum);
 8603:         my %access_controls = &get_access_controls($current_perms,
 8604:                                                    $group,$file_name);
 8605:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 8606:             my ($num,$scope,$end,$start) = 
 8607:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 8608:             if ($scope eq 'public') {
 8609:                 if ($start <= $now && $end == 0) {
 8610:                     $action = 'none';
 8611:                 } else {
 8612:                     $action = 'update';
 8613:                     $aclnum = $num;
 8614:                 }
 8615:                 last;
 8616:             }
 8617:         }
 8618:         if ($action eq 'none') {
 8619:              return 'ok';
 8620:         } else {
 8621:             my %changes;
 8622:             my $newend = 0;
 8623:             my $newstart = $now;
 8624:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 8625:             $changes{$action}{$newkey} = {
 8626:                 type => 'public',
 8627:                 time => {
 8628:                     start => $newstart,
 8629:                     end   => $newend,
 8630:                 },
 8631:             };
 8632:             my ($outcome,$deloutcome,$new_values,$translation) =
 8633:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 8634:             return $outcome;
 8635:         }
 8636:     } else {
 8637:         return 'invalid';
 8638:     }
 8639: }
 8640: 
 8641: #------------------------------------------------------Get Marked as Read Only
 8642: 
 8643: sub get_marked_as_readonly {
 8644:     my ($domain,$user,$what,$group) = @_;
 8645:     my $current_permissions = &get_portfile_permissions($domain,$user);
 8646:     my @readonly_files;
 8647:     my $cmp1=$what;
 8648:     if (ref($what)) { $cmp1=join('',@{$what}) };
 8649:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 8650:         if (defined($group)) {
 8651:             if ($file_name !~ m-^\Q$group\E/-) {
 8652:                 next;
 8653:             }
 8654:         }
 8655:         if (ref($value) eq "ARRAY"){
 8656:             foreach my $stored_what (@{$value}) {
 8657:                 my $cmp2=$stored_what;
 8658:                 if (ref($stored_what) eq 'ARRAY') {
 8659:                     $cmp2=join('',@{$stored_what});
 8660:                 }
 8661:                 if ($cmp1 eq $cmp2) {
 8662:                     push(@readonly_files, $file_name);
 8663:                     last;
 8664:                 } elsif (!defined($what)) {
 8665:                     push(@readonly_files, $file_name);
 8666:                     last;
 8667:                 }
 8668:             }
 8669:         }
 8670:     }
 8671:     return @readonly_files;
 8672: }
 8673: #-----------------------------------------------------------Get Marked as Read Only Hash
 8674: 
 8675: sub get_marked_as_readonly_hash {
 8676:     my ($current_permissions,$group,$what) = @_;
 8677:     my %readonly_files;
 8678:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 8679:         if (defined($group)) {
 8680:             if ($file_name !~ m-^\Q$group\E/-) {
 8681:                 next;
 8682:             }
 8683:         }
 8684:         if (ref($value) eq "ARRAY"){
 8685:             foreach my $stored_what (@{$value}) {
 8686:                 if (ref($stored_what) eq 'ARRAY') {
 8687:                     foreach my $lock_descriptor(@{$stored_what}) {
 8688:                         if ($lock_descriptor eq 'graded') {
 8689:                             $readonly_files{$file_name} = 'graded';
 8690:                         } elsif ($lock_descriptor eq 'handback') {
 8691:                             $readonly_files{$file_name} = 'handback';
 8692:                         } else {
 8693:                             if (!exists($readonly_files{$file_name})) {
 8694:                                 $readonly_files{$file_name} = 'locked';
 8695:                             }
 8696:                         }
 8697:                     }
 8698:                 } 
 8699:             }
 8700:         } 
 8701:     }
 8702:     return %readonly_files;
 8703: }
 8704: # ------------------------------------------------------------ Unmark as Read Only
 8705: 
 8706: sub unmark_as_readonly {
 8707:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 8708:     # for portfolio submissions, $what contains [$symb,$crsid] 
 8709:     my ($domain,$user,$what,$file_name,$group) = @_;
 8710:     $file_name = &declutter_portfile($file_name);
 8711:     my $symb_crs = $what;
 8712:     if (ref($what)) { $symb_crs=join('',@$what); }
 8713:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 8714:     my ($tmp)=keys(%current_permissions);
 8715:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 8716:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 8717:     foreach my $file (@readonly_files) {
 8718: 	my $clean_file = &declutter_portfile($file);
 8719: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 8720: 	my $current_locks = $current_permissions{$file};
 8721:         my @new_locks;
 8722:         my @del_keys;
 8723:         if (ref($current_locks) eq "ARRAY"){
 8724:             foreach my $locker (@{$current_locks}) {
 8725:                 my $compare=$locker;
 8726:                 if (ref($locker) eq 'ARRAY') {
 8727:                     $compare=join('',@{$locker});
 8728:                     if ($compare ne $symb_crs) {
 8729:                         push(@new_locks, $locker);
 8730:                     }
 8731:                 }
 8732:             }
 8733:             if (scalar(@new_locks) > 0) {
 8734:                 $current_permissions{$file} = \@new_locks;
 8735:             } else {
 8736:                 push(@del_keys, $file);
 8737:                 &del('file_permissions',\@del_keys, $domain, $user);
 8738:                 delete($current_permissions{$file});
 8739:             }
 8740:         }
 8741:     }
 8742:     &put('file_permissions',\%current_permissions,$domain,$user);
 8743:     return;
 8744: }
 8745: 
 8746: # ------------------------------------------------------------ Directory lister
 8747: 
 8748: sub dirlist {
 8749:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
 8750:     $uri=~s/^\///;
 8751:     $uri=~s/\/$//;
 8752:     my ($udom, $uname);
 8753:     if ($getuserdir) {
 8754:         $udom = $userdomain;
 8755:         $uname = $username;
 8756:     } else {
 8757:         (undef,$udom,$uname)=split(/\//,$uri);
 8758:         if(defined($userdomain)) {
 8759:             $udom = $userdomain;
 8760:         }
 8761:         if(defined($username)) {
 8762:             $uname = $username;
 8763:         }
 8764:     }
 8765:     my ($dirRoot,$listing,@listing_results);
 8766: 
 8767:     $dirRoot = $perlvar{'lonDocRoot'};
 8768:     if (defined($getpropath)) {
 8769:         $dirRoot = &propath($udom,$uname);
 8770:         $dirRoot =~ s/\/$//;
 8771:     } elsif (defined($getuserdir)) {
 8772:         my $subdir=$uname.'__';
 8773:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 8774:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
 8775:                    ."/$udom/$subdir/$uname";
 8776:     } elsif (defined($alternateRoot)) {
 8777:         $dirRoot = $alternateRoot;
 8778:     }
 8779: 
 8780:     if($udom) {
 8781:         if($uname) {
 8782:             my $uhome = &homeserver($uname,$udom);
 8783:             if ($uhome eq 'no_host') {
 8784:                 return ([],'no_host');
 8785:             }
 8786:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
 8787:                               .$getuserdir.':'.&escape($dirRoot)
 8788:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
 8789:             if ($listing eq 'unknown_cmd') {
 8790:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
 8791:             } else {
 8792:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 8793:             }
 8794:             if ($listing eq 'unknown_cmd') {
 8795:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
 8796:                 @listing_results = split(/:/,$listing);
 8797:             } else {
 8798:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 8799:             }
 8800:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
 8801:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
 8802:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 8803:                 return ([],$listing);
 8804:             } else {
 8805:                 return (\@listing_results);
 8806:             }
 8807:         } elsif(!$alternateRoot) {
 8808:             my (%allusers,%listerror);
 8809: 	    my %servers = &get_servers($udom,'library');
 8810:  	    foreach my $tryserver (keys(%servers)) {
 8811:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
 8812:                                   &escape($udom),$tryserver);
 8813:                 if ($listing eq 'unknown_cmd') {
 8814: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 8815: 				      $udom, $tryserver);
 8816:                 } else {
 8817:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
 8818:                 }
 8819: 		if ($listing eq 'unknown_cmd') {
 8820: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 8821: 				      $udom, $tryserver);
 8822: 		    @listing_results = split(/:/,$listing);
 8823: 		} else {
 8824: 		    @listing_results =
 8825: 			map { &unescape($_); } split(/:/,$listing);
 8826: 		}
 8827:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
 8828:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
 8829:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 8830:                     $listerror{$tryserver} = $listing;
 8831:                 } else {
 8832: 		    foreach my $line (@listing_results) {
 8833: 			my ($entry) = split(/&/,$line,2);
 8834: 			$allusers{$entry} = 1;
 8835: 		    }
 8836: 		}
 8837:             }
 8838:             my @alluserslist=();
 8839:             foreach my $user (sort(keys(%allusers))) {
 8840:                 push(@alluserslist,$user.'&user');
 8841:             }
 8842:             return (\@alluserslist);
 8843:         } else {
 8844:             return ([],'missing username');
 8845:         }
 8846:     } elsif(!defined($getpropath)) {
 8847:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
 8848:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
 8849:         return (\@all_domains);
 8850:     } else {
 8851:         return ([],'missing domain');
 8852:     }
 8853: }
 8854: 
 8855: # --------------------------------------------- GetFileTimestamp
 8856: # This function utilizes dirlist and returns the date stamp for
 8857: # when it was last modified.  It will also return an error of -1
 8858: # if an error occurs
 8859: 
 8860: sub GetFileTimestamp {
 8861:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
 8862:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 8863:     $studentName   = &LONCAPA::clean_username($studentName);
 8864:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
 8865:                                     undef,$getuserdir);
 8866:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 8867:         return -1;
 8868:     }
 8869:     if (ref($fileref) eq 'ARRAY') {
 8870:         my @stats = split('&',$fileref->[0]);
 8871:         # @stats contains first the filename, then the stat output
 8872:         return $stats[10]; # so this is 10 instead of 9.
 8873:     } else {
 8874:         return -1;
 8875:     }
 8876: }
 8877: 
 8878: sub stat_file {
 8879:     my ($uri) = @_;
 8880:     $uri = &clutter_with_no_wrapper($uri);
 8881: 
 8882:     my ($udom,$uname,$file);
 8883:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 8884: 	($udom,$uname,$file) =
 8885: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 8886: 	$file = 'userfiles/'.$file;
 8887:     }
 8888:     if ($uri =~ m-^/res/-) {
 8889: 	($udom,$uname) = 
 8890: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 8891: 	$file = $uri;
 8892:     }
 8893: 
 8894:     if (!$udom || !$uname || !$file) {
 8895: 	# unable to handle the uri
 8896: 	return ();
 8897:     }
 8898:     my $getpropath;
 8899:     if ($file =~ /^userfiles\//) {
 8900:         $getpropath = 1;
 8901:     }
 8902:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
 8903:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 8904:         return ();
 8905:     } else {
 8906:         if (ref($listref) eq 'ARRAY') {
 8907:             my @stats = split('&',$listref->[0]);
 8908: 	    shift(@stats); #filename is first
 8909: 	    return @stats;
 8910:         }
 8911:     }
 8912:     return ();
 8913: }
 8914: 
 8915: # -------------------------------------------------------- Value of a Condition
 8916: 
 8917: # gets the value of a specific preevaluated condition
 8918: #    stored in the string  $env{user.state.<cid>}
 8919: # or looks up a condition reference in the bighash and if if hasn't
 8920: # already been evaluated recurses into docondval to get the value of
 8921: # the condition, then memoizing it to 
 8922: #   $env{user.state.<cid>.<condition>}
 8923: sub directcondval {
 8924:     my $number=shift;
 8925:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 8926: 	&Apache::lonuserstate::evalstate();
 8927:     }
 8928:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 8929: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 8930:     } elsif ($number =~ /^_/) {
 8931: 	my $sub_condition;
 8932: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8933: 		&GDBM_READER(),0640)) {
 8934: 	    $sub_condition=$bighash{'conditions'.$number};
 8935: 	    untie(%bighash);
 8936: 	}
 8937: 	my $value = &docondval($sub_condition);
 8938: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
 8939: 	return $value;
 8940:     }
 8941:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 8942:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 8943:     } else {
 8944:        return 2;
 8945:     }
 8946: }
 8947: 
 8948: # get the collection of conditions for this resource
 8949: sub condval {
 8950:     my $condidx=shift;
 8951:     my $allpathcond='';
 8952:     foreach my $cond (split(/\|/,$condidx)) {
 8953: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 8954: 	    $allpathcond.=
 8955: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 8956: 	}
 8957:     }
 8958:     $allpathcond=~s/\|$//;
 8959:     return &docondval($allpathcond);
 8960: }
 8961: 
 8962: #evaluates an expression of conditions
 8963: sub docondval {
 8964:     my ($allpathcond) = @_;
 8965:     my $result=0;
 8966:     if ($env{'request.course.id'}
 8967: 	&& defined($allpathcond)) {
 8968: 	my $operand='|';
 8969: 	my @stack;
 8970: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 8971: 	    if ($chunk eq '(') {
 8972: 		push @stack,($operand,$result);
 8973: 	    } elsif ($chunk eq ')') {
 8974: 		my $before=pop @stack;
 8975: 		if (pop @stack eq '&') {
 8976: 		    $result=$result>$before?$before:$result;
 8977: 		} else {
 8978: 		    $result=$result>$before?$result:$before;
 8979: 		}
 8980: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 8981: 		$operand=$chunk;
 8982: 	    } else {
 8983: 		my $new=directcondval($chunk);
 8984: 		if ($operand eq '&') {
 8985: 		    $result=$result>$new?$new:$result;
 8986: 		} else {
 8987: 		    $result=$result>$new?$result:$new;
 8988: 		}
 8989: 	    }
 8990: 	}
 8991:     }
 8992:     return $result;
 8993: }
 8994: 
 8995: # ---------------------------------------------------- Devalidate courseresdata
 8996: 
 8997: sub devalidatecourseresdata {
 8998:     my ($coursenum,$coursedomain)=@_;
 8999:     my $hashid=$coursenum.':'.$coursedomain;
 9000:     &devalidate_cache_new('courseres',$hashid);
 9001: }
 9002: 
 9003: 
 9004: # --------------------------------------------------- Course Resourcedata Query
 9005: #
 9006: #  Parameters:
 9007: #      $coursenum    - Number of the course.
 9008: #      $coursedomain - Domain at which the course was created.
 9009: #  Returns:
 9010: #     A hash of the course parameters along (I think) with timestamps
 9011: #     and version info.
 9012: 
 9013: sub get_courseresdata {
 9014:     my ($coursenum,$coursedomain)=@_;
 9015:     my $coursehom=&homeserver($coursenum,$coursedomain);
 9016:     my $hashid=$coursenum.':'.$coursedomain;
 9017:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 9018:     my %dumpreply;
 9019:     unless (defined($cached)) {
 9020: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 9021: 	$result=\%dumpreply;
 9022: 	my ($tmp) = keys(%dumpreply);
 9023: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 9024: 	    &do_cache_new('courseres',$hashid,$result,600);
 9025: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 9026: 	    return $tmp;
 9027: 	} elsif ($tmp =~ /^(error)/) {
 9028: 	    $result=undef;
 9029: 	    &do_cache_new('courseres',$hashid,$result,600);
 9030: 	}
 9031:     }
 9032:     return $result;
 9033: }
 9034: 
 9035: sub devalidateuserresdata {
 9036:     my ($uname,$udom)=@_;
 9037:     my $hashid="$udom:$uname";
 9038:     &devalidate_cache_new('userres',$hashid);
 9039: }
 9040: 
 9041: sub get_userresdata {
 9042:     my ($uname,$udom)=@_;
 9043:     #most student don\'t have any data set, check if there is some data
 9044:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 9045: 
 9046:     my $hashid="$udom:$uname";
 9047:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 9048:     if (!defined($cached)) {
 9049: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 9050: 	$result=\%resourcedata;
 9051: 	&do_cache_new('userres',$hashid,$result,600);
 9052:     }
 9053:     my ($tmp)=keys(%$result);
 9054:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 9055: 	return $result;
 9056:     }
 9057:     #error 2 occurs when the .db doesn't exist
 9058:     if ($tmp!~/error: 2 /) {
 9059: 	&logthis("<font color=\"blue\">WARNING:".
 9060: 		 " Trying to get resource data for ".
 9061: 		 $uname." at ".$udom.": ".
 9062: 		 $tmp."</font>");
 9063:     } elsif ($tmp=~/error: 2 /) {
 9064: 	#&EXT_cache_set($udom,$uname);
 9065: 	&do_cache_new('userres',$hashid,undef,600);
 9066: 	undef($tmp); # not really an error so don't send it back
 9067:     }
 9068:     return $tmp;
 9069: }
 9070: #----------------------------------------------- resdata - return resource data
 9071: #  Purpose:
 9072: #    Return resource data for either users or for a course.
 9073: #  Parameters:
 9074: #     $name      - Course/user name.
 9075: #     $domain    - Name of the domain the user/course is registered on.
 9076: #     $type      - Type of thing $name is (must be 'course' or 'user'
 9077: #     @which     - Array of names of resources desired.
 9078: #  Returns:
 9079: #     The value of the first reasource in @which that is found in the
 9080: #     resource hash.
 9081: #  Exceptional Conditions:
 9082: #     If the $type passed in is not valid (not the string 'course' or 
 9083: #     'user', an undefined  reference is returned.
 9084: #     If none of the resources are found, an undef is returned
 9085: sub resdata {
 9086:     my ($name,$domain,$type,@which)=@_;
 9087:     my $result;
 9088:     if ($type eq 'course') {
 9089: 	$result=&get_courseresdata($name,$domain);
 9090:     } elsif ($type eq 'user') {
 9091: 	$result=&get_userresdata($name,$domain);
 9092:     }
 9093:     if (!ref($result)) { return $result; }    
 9094:     foreach my $item (@which) {
 9095: 	if (defined($result->{$item->[0]})) {
 9096: 	    return [$result->{$item->[0]},$item->[1]];
 9097: 	}
 9098:     }
 9099:     return undef;
 9100: }
 9101: 
 9102: #
 9103: # EXT resource caching routines
 9104: #
 9105: 
 9106: sub clear_EXT_cache_status {
 9107:     &delenv('cache.EXT.');
 9108: }
 9109: 
 9110: sub EXT_cache_status {
 9111:     my ($target_domain,$target_user) = @_;
 9112:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 9113:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 9114:         # We know already the user has no data
 9115:         return 1;
 9116:     } else {
 9117:         return 0;
 9118:     }
 9119: }
 9120: 
 9121: sub EXT_cache_set {
 9122:     my ($target_domain,$target_user) = @_;
 9123:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 9124:     #&appenv({$cachename => time});
 9125: }
 9126: 
 9127: # --------------------------------------------------------- Value of a Variable
 9128: sub EXT {
 9129: 
 9130:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
 9131:     unless ($varname) { return ''; }
 9132:     #get real user name/domain, courseid and symb
 9133:     my $courseid;
 9134:     my $publicuser;
 9135:     if ($symbparm) {
 9136: 	$symbparm=&get_symb_from_alias($symbparm);
 9137:     }
 9138:     if (!($uname && $udom)) {
 9139:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 9140:       if (!$symbparm) {	$symbparm=$cursymb; }
 9141:     } else {
 9142: 	$courseid=$env{'request.course.id'};
 9143:     }
 9144:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 9145:     my $rest;
 9146:     if (defined($therest[0])) {
 9147:        $rest=join('.',@therest);
 9148:     } else {
 9149:        $rest='';
 9150:     }
 9151: 
 9152:     my $qualifierrest=$qualifier;
 9153:     if ($rest) { $qualifierrest.='.'.$rest; }
 9154:     my $spacequalifierrest=$space;
 9155:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 9156:     if ($realm eq 'user') {
 9157: # --------------------------------------------------------------- user.resource
 9158: 	if ($space eq 'resource') {
 9159: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 9160: 		  || defined($Apache::lonhomework::parsing_a_task))
 9161: 		 &&
 9162: 		 ($symbparm eq &symbread()) ) {	
 9163: 		# if we are in the middle of processing the resource the
 9164: 		# get the value we are planning on committing
 9165:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 9166:                     return $Apache::lonhomework::results{$qualifierrest};
 9167:                 } else {
 9168:                     return $Apache::lonhomework::history{$qualifierrest};
 9169:                 }
 9170: 	    } else {
 9171: 		my %restored;
 9172: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 9173: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 9174: 		} else {
 9175: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 9176: 		}
 9177: 		return $restored{$qualifierrest};
 9178: 	    }
 9179: # ----------------------------------------------------------------- user.access
 9180:         } elsif ($space eq 'access') {
 9181: 	    # FIXME - not supporting calls for a specific user
 9182:             return &allowed($qualifier,$rest);
 9183: # ------------------------------------------ user.preferences, user.environment
 9184:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 9185: 	    if (($uname eq $env{'user.name'}) &&
 9186: 		($udom eq $env{'user.domain'})) {
 9187: 		return $env{join('.',('environment',$qualifierrest))};
 9188: 	    } else {
 9189: 		my %returnhash;
 9190: 		if (!$publicuser) {
 9191: 		    %returnhash=&userenvironment($udom,$uname,
 9192: 						 $qualifierrest);
 9193: 		}
 9194: 		return $returnhash{$qualifierrest};
 9195: 	    }
 9196: # ----------------------------------------------------------------- user.course
 9197:         } elsif ($space eq 'course') {
 9198: 	    # FIXME - not supporting calls for a specific user
 9199:             return $env{join('.',('request.course',$qualifier))};
 9200: # ------------------------------------------------------------------- user.role
 9201:         } elsif ($space eq 'role') {
 9202: 	    # FIXME - not supporting calls for a specific user
 9203:             my ($role,$where)=split(/\./,$env{'request.role'});
 9204:             if ($qualifier eq 'value') {
 9205: 		return $role;
 9206:             } elsif ($qualifier eq 'extent') {
 9207:                 return $where;
 9208:             }
 9209: # ----------------------------------------------------------------- user.domain
 9210:         } elsif ($space eq 'domain') {
 9211:             return $udom;
 9212: # ------------------------------------------------------------------- user.name
 9213:         } elsif ($space eq 'name') {
 9214:             return $uname;
 9215: # ---------------------------------------------------- Any other user namespace
 9216:         } else {
 9217: 	    my %reply;
 9218: 	    if (!$publicuser) {
 9219: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 9220: 	    }
 9221: 	    return $reply{$qualifierrest};
 9222:         }
 9223:     } elsif ($realm eq 'query') {
 9224: # ---------------------------------------------- pull stuff out of query string
 9225:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 9226: 						[$spacequalifierrest]);
 9227: 	return $env{'form.'.$spacequalifierrest}; 
 9228:    } elsif ($realm eq 'request') {
 9229: # ------------------------------------------------------------- request.browser
 9230:         if ($space eq 'browser') {
 9231:             return $env{'browser.'.$qualifier};
 9232: # ------------------------------------------------------------ request.filename
 9233:         } else {
 9234:             return $env{'request.'.$spacequalifierrest};
 9235:         }
 9236:     } elsif ($realm eq 'course') {
 9237: # ---------------------------------------------------------- course.description
 9238:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 9239:     } elsif ($realm eq 'resource') {
 9240: 
 9241: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 9242: 	    if (!$symbparm) { $symbparm=&symbread(); }
 9243: 	}
 9244: 
 9245: 	if ($space eq 'title') {
 9246: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 9247: 	    return &gettitle($symbparm);
 9248: 	}
 9249: 	
 9250: 	if ($space eq 'map') {
 9251: 	    my ($map) = &decode_symb($symbparm);
 9252: 	    return &symbread($map);
 9253: 	}
 9254: 	if ($space eq 'filename') {
 9255: 	    if ($symbparm) {
 9256: 		return &clutter((&decode_symb($symbparm))[2]);
 9257: 	    }
 9258: 	    return &hreflocation('',$env{'request.filename'});
 9259: 	}
 9260: 
 9261: 	my ($section, $group, @groups);
 9262: 	my ($courselevelm,$courselevel);
 9263: 	if ($symbparm && defined($courseid) && 
 9264: 	    $courseid eq $env{'request.course.id'}) {
 9265: 
 9266: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 9267: 
 9268: # ----------------------------------------------------- Cascading lookup scheme
 9269: 	    my $symbp=$symbparm;
 9270: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 9271: 
 9272: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 9273: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 9274: 
 9275: 	    if (($env{'user.name'} eq $uname) &&
 9276: 		($env{'user.domain'} eq $udom)) {
 9277: 		$section=$env{'request.course.sec'};
 9278:                 @groups = split(/:/,$env{'request.course.groups'});  
 9279:                 @groups=&sort_course_groups($courseid,@groups); 
 9280: 	    } else {
 9281: 		if (! defined($usection)) {
 9282: 		    $section=&getsection($udom,$uname,$courseid);
 9283: 		} else {
 9284: 		    $section = $usection;
 9285: 		}
 9286:                 @groups = &get_users_groups($udom,$uname,$courseid);
 9287: 	    }
 9288: 
 9289: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 9290: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 9291: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 9292: 
 9293: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 9294: 	    my $courselevelr=$courseid.'.'.$symbparm;
 9295: 	    $courselevelm=$courseid.'.'.$mapparm;
 9296: 
 9297: # ----------------------------------------------------------- first, check user
 9298: 
 9299: 	    my $userreply=&resdata($uname,$udom,'user',
 9300: 				       ([$courselevelr,'resource'],
 9301: 					[$courselevelm,'map'     ],
 9302: 					[$courselevel, 'course'  ]));
 9303: 	    if (defined($userreply)) { return &get_reply($userreply); }
 9304: 
 9305: # ------------------------------------------------ second, check some of course
 9306:             my $coursereply;
 9307:             if (@groups > 0) {
 9308:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 9309:                                        $mapparm,$spacequalifierrest);
 9310:                 if (defined($coursereply)) { return &get_reply($coursereply); }
 9311:             }
 9312: 
 9313: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 9314: 				  $env{'course.'.$courseid.'.domain'},
 9315: 				  'course',
 9316: 				  ([$seclevelr,   'resource'],
 9317: 				   [$seclevelm,   'map'     ],
 9318: 				   [$seclevel,    'course'  ],
 9319: 				   [$courselevelr,'resource']));
 9320: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 9321: 
 9322: # ------------------------------------------------------ third, check map parms
 9323: 	    my %parmhash=();
 9324: 	    my $thisparm='';
 9325: 	    if (tie(%parmhash,'GDBM_File',
 9326: 		    $env{'request.course.fn'}.'_parms.db',
 9327: 		    &GDBM_READER(),0640)) {
 9328: 		$thisparm=$parmhash{$symbparm};
 9329: 		untie(%parmhash);
 9330: 	    }
 9331: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
 9332: 	}
 9333: # ------------------------------------------ fourth, look in resource metadata
 9334: 
 9335: 	$spacequalifierrest=~s/\./\_/;
 9336: 	my $filename;
 9337: 	if (!$symbparm) { $symbparm=&symbread(); }
 9338: 	if ($symbparm) {
 9339: 	    $filename=(&decode_symb($symbparm))[2];
 9340: 	} else {
 9341: 	    $filename=$env{'request.filename'};
 9342: 	}
 9343: 	my $metadata=&metadata($filename,$spacequalifierrest);
 9344: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 9345: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 9346: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 9347: 
 9348: # ---------------------------------------------- fourth, look in rest of course
 9349: 	if ($symbparm && defined($courseid) && 
 9350: 	    $courseid eq $env{'request.course.id'}) {
 9351: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 9352: 				     $env{'course.'.$courseid.'.domain'},
 9353: 				     'course',
 9354: 				     ([$courselevelm,'map'   ],
 9355: 				      [$courselevel, 'course']));
 9356: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 9357: 	}
 9358: # ------------------------------------------------------------------ Cascade up
 9359: 	unless ($space eq '0') {
 9360: 	    my @parts=split(/_/,$space);
 9361: 	    my $id=pop(@parts);
 9362: 	    my $part=join('_',@parts);
 9363: 	    if ($part eq '') { $part='0'; }
 9364: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 9365: 				 $symbparm,$udom,$uname,$section,1);
 9366: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
 9367: 	}
 9368: 	if ($recurse) { return undef; }
 9369: 	my $pack_def=&packages_tab_default($filename,$varname);
 9370: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
 9371: # ---------------------------------------------------- Any other user namespace
 9372:     } elsif ($realm eq 'environment') {
 9373: # ----------------------------------------------------------------- environment
 9374: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 9375: 	    return $env{'environment.'.$spacequalifierrest};
 9376: 	} else {
 9377: 	    if ($uname eq 'anonymous' && $udom eq '') {
 9378: 		return '';
 9379: 	    }
 9380: 	    my %returnhash=&userenvironment($udom,$uname,
 9381: 					    $spacequalifierrest);
 9382: 	    return $returnhash{$spacequalifierrest};
 9383: 	}
 9384:     } elsif ($realm eq 'system') {
 9385: # ----------------------------------------------------------------- system.time
 9386: 	if ($space eq 'time') {
 9387: 	    return time;
 9388:         }
 9389:     } elsif ($realm eq 'server') {
 9390: # ----------------------------------------------------------------- system.time
 9391: 	if ($space eq 'name') {
 9392: 	    return $ENV{'SERVER_NAME'};
 9393:         }
 9394:     }
 9395:     return '';
 9396: }
 9397: 
 9398: sub get_reply {
 9399:     my ($reply_value) = @_;
 9400:     if (ref($reply_value) eq 'ARRAY') {
 9401:         if (wantarray) {
 9402: 	    return @$reply_value;
 9403:         }
 9404:         return $reply_value->[0];
 9405:     } else {
 9406:         return $reply_value;
 9407:     }
 9408: }
 9409: 
 9410: sub check_group_parms {
 9411:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
 9412:     my @groupitems = ();
 9413:     my $resultitem;
 9414:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
 9415:     foreach my $group (@{$groups}) {
 9416:         foreach my $level (@levels) {
 9417:              my $item = $courseid.'.['.$group.'].'.$level->[0];
 9418:              push(@groupitems,[$item,$level->[1]]);
 9419:         }
 9420:     }
 9421:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
 9422:                             $env{'course.'.$courseid.'.domain'},
 9423:                                      'course',@groupitems);
 9424:     return $coursereply;
 9425: }
 9426: 
 9427: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
 9428:     my ($courseid,@groups) = @_;
 9429:     @groups = sort(@groups);
 9430:     return @groups;
 9431: }
 9432: 
 9433: sub packages_tab_default {
 9434:     my ($uri,$varname)=@_;
 9435:     my (undef,$part,$name)=split(/\./,$varname);
 9436: 
 9437:     my (@extension,@specifics,$do_default);
 9438:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
 9439: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 9440: 	if ($pack_type eq 'default') {
 9441: 	    $do_default=1;
 9442: 	} elsif ($pack_type eq 'extension') {
 9443: 	    push(@extension,[$package,$pack_type,$pack_part]);
 9444: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
 9445: 	    # only look at packages defaults for packages that this id is
 9446: 	    push(@specifics,[$package,$pack_type,$pack_part]);
 9447: 	}
 9448:     }
 9449:     # first look for a package that matches the requested part id
 9450:     foreach my $package (@specifics) {
 9451: 	my (undef,$pack_type,$pack_part)=@{$package};
 9452: 	next if ($pack_part ne $part);
 9453: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 9454: 	    return $packagetab{"$pack_type&$name&default"};
 9455: 	}
 9456:     }
 9457:     # look for any possible matching non extension_ package
 9458:     foreach my $package (@specifics) {
 9459: 	my (undef,$pack_type,$pack_part)=@{$package};
 9460: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 9461: 	    return $packagetab{"$pack_type&$name&default"};
 9462: 	}
 9463: 	if ($pack_type eq 'part') { $pack_part='0'; }
 9464: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
 9465: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
 9466: 	}
 9467:     }
 9468:     # look for any posible extension_ match
 9469:     foreach my $package (@extension) {
 9470: 	my ($package,$pack_type)=@{$package};
 9471: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 9472: 	    return $packagetab{"$pack_type&$name&default"};
 9473: 	}
 9474: 	if (defined($packagetab{$package."&$name&default"})) {
 9475: 	    return $packagetab{$package."&$name&default"};
 9476: 	}
 9477:     }
 9478:     # look for a global default setting
 9479:     if ($do_default && defined($packagetab{"default&$name&default"})) {
 9480: 	return $packagetab{"default&$name&default"};
 9481:     }
 9482:     return undef;
 9483: }
 9484: 
 9485: sub add_prefix_and_part {
 9486:     my ($prefix,$part)=@_;
 9487:     my $keyroot;
 9488:     if (defined($prefix) && $prefix !~ /^__/) {
 9489: 	# prefix that has a part already
 9490: 	$keyroot=$prefix;
 9491:     } elsif (defined($prefix)) {
 9492: 	# prefix that is missing a part
 9493: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 9494:     } else {
 9495: 	# no prefix at all
 9496: 	if (defined($part)) { $keyroot='_'.$part; }
 9497:     }
 9498:     return $keyroot;
 9499: }
 9500: 
 9501: # ---------------------------------------------------------------- Get metadata
 9502: 
 9503: my %metaentry;
 9504: my %importedpartids;
 9505: sub metadata {
 9506:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 9507:     $uri=&declutter($uri);
 9508:     # if it is a non metadata possible uri return quickly
 9509:     if (($uri eq '') || 
 9510: 	(($uri =~ m|^/*adm/|) && 
 9511: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
 9512:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
 9513: 	return undef;
 9514:     }
 9515:     if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) 
 9516: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
 9517: 	return undef;
 9518:     }
 9519:     my $filename=$uri;
 9520:     $uri=~s/\.meta$//;
 9521: #
 9522: # Is the metadata already cached?
 9523: # Look at timestamp of caching
 9524: # Everything is cached by the main uri, libraries are never directly cached
 9525: #
 9526:     if (!defined($liburi)) {
 9527: 	my ($result,$cached)=&is_cached_new('meta',$uri);
 9528: 	if (defined($cached)) { return $result->{':'.$what}; }
 9529:     }
 9530:     {
 9531: # Imported parts would go here
 9532:         my %importedids=();
 9533:         my @origfileimportpartids=();
 9534:         my $importedparts=0;
 9535: #
 9536: # Is this a recursive call for a library?
 9537: #
 9538: #	if (! exists($metacache{$uri})) {
 9539: #	    $metacache{$uri}={};
 9540: #	}
 9541: 	my $cachetime = 60*60;
 9542:         if ($liburi) {
 9543: 	    $liburi=&declutter($liburi);
 9544:             $filename=$liburi;
 9545:         } else {
 9546: 	    &devalidate_cache_new('meta',$uri);
 9547: 	    undef(%metaentry);
 9548: 	}
 9549:         my %metathesekeys=();
 9550:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 9551: 	my $metastring;
 9552: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
 9553: 	    my $which = &hreflocation('','/'.($liburi || $uri));
 9554: 	    $metastring = 
 9555: 		&Apache::lonnet::ssi_body($which,
 9556: 					  ('grade_target' => 'meta'));
 9557: 	    $cachetime = 1; # only want this cached in the child not long term
 9558: 	} elsif (($uri !~ m -^(editupload)/-) && 
 9559:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
 9560: 	    my $file=&filelocation('',&clutter($filename));
 9561: 	    #push(@{$metaentry{$uri.'.file'}},$file);
 9562: 	    $metastring=&getfile($file);
 9563: 	}
 9564:         my $parser=HTML::LCParser->new(\$metastring);
 9565:         my $token;
 9566:         undef %metathesekeys;
 9567:         while ($token=$parser->get_token) {
 9568: 	    if ($token->[0] eq 'S') {
 9569: 		if (defined($token->[2]->{'package'})) {
 9570: #
 9571: # This is a package - get package info
 9572: #
 9573: 		    my $package=$token->[2]->{'package'};
 9574: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 9575: 		    if (defined($token->[2]->{'id'})) { 
 9576: 			$keyroot.='_'.$token->[2]->{'id'}; 
 9577: 		    }
 9578: 		    if ($metaentry{':packages'}) {
 9579: 			$metaentry{':packages'}.=','.$package.$keyroot;
 9580: 		    } else {
 9581: 			$metaentry{':packages'}=$package.$keyroot;
 9582: 		    }
 9583: 		    foreach my $pack_entry (keys(%packagetab)) {
 9584: 			my $part=$keyroot;
 9585: 			$part=~s/^\_//;
 9586: 			if ($pack_entry=~/^\Q$package\E\&/ || 
 9587: 			    $pack_entry=~/^\Q$package\E_0\&/) {
 9588: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
 9589: 			    # ignore package.tab specified default values
 9590:                             # here &package_tab_default() will fetch those
 9591: 			    if ($subp eq 'default') { next; }
 9592: 			    my $value=$packagetab{$pack_entry};
 9593: 			    my $unikey;
 9594: 			    if ($pack =~ /_0$/) {
 9595: 				$unikey='parameter_0_'.$name;
 9596: 				$part=0;
 9597: 			    } else {
 9598: 				$unikey='parameter'.$keyroot.'_'.$name;
 9599: 			    }
 9600: 			    if ($subp eq 'display') {
 9601: 				$value.=' [Part: '.$part.']';
 9602: 			    }
 9603: 			    $metaentry{':'.$unikey.'.part'}=$part;
 9604: 			    $metathesekeys{$unikey}=1;
 9605: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 9606: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
 9607: 			    }
 9608: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
 9609: 				$metaentry{':'.$unikey}=
 9610: 				    $metaentry{':'.$unikey.'.default'};
 9611: 			    }
 9612: 			}
 9613: 		    }
 9614: 		} else {
 9615: #
 9616: # This is not a package - some other kind of start tag
 9617: #
 9618: 		    my $entry=$token->[1];
 9619: 		    my $unikey='';
 9620: 
 9621: 		    if ($entry eq 'import') {
 9622: #
 9623: # Importing a library here
 9624: #
 9625:                         my $location=$parser->get_text('/import');
 9626:                         my $dir=$filename;
 9627:                         $dir=~s|[^/]*$||;
 9628:                         $location=&filelocation($dir,$location);
 9629:                        
 9630:                         my $importmode=$token->[2]->{'importmode'};
 9631:                         if ($importmode eq 'problem') {
 9632: # Import as problem/response
 9633:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 9634:                         } elsif ($importmode eq 'part') {
 9635: # Import as part(s)
 9636:                            $importedparts=1;
 9637: # We need to get the original file and the imported file to get the part order correct
 9638: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
 9639: # Load and inspect original file
 9640:                            if ($#origfileimportpartids<0) {
 9641:                               undef(%importedpartids);
 9642:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
 9643:                               my $origfile=&getfile($origfilelocation);
 9644:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
 9645:                            }
 9646: 
 9647: # Load and inspect imported file
 9648:                            my $impfile=&getfile($location);
 9649:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
 9650:                            if ($#impfilepartids>=0) {
 9651: # This problem had parts
 9652:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
 9653:                            } else {
 9654: # Importing by turning a single problem into a problem part
 9655: # It gets the import-tags ID as part-ID
 9656:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
 9657:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
 9658:                            }
 9659:                         } else {
 9660: # Normal import
 9661:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 9662:                            if (defined($token->[2]->{'id'})) {
 9663:                               $unikey.='_'.$token->[2]->{'id'};
 9664:                            }
 9665:                         }
 9666: 
 9667: 			if ($depthcount<20) {
 9668: 			    my $metadata = 
 9669: 				&metadata($uri,'keys', $location,$unikey,
 9670: 					  $depthcount+1);
 9671: 			    foreach my $meta (split(',',$metadata)) {
 9672: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
 9673: 				$metathesekeys{$meta}=1;
 9674: 			    }
 9675: 			
 9676:                         }
 9677: 		    } else {
 9678: #
 9679: # Not importing, some other kind of non-package, non-library start tag
 9680: # 
 9681:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
 9682:                         if (defined($token->[2]->{'id'})) {
 9683:                             $unikey.='_'.$token->[2]->{'id'};
 9684:                         }
 9685: 			if (defined($token->[2]->{'name'})) { 
 9686: 			    $unikey.='_'.$token->[2]->{'name'}; 
 9687: 			}
 9688: 			$metathesekeys{$unikey}=1;
 9689: 			foreach my $param (@{$token->[3]}) {
 9690: 			    $metaentry{':'.$unikey.'.'.$param} =
 9691: 				$token->[2]->{$param};
 9692: 			}
 9693: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
 9694: 			my $default=$metaentry{':'.$unikey.'.default'};
 9695: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
 9696: 		 # only ws inside the tag, and not in default, so use default
 9697: 		 # as value
 9698: 			    $metaentry{':'.$unikey}=$default;
 9699: 			} elsif ( $internaltext =~ /\S/ ) {
 9700: 		  # something interesting inside the tag
 9701: 			    $metaentry{':'.$unikey}=$internaltext;
 9702: 			} else {
 9703: 		  # no interesting values, don't set a default
 9704: 			}
 9705: # end of not-a-package not-a-library import
 9706: 		    }
 9707: # end of not-a-package start tag
 9708: 		}
 9709: # the next is the end of "start tag"
 9710: 	    }
 9711: 	}
 9712: 	my ($extension) = ($uri =~ /\.(\w+)$/);
 9713: 	$extension = lc($extension);
 9714: 	if ($extension eq 'htm') { $extension='html'; }
 9715: 
 9716: 	foreach my $key (keys(%packagetab)) {
 9717: 	    #no specific packages #how's our extension
 9718: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
 9719: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
 9720: 					 \%metathesekeys);
 9721: 	}
 9722: 
 9723: 	if (!exists($metaentry{':packages'})
 9724: 	    || $packagetab{"import_defaults&extension_$extension"}) {
 9725: 	    foreach my $key (keys(%packagetab)) {
 9726: 		#no specific packages well let's get default then
 9727: 		if ($key!~/^default&/) { next; }
 9728: 		&metadata_create_package_def($uri,$key,'default',
 9729: 					     \%metathesekeys);
 9730: 	    }
 9731: 	}
 9732: # are there custom rights to evaluate
 9733: 	if ($metaentry{':copyright'} eq 'custom') {
 9734: 
 9735:     #
 9736:     # Importing a rights file here
 9737:     #
 9738: 	    unless ($depthcount) {
 9739: 		my $location=$metaentry{':customdistributionfile'};
 9740: 		my $dir=$filename;
 9741: 		$dir=~s|[^/]*$||;
 9742: 		$location=&filelocation($dir,$location);
 9743: 		my $rights_metadata =
 9744: 		    &metadata($uri,'keys',$location,'_rights',
 9745: 			      $depthcount+1);
 9746: 		foreach my $rights (split(',',$rights_metadata)) {
 9747: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
 9748: 		    $metathesekeys{$rights}=1;
 9749: 		}
 9750: 	    }
 9751: 	}
 9752: 	# uniqifiy package listing
 9753: 	my %seen;
 9754: 	my @uniq_packages =
 9755: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
 9756: 	$metaentry{':packages'} = join(',',@uniq_packages);
 9757: 
 9758:         if ($importedparts) {
 9759: # We had imported parts and need to rebuild partorder
 9760:            $metaentry{':partorder'}='';
 9761:            $metathesekeys{'partorder'}=1;
 9762:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
 9763:                if ($origfileimportpartids[$index] eq 'part') {
 9764: # original part, part of the problem
 9765:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
 9766:                } else {
 9767: # we have imported parts at this position
 9768:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
 9769:                }
 9770:            }
 9771:            $metaentry{':partorder'}=~s/^\,//;
 9772:         }
 9773: 
 9774: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
 9775: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
 9776: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
 9777: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
 9778: # this is the end of "was not already recently cached
 9779:     }
 9780:     return $metaentry{':'.$what};
 9781: }
 9782: 
 9783: sub metadata_create_package_def {
 9784:     my ($uri,$key,$package,$metathesekeys)=@_;
 9785:     my ($pack,$name,$subp)=split(/\&/,$key);
 9786:     if ($subp eq 'default') { next; }
 9787:     
 9788:     if (defined($metaentry{':packages'})) {
 9789: 	$metaentry{':packages'}.=','.$package;
 9790:     } else {
 9791: 	$metaentry{':packages'}=$package;
 9792:     }
 9793:     my $value=$packagetab{$key};
 9794:     my $unikey;
 9795:     $unikey='parameter_0_'.$name;
 9796:     $metaentry{':'.$unikey.'.part'}=0;
 9797:     $$metathesekeys{$unikey}=1;
 9798:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 9799: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
 9800:     }
 9801:     if (defined($metaentry{':'.$unikey.'.default'})) {
 9802: 	$metaentry{':'.$unikey}=
 9803: 	    $metaentry{':'.$unikey.'.default'};
 9804:     }
 9805: }
 9806: 
 9807: sub metadata_generate_part0 {
 9808:     my ($metadata,$metacache,$uri) = @_;
 9809:     my %allnames;
 9810:     foreach my $metakey (keys(%$metadata)) {
 9811: 	if ($metakey=~/^parameter\_(.*)/) {
 9812: 	  my $part=$$metacache{':'.$metakey.'.part'};
 9813: 	  my $name=$$metacache{':'.$metakey.'.name'};
 9814: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
 9815: 	    $allnames{$name}=$part;
 9816: 	  }
 9817: 	}
 9818:     }
 9819:     foreach my $name (keys(%allnames)) {
 9820:       $$metadata{"parameter_0_$name"}=1;
 9821:       my $key=":parameter_0_$name";
 9822:       $$metacache{"$key.part"}='0';
 9823:       $$metacache{"$key.name"}=$name;
 9824:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
 9825: 					   $allnames{$name}.'_'.$name.
 9826: 					   '.type'};
 9827:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
 9828: 			     '.display'};
 9829:       my $expr='[Part: '.$allnames{$name}.']';
 9830:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
 9831:       $$metacache{"$key.display"}=$olddis;
 9832:     }
 9833: }
 9834: 
 9835: # ------------------------------------------------------ Devalidate title cache
 9836: 
 9837: sub devalidate_title_cache {
 9838:     my ($url)=@_;
 9839:     if (!$env{'request.course.id'}) { return; }
 9840:     my $symb=&symbread($url);
 9841:     if (!$symb) { return; }
 9842:     my $key=$env{'request.course.id'}."\0".$symb;
 9843:     &devalidate_cache_new('title',$key);
 9844: }
 9845: 
 9846: # ------------------------------------------------- Get the title of a course
 9847: 
 9848: sub current_course_title {
 9849:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
 9850: }
 9851: # ------------------------------------------------- Get the title of a resource
 9852: 
 9853: sub gettitle {
 9854:     my $urlsymb=shift;
 9855:     my $symb=&symbread($urlsymb);
 9856:     if ($symb) {
 9857: 	my $key=$env{'request.course.id'}."\0".$symb;
 9858: 	my ($result,$cached)=&is_cached_new('title',$key);
 9859: 	if (defined($cached)) { 
 9860: 	    return $result;
 9861: 	}
 9862: 	my ($map,$resid,$url)=&decode_symb($symb);
 9863: 	my $title='';
 9864: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
 9865: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
 9866: 	} else {
 9867: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9868: 		    &GDBM_READER(),0640)) {
 9869: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
 9870: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
 9871: 		untie(%bighash);
 9872: 	    }
 9873: 	}
 9874: 	$title=~s/\&colon\;/\:/gs;
 9875: 	if ($title) {
 9876: # Remember both $symb and $title for dynamic metadata
 9877:             $accesshash{$symb.'___crstitle'}=$title;
 9878:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
 9879: # Cache this title and then return it
 9880: 	    return &do_cache_new('title',$key,$title,600);
 9881: 	}
 9882: 	$urlsymb=$url;
 9883:     }
 9884:     my $title=&metadata($urlsymb,'title');
 9885:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
 9886:     return $title;
 9887: }
 9888: 
 9889: sub get_slot {
 9890:     my ($which,$cnum,$cdom)=@_;
 9891:     if (!$cnum || !$cdom) {
 9892: 	(undef,my $courseid)=&whichuser();
 9893: 	$cdom=$env{'course.'.$courseid.'.domain'};
 9894: 	$cnum=$env{'course.'.$courseid.'.num'};
 9895:     }
 9896:     my $key=join("\0",'slots',$cdom,$cnum,$which);
 9897:     my %slotinfo;
 9898:     if (exists($remembered{$key})) {
 9899: 	$slotinfo{$which} = $remembered{$key};
 9900:     } else {
 9901: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
 9902: 	&Apache::lonhomework::showhash(%slotinfo);
 9903: 	my ($tmp)=keys(%slotinfo);
 9904: 	if ($tmp=~/^error:/) { return (); }
 9905: 	$remembered{$key} = $slotinfo{$which};
 9906:     }
 9907:     if (ref($slotinfo{$which}) eq 'HASH') {
 9908: 	return %{$slotinfo{$which}};
 9909:     }
 9910:     return $slotinfo{$which};
 9911: }
 9912: 
 9913: sub get_reservable_slots {
 9914:     my ($cnum,$cdom,$uname,$udom) = @_;
 9915:     my $now = time;
 9916:     my $reservable_info;
 9917:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
 9918:     if (exists($remembered{$key})) {
 9919:         $reservable_info = $remembered{$key};
 9920:     } else {
 9921:         my %resv;
 9922:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
 9923:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
 9924:         $reservable_info = \%resv;
 9925:         $remembered{$key} = $reservable_info;
 9926:     }
 9927:     return $reservable_info;
 9928: }
 9929: 
 9930: sub get_course_slots {
 9931:     my ($cnum,$cdom) = @_;
 9932:     my $hashid=$cnum.':'.$cdom;
 9933:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
 9934:     if (defined($cached)) {
 9935:         if (ref($result) eq 'HASH') {
 9936:             return %{$result};
 9937:         }
 9938:     } else {
 9939:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
 9940:         my ($tmp) = keys(%slots);
 9941:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 9942:             &Apache::lonnet::do_cache_new('allslots',$hashid,\%slots,600);
 9943:             return %slots;
 9944:         }
 9945:     }
 9946:     return;
 9947: }
 9948: 
 9949: sub devalidate_slots_cache {
 9950:     my ($cnum,$cdom)=@_;
 9951:     my $hashid=$cnum.':'.$cdom;
 9952:     &devalidate_cache_new('allslots',$hashid);
 9953: }
 9954: 
 9955: sub get_coursechange {
 9956:     my ($cdom,$cnum) = @_;
 9957:     if ($cdom eq '' || $cnum eq '') {
 9958:         return unless ($env{'request.course.id'});
 9959:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9960:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9961:     }
 9962:     my $hashid=$cdom.'_'.$cnum;
 9963:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
 9964:     if ((defined($cached)) && ($change ne '')) {
 9965:         return $change;
 9966:     } else {
 9967:         my %crshash;
 9968:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
 9969:         if ($crshash{'internal.contentchange'} eq '') {
 9970:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
 9971:             if ($change eq '') {
 9972:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
 9973:                 $change = $crshash{'internal.created'};
 9974:             }
 9975:         } else {
 9976:             $change = $crshash{'internal.contentchange'};
 9977:         }
 9978:         my $cachetime = 600;
 9979:         &do_cache_new('crschange',$hashid,$change,$cachetime);
 9980:     }
 9981:     return $change;
 9982: }
 9983: 
 9984: sub devalidate_coursechange_cache {
 9985:     my ($cnum,$cdom)=@_;
 9986:     my $hashid=$cnum.':'.$cdom;
 9987:     &devalidate_cache_new('crschange',$hashid);
 9988: }
 9989: 
 9990: # ------------------------------------------------- Update symbolic store links
 9991: 
 9992: sub symblist {
 9993:     my ($mapname,%newhash)=@_;
 9994:     $mapname=&deversion(&declutter($mapname));
 9995:     my %hash;
 9996:     if (($env{'request.course.fn'}) && (%newhash)) {
 9997:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 9998:                       &GDBM_WRCREAT(),0640)) {
 9999: 	    foreach my $url (keys(%newhash)) {
10000: 		next if ($url eq 'last_known'
10001: 			 && $env{'form.no_update_last_known'});
10002: 		$hash{declutter($url)}=&encode_symb($mapname,
10003: 						    $newhash{$url}->[1],
10004: 						    $newhash{$url}->[0]);
10005:             }
10006:             if (untie(%hash)) {
10007: 		return 'ok';
10008:             }
10009:         }
10010:     }
10011:     return 'error';
10012: }
10013: 
10014: # --------------------------------------------------------------- Verify a symb
10015: 
10016: sub symbverify {
10017:     my ($symb,$thisurl)=@_;
10018:     my $thisfn=$thisurl;
10019:     $thisfn=&declutter($thisfn);
10020: # direct jump to resource in page or to a sequence - will construct own symbs
10021:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
10022: # check URL part
10023:     my ($map,$resid,$url)=&decode_symb($symb);
10024: 
10025:     unless ($url eq $thisfn) { return 0; }
10026: 
10027:     $symb=&symbclean($symb);
10028:     $thisurl=&deversion($thisurl);
10029:     $thisfn=&deversion($thisfn);
10030: 
10031:     my %bighash;
10032:     my $okay=0;
10033: 
10034:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10035:                             &GDBM_READER(),0640)) {
10036:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
10037:             $thisurl =~ s/\?.+$//;
10038:         }
10039:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
10040:         unless ($ids) {
10041:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
10042:             $ids=$bighash{$idkey};
10043:         }
10044:         if ($ids) {
10045: # ------------------------------------------------------------------- Has ID(s)
10046: 	    foreach my $id (split(/\,/,$ids)) {
10047: 	       my ($mapid,$resid)=split(/\./,$id);
10048:                if ($thisfn =~ m{^/adm/wrapper/ext/}) {
10049:                    $symb =~ s/\?.+$//;
10050:                }
10051:                if (
10052:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
10053:    eq $symb) { 
10054: 		   if (($env{'request.role.adv'}) ||
10055: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
10056:                        ($thisurl eq '/adm/navmaps')) {
10057: 		       $okay=1; 
10058: 		   }
10059: 	       }
10060: 	   }
10061:         }
10062: 	untie(%bighash);
10063:     }
10064:     return $okay;
10065: }
10066: 
10067: # --------------------------------------------------------------- Clean-up symb
10068: 
10069: sub symbclean {
10070:     my $symb=shift;
10071:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10072: # remove version from map
10073:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
10074: 
10075: # remove version from URL
10076:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
10077: 
10078: # remove wrapper
10079: 
10080:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
10081:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
10082:     return $symb;
10083: }
10084: 
10085: # ---------------------------------------------- Split symb to find map and url
10086: 
10087: sub encode_symb {
10088:     my ($map,$resid,$url)=@_;
10089:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
10090: }
10091: 
10092: sub decode_symb {
10093:     my $symb=shift;
10094:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10095:     my ($map,$resid,$url)=split(/___/,$symb);
10096:     return (&fixversion($map),$resid,&fixversion($url));
10097: }
10098: 
10099: sub fixversion {
10100:     my $fn=shift;
10101:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
10102:     my %bighash;
10103:     my $uri=&clutter($fn);
10104:     my $key=$env{'request.course.id'}.'_'.$uri;
10105: # is this cached?
10106:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
10107:     if (defined($cached)) { return $result; }
10108: # unfortunately not cached, or expired
10109:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10110: 	    &GDBM_READER(),0640)) {
10111:  	if ($bighash{'version_'.$uri}) {
10112:  	    my $version=$bighash{'version_'.$uri};
10113:  	    unless (($version eq 'mostrecent') || 
10114: 		    ($version==&getversion($uri))) {
10115:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
10116:  	    }
10117:  	}
10118:  	untie %bighash;
10119:     }
10120:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
10121: }
10122: 
10123: sub deversion {
10124:     my $url=shift;
10125:     $url=~s/\.\d+\.(\w+)$/\.$1/;
10126:     return $url;
10127: }
10128: 
10129: # ------------------------------------------------------ Return symb list entry
10130: 
10131: sub symbread {
10132:     my ($thisfn,$donotrecurse)=@_;
10133:     my $cache_str='request.symbread.cached.'.$thisfn;
10134:     if (defined($env{$cache_str})) {
10135:         if (($thisfn) || ($env{$cache_str} ne '')) {
10136:             return $env{$cache_str};
10137:         }
10138:     }
10139: # no filename provided? try from environment
10140:     unless ($thisfn) {
10141:         if ($env{'request.symb'}) {
10142: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
10143: 	}
10144: 	$thisfn=$env{'request.filename'};
10145:     }
10146:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
10147: # is that filename actually a symb? Verify, clean, and return
10148:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
10149: 	if (&symbverify($thisfn,$1)) {
10150: 	    return $env{$cache_str}=&symbclean($thisfn);
10151: 	}
10152:     }
10153:     $thisfn=declutter($thisfn);
10154:     my %hash;
10155:     my %bighash;
10156:     my $syval='';
10157:     if (($env{'request.course.fn'}) && ($thisfn)) {
10158:         my $targetfn = $thisfn;
10159:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
10160:             $targetfn = 'adm/wrapper/'.$thisfn;
10161:         }
10162: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
10163: 	    $targetfn=$1;
10164: 	}
10165:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
10166:                       &GDBM_READER(),0640)) {
10167: 	    $syval=$hash{$targetfn};
10168:             untie(%hash);
10169:         }
10170: # ---------------------------------------------------------- There was an entry
10171:         if ($syval) {
10172: 	    #unless ($syval=~/\_\d+$/) {
10173: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
10174: 		    #&appenv({'request.ambiguous' => $thisfn});
10175: 		    #return $env{$cache_str}='';
10176: 		#}    
10177: 		#$syval.=$1;
10178: 	    #}
10179:         } else {
10180: # ------------------------------------------------------- Was not in symb table
10181:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10182:                             &GDBM_READER(),0640)) {
10183: # ---------------------------------------------- Get ID(s) for current resource
10184:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
10185:               unless ($ids) { 
10186:                  $ids=$bighash{'ids_/'.$thisfn};
10187:               }
10188:               unless ($ids) {
10189: # alias?
10190: 		  $ids=$bighash{'mapalias_'.$thisfn};
10191:               }
10192:               if ($ids) {
10193: # ------------------------------------------------------------------- Has ID(s)
10194:                  my @possibilities=split(/\,/,$ids);
10195:                  if ($#possibilities==0) {
10196: # ----------------------------------------------- There is only one possibility
10197: 		     my ($mapid,$resid)=split(/\./,$ids);
10198: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
10199: 						    $resid,$thisfn);
10200:                  } elsif (!$donotrecurse) {
10201: # ------------------------------------------ There is more than one possibility
10202:                      my $realpossible=0;
10203:                      foreach my $id (@possibilities) {
10204: 			 my $file=$bighash{'src_'.$id};
10205:                          if (&allowed('bre',$file)) {
10206:          		    my ($mapid,$resid)=split(/\./,$id);
10207:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
10208: 				$realpossible++;
10209:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
10210: 						    $resid,$thisfn);
10211:                             }
10212: 			 }
10213:                      }
10214: 		     if ($realpossible!=1) { $syval=''; }
10215:                  } else {
10216:                      $syval='';
10217:                  }
10218: 	      }
10219:               untie(%bighash)
10220:            }
10221:         }
10222:         if ($syval) {
10223: 	    return $env{$cache_str}=$syval;
10224:         }
10225:     }
10226:     &appenv({'request.ambiguous' => $thisfn});
10227:     return $env{$cache_str}='';
10228: }
10229: 
10230: # ---------------------------------------------------------- Return random seed
10231: 
10232: sub numval {
10233:     my $txt=shift;
10234:     $txt=~tr/A-J/0-9/;
10235:     $txt=~tr/a-j/0-9/;
10236:     $txt=~tr/K-T/0-9/;
10237:     $txt=~tr/k-t/0-9/;
10238:     $txt=~tr/U-Z/0-5/;
10239:     $txt=~tr/u-z/0-5/;
10240:     $txt=~s/\D//g;
10241:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
10242:     return int($txt);
10243: }
10244: 
10245: sub numval2 {
10246:     my $txt=shift;
10247:     $txt=~tr/A-J/0-9/;
10248:     $txt=~tr/a-j/0-9/;
10249:     $txt=~tr/K-T/0-9/;
10250:     $txt=~tr/k-t/0-9/;
10251:     $txt=~tr/U-Z/0-5/;
10252:     $txt=~tr/u-z/0-5/;
10253:     $txt=~s/\D//g;
10254:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10255:     my $total;
10256:     foreach my $val (@txts) { $total+=$val; }
10257:     if ($_64bit) { if ($total > 2**32) { return -1; } }
10258:     return int($total);
10259: }
10260: 
10261: sub numval3 {
10262:     use integer;
10263:     my $txt=shift;
10264:     $txt=~tr/A-J/0-9/;
10265:     $txt=~tr/a-j/0-9/;
10266:     $txt=~tr/K-T/0-9/;
10267:     $txt=~tr/k-t/0-9/;
10268:     $txt=~tr/U-Z/0-5/;
10269:     $txt=~tr/u-z/0-5/;
10270:     $txt=~s/\D//g;
10271:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10272:     my $total;
10273:     foreach my $val (@txts) { $total+=$val; }
10274:     if ($_64bit) { $total=(($total<<32)>>32); }
10275:     return $total;
10276: }
10277: 
10278: sub digest {
10279:     my ($data)=@_;
10280:     my $digest=&Digest::MD5::md5($data);
10281:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
10282:     my ($e,$f);
10283:     {
10284:         use integer;
10285:         $e=($a+$b);
10286:         $f=($c+$d);
10287:         if ($_64bit) {
10288:             $e=(($e<<32)>>32);
10289:             $f=(($f<<32)>>32);
10290:         }
10291:     }
10292:     if (wantarray) {
10293: 	return ($e,$f);
10294:     } else {
10295: 	my $g;
10296: 	{
10297: 	    use integer;
10298: 	    $g=($e+$f);
10299: 	    if ($_64bit) {
10300: 		$g=(($g<<32)>>32);
10301: 	    }
10302: 	}
10303: 	return $g;
10304:     }
10305: }
10306: 
10307: sub latest_rnd_algorithm_id {
10308:     return '64bit5';
10309: }
10310: 
10311: sub get_rand_alg {
10312:     my ($courseid)=@_;
10313:     if (!$courseid) { $courseid=(&whichuser())[1]; }
10314:     if ($courseid) {
10315: 	return $env{"course.$courseid.rndseed"};
10316:     }
10317:     return &latest_rnd_algorithm_id();
10318: }
10319: 
10320: sub validCODE {
10321:     my ($CODE)=@_;
10322:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
10323:     return 0;
10324: }
10325: 
10326: sub getCODE {
10327:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
10328:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
10329: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
10330: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
10331: 	return $Apache::lonhomework::history{'resource.CODE'};
10332:     }
10333:     return undef;
10334: }
10335: #
10336: #  Determines the random seed for a specific context:
10337: #
10338: # parameters:
10339: #   symb      - in course context the symb for the seed.
10340: #   course_id - The course id of the form domain_coursenum.
10341: #   domain    - Domain for the user.
10342: #   course    - Course for the user.
10343: #   cenv      - environment of the course.
10344: #
10345: # NOTE:
10346: #   All parameters are picked out of the environment if missing
10347: #   or not defined.
10348: #   If a symb cannot be determined the current time is used instead.
10349: #
10350: #  For a given well defined symb, courside, domain, username,
10351: #  and course environment, the seed is reproducible.
10352: #
10353: sub rndseed {
10354:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
10355:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
10356:     if (!defined($symb)) {
10357: 	unless ($symb=$wsymb) { return time; }
10358:     }
10359:     if (!defined $courseid) { 
10360: 	$courseid=$wcourseid; 
10361:     }
10362:     if (!defined $domain) { $domain=$wdomain; }
10363:     if (!defined $username) { $username=$wusername }
10364: 
10365:     my $which;
10366:     if (defined($cenv->{'rndseed'})) {
10367: 	$which = $cenv->{'rndseed'};
10368:     } else {
10369: 	$which =&get_rand_alg($courseid);
10370:     }
10371:     if (defined(&getCODE())) {
10372: 
10373: 	if ($which eq '64bit5') {
10374: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
10375: 	} elsif ($which eq '64bit4') {
10376: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
10377: 	} else {
10378: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
10379: 	}
10380:     } elsif ($which eq '64bit5') {
10381: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
10382:     } elsif ($which eq '64bit4') {
10383: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
10384:     } elsif ($which eq '64bit3') {
10385: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
10386:     } elsif ($which eq '64bit2') {
10387: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
10388:     } elsif ($which eq '64bit') {
10389: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
10390:     }
10391:     return &rndseed_32bit($symb,$courseid,$domain,$username);
10392: }
10393: 
10394: sub rndseed_32bit {
10395:     my ($symb,$courseid,$domain,$username)=@_;
10396:     {
10397: 	use integer;
10398: 	my $symbchck=unpack("%32C*",$symb) << 27;
10399: 	my $symbseed=numval($symb) << 22;
10400: 	my $namechck=unpack("%32C*",$username) << 17;
10401: 	my $nameseed=numval($username) << 12;
10402: 	my $domainseed=unpack("%32C*",$domain) << 7;
10403: 	my $courseseed=unpack("%32C*",$courseid);
10404: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
10405: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10406: 	#&logthis("rndseed :$num:$symb");
10407: 	if ($_64bit) { $num=(($num<<32)>>32); }
10408: 	return $num;
10409:     }
10410: }
10411: 
10412: sub rndseed_64bit {
10413:     my ($symb,$courseid,$domain,$username)=@_;
10414:     {
10415: 	use integer;
10416: 	my $symbchck=unpack("%32S*",$symb) << 21;
10417: 	my $symbseed=numval($symb) << 10;
10418: 	my $namechck=unpack("%32S*",$username);
10419: 	
10420: 	my $nameseed=numval($username) << 21;
10421: 	my $domainseed=unpack("%32S*",$domain) << 10;
10422: 	my $courseseed=unpack("%32S*",$courseid);
10423: 	
10424: 	my $num1=$symbchck+$symbseed+$namechck;
10425: 	my $num2=$nameseed+$domainseed+$courseseed;
10426: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10427: 	#&logthis("rndseed :$num:$symb");
10428: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10429: 	return "$num1,$num2";
10430:     }
10431: }
10432: 
10433: sub rndseed_64bit2 {
10434:     my ($symb,$courseid,$domain,$username)=@_;
10435:     {
10436: 	use integer;
10437: 	# strings need to be an even # of cahracters long, it it is odd the
10438:         # last characters gets thrown away
10439: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
10440: 	my $symbseed=numval($symb) << 10;
10441: 	my $namechck=unpack("%32S*",$username.' ');
10442: 	
10443: 	my $nameseed=numval($username) << 21;
10444: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
10445: 	my $courseseed=unpack("%32S*",$courseid.' ');
10446: 	
10447: 	my $num1=$symbchck+$symbseed+$namechck;
10448: 	my $num2=$nameseed+$domainseed+$courseseed;
10449: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10450: 	#&logthis("rndseed :$num:$symb");
10451: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10452: 	return "$num1,$num2";
10453:     }
10454: }
10455: 
10456: sub rndseed_64bit3 {
10457:     my ($symb,$courseid,$domain,$username)=@_;
10458:     {
10459: 	use integer;
10460: 	# strings need to be an even # of cahracters long, it it is odd the
10461:         # last characters gets thrown away
10462: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
10463: 	my $symbseed=numval2($symb) << 10;
10464: 	my $namechck=unpack("%32S*",$username.' ');
10465: 	
10466: 	my $nameseed=numval2($username) << 21;
10467: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
10468: 	my $courseseed=unpack("%32S*",$courseid.' ');
10469: 	
10470: 	my $num1=$symbchck+$symbseed+$namechck;
10471: 	my $num2=$nameseed+$domainseed+$courseseed;
10472: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10473: 	#&logthis("rndseed :$num1:$num2:$_64bit");
10474: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10475: 	
10476: 	return "$num1:$num2";
10477:     }
10478: }
10479: 
10480: sub rndseed_64bit4 {
10481:     my ($symb,$courseid,$domain,$username)=@_;
10482:     {
10483: 	use integer;
10484: 	# strings need to be an even # of cahracters long, it it is odd the
10485:         # last characters gets thrown away
10486: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
10487: 	my $symbseed=numval3($symb) << 10;
10488: 	my $namechck=unpack("%32S*",$username.' ');
10489: 	
10490: 	my $nameseed=numval3($username) << 21;
10491: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
10492: 	my $courseseed=unpack("%32S*",$courseid.' ');
10493: 	
10494: 	my $num1=$symbchck+$symbseed+$namechck;
10495: 	my $num2=$nameseed+$domainseed+$courseseed;
10496: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10497: 	#&logthis("rndseed :$num1:$num2:$_64bit");
10498: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10499: 	
10500: 	return "$num1:$num2";
10501:     }
10502: }
10503: 
10504: sub rndseed_64bit5 {
10505:     my ($symb,$courseid,$domain,$username)=@_;
10506:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
10507:     return "$num1:$num2";
10508: }
10509: 
10510: sub rndseed_CODE_64bit {
10511:     my ($symb,$courseid,$domain,$username)=@_;
10512:     {
10513: 	use integer;
10514: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
10515: 	my $symbseed=numval2($symb);
10516: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
10517: 	my $CODEseed=numval(&getCODE());
10518: 	my $courseseed=unpack("%32S*",$courseid.' ');
10519: 	my $num1=$symbseed+$CODEchck;
10520: 	my $num2=$CODEseed+$courseseed+$symbchck;
10521: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
10522: 	#&logthis("rndseed :$num1:$num2:$symb");
10523: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
10524: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
10525: 	return "$num1:$num2";
10526:     }
10527: }
10528: 
10529: sub rndseed_CODE_64bit4 {
10530:     my ($symb,$courseid,$domain,$username)=@_;
10531:     {
10532: 	use integer;
10533: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
10534: 	my $symbseed=numval3($symb);
10535: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
10536: 	my $CODEseed=numval3(&getCODE());
10537: 	my $courseseed=unpack("%32S*",$courseid.' ');
10538: 	my $num1=$symbseed+$CODEchck;
10539: 	my $num2=$CODEseed+$courseseed+$symbchck;
10540: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
10541: 	#&logthis("rndseed :$num1:$num2:$symb");
10542: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
10543: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
10544: 	return "$num1:$num2";
10545:     }
10546: }
10547: 
10548: sub rndseed_CODE_64bit5 {
10549:     my ($symb,$courseid,$domain,$username)=@_;
10550:     my $code = &getCODE();
10551:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
10552:     return "$num1:$num2";
10553: }
10554: 
10555: sub setup_random_from_rndseed {
10556:     my ($rndseed)=@_;
10557:     if ($rndseed =~/([,:])/) {
10558: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
10559: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
10560:     } else {
10561: 	&Math::Random::random_set_seed_from_phrase($rndseed);
10562:     }
10563: }
10564: 
10565: sub latest_receipt_algorithm_id {
10566:     return 'receipt3';
10567: }
10568: 
10569: sub recunique {
10570:     my $fucourseid=shift;
10571:     my $unique;
10572:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
10573: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
10574: 	$unique=$env{"course.$fucourseid.internal.encseed"};
10575:     } else {
10576: 	$unique=$perlvar{'lonReceipt'};
10577:     }
10578:     return unpack("%32C*",$unique);
10579: }
10580: 
10581: sub recprefix {
10582:     my $fucourseid=shift;
10583:     my $prefix;
10584:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
10585: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
10586: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
10587:     } else {
10588: 	$prefix=$perlvar{'lonHostID'};
10589:     }
10590:     return unpack("%32C*",$prefix);
10591: }
10592: 
10593: sub ireceipt {
10594:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
10595: 
10596:     my $return =&recprefix($fucourseid).'-';
10597: 
10598:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
10599: 	$env{'request.state'} eq 'construct') {
10600: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
10601: 	return $return;
10602:     }
10603: 
10604:     my $cuname=unpack("%32C*",$funame);
10605:     my $cudom=unpack("%32C*",$fudom);
10606:     my $cucourseid=unpack("%32C*",$fucourseid);
10607:     my $cusymb=unpack("%32C*",$fusymb);
10608:     my $cunique=&recunique($fucourseid);
10609:     my $cpart=unpack("%32S*",$part);
10610:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
10611: 
10612: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
10613: 			       
10614: 	$return.= ($cunique%$cuname+
10615: 		   $cunique%$cudom+
10616: 		   $cusymb%$cuname+
10617: 		   $cusymb%$cudom+
10618: 		   $cucourseid%$cuname+
10619: 		   $cucourseid%$cudom+
10620: 		   $cpart%$cuname+
10621: 		   $cpart%$cudom);
10622:     } else {
10623: 	$return.= ($cunique%$cuname+
10624: 		   $cunique%$cudom+
10625: 		   $cusymb%$cuname+
10626: 		   $cusymb%$cudom+
10627: 		   $cucourseid%$cuname+
10628: 		   $cucourseid%$cudom);
10629:     }
10630:     return $return;
10631: }
10632: 
10633: sub receipt {
10634:     my ($part)=@_;
10635:     my ($symb,$courseid,$domain,$name) = &whichuser();
10636:     return &ireceipt($name,$domain,$courseid,$symb,$part);
10637: }
10638: 
10639: sub whichuser {
10640:     my ($passedsymb)=@_;
10641:     my ($symb,$courseid,$domain,$name,$publicuser);
10642:     if (defined($env{'form.grade_symb'})) {
10643: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
10644: 	my $allowed=&allowed('vgr',$tmp_courseid);
10645: 	if (!$allowed &&
10646: 	    exists($env{'request.course.sec'}) &&
10647: 	    $env{'request.course.sec'} !~ /^\s*$/) {
10648: 	    $allowed=&allowed('vgr',$tmp_courseid.
10649: 			      '/'.$env{'request.course.sec'});
10650: 	}
10651: 	if ($allowed) {
10652: 	    ($symb)=&get_env_multiple('form.grade_symb');
10653: 	    $courseid=$tmp_courseid;
10654: 	    ($domain)=&get_env_multiple('form.grade_domain');
10655: 	    ($name)=&get_env_multiple('form.grade_username');
10656: 	    return ($symb,$courseid,$domain,$name,$publicuser);
10657: 	}
10658:     }
10659:     if (!$passedsymb) {
10660: 	$symb=&symbread();
10661:     } else {
10662: 	$symb=$passedsymb;
10663:     }
10664:     $courseid=$env{'request.course.id'};
10665:     $domain=$env{'user.domain'};
10666:     $name=$env{'user.name'};
10667:     if ($name eq 'public' && $domain eq 'public') {
10668: 	if (!defined($env{'form.username'})) {
10669: 	    $env{'form.username'}.=time.rand(10000000);
10670: 	}
10671: 	$name.=$env{'form.username'};
10672:     }
10673:     return ($symb,$courseid,$domain,$name,$publicuser);
10674: 
10675: }
10676: 
10677: # ------------------------------------------------------------ Serves up a file
10678: # returns either the contents of the file or 
10679: # -1 if the file doesn't exist
10680: #
10681: # if the target is a file that was uploaded via DOCS, 
10682: # a check will be made to see if a current copy exists on the local server,
10683: # if it does this will be served, otherwise a copy will be retrieved from
10684: # the home server for the course and stored in /home/httpd/html/userfiles on
10685: # the local server.   
10686: 
10687: sub getfile {
10688:     my ($file) = @_;
10689:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
10690:     &repcopy($file);
10691:     return &readfile($file);
10692: }
10693: 
10694: sub repcopy_userfile {
10695:     my ($file)=@_;
10696:     my $londocroot = $perlvar{'lonDocRoot'};
10697:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
10698:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
10699:     my ($cdom,$cnum,$filename) = 
10700: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
10701:     my $uri="/uploaded/$cdom/$cnum/$filename";
10702:     if (-e "$file") {
10703: # we already have a local copy, check it out
10704: 	my @fileinfo = stat($file);
10705: 	my $rtncode;
10706: 	my $info;
10707: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
10708: 	if ($lwpresp ne 'ok') {
10709: # there is no such file anymore, even though we had a local copy
10710: 	    if ($rtncode eq '404') {
10711: 		unlink($file);
10712: 	    }
10713: 	    return -1;
10714: 	}
10715: 	if ($info < $fileinfo[9]) {
10716: # nice, the file we have is up-to-date, just say okay
10717: 	    return 'ok';
10718: 	} else {
10719: # the file is outdated, get rid of it
10720: 	    unlink($file);
10721: 	}
10722:     }
10723: # one way or the other, at this point, we don't have the file
10724: # construct the correct path for the file
10725:     my @parts = ($cdom,$cnum); 
10726:     if ($filename =~ m|^(.+)/[^/]+$|) {
10727: 	push @parts, split(/\//,$1);
10728:     }
10729:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
10730:     foreach my $part (@parts) {
10731: 	$path .= '/'.$part;
10732: 	if (!-e $path) {
10733: 	    mkdir($path,0770);
10734: 	}
10735:     }
10736: # now the path exists for sure
10737: # get a user agent
10738:     my $ua=new LWP::UserAgent;
10739:     my $transferfile=$file.'.in.transfer';
10740: # FIXME: this should flock
10741:     if (-e $transferfile) { return 'ok'; }
10742:     my $request;
10743:     $uri=~s/^\///;
10744:     my $homeserver = &homeserver($cnum,$cdom);
10745:     my $protocol = $protocol{$homeserver};
10746:     $protocol = 'http' if ($protocol ne 'https');
10747:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
10748:     my $response=$ua->request($request,$transferfile);
10749: # did it work?
10750:     if ($response->is_error()) {
10751: 	unlink($transferfile);
10752: 	&logthis("Userfile repcopy failed for $uri");
10753: 	return -1;
10754:     }
10755: # worked, rename the transfer file
10756:     rename($transferfile,$file);
10757:     return 'ok';
10758: }
10759: 
10760: sub tokenwrapper {
10761:     my $uri=shift;
10762:     $uri=~s|^https?\://([^/]+)||;
10763:     $uri=~s|^/||;
10764:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
10765:     my $token=$1;
10766:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
10767:     if ($udom && $uname && $file) {
10768: 	$file=~s|(\?\.*)*$||;
10769:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
10770:         my $homeserver = &homeserver($uname,$udom);
10771:         my $protocol = $protocol{$homeserver};
10772:         $protocol = 'http' if ($protocol ne 'https');
10773:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
10774:                (($uri=~/\?/)?'&':'?').'token='.$token.
10775:                                '&tokenissued='.$perlvar{'lonHostID'};
10776:     } else {
10777:         return '/adm/notfound.html';
10778:     }
10779: }
10780: 
10781: # call with reqtype HEAD: get last modification time
10782: # call with reqtype GET: get the file contents
10783: # Do not call this with reqtype GET for large files! It loads everything into memory
10784: #
10785: sub getuploaded {
10786:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
10787:     $uri=~s/^\///;
10788:     my $homeserver = &homeserver($cnum,$cdom);
10789:     my $protocol = $protocol{$homeserver};
10790:     $protocol = 'http' if ($protocol ne 'https');
10791:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
10792:     my $ua=new LWP::UserAgent;
10793:     my $request=new HTTP::Request($reqtype,$uri);
10794:     my $response=$ua->request($request);
10795:     $$rtncode = $response->code;
10796:     if (! $response->is_success()) {
10797: 	return 'failed';
10798:     }      
10799:     if ($reqtype eq 'HEAD') {
10800: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
10801:     } elsif ($reqtype eq 'GET') {
10802: 	$$info = $response->content;
10803:     }
10804:     return 'ok';
10805: }
10806: 
10807: sub readfile {
10808:     my $file = shift;
10809:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
10810:     my $fh;
10811:     open($fh,"<$file");
10812:     my $a='';
10813:     while (my $line = <$fh>) { $a .= $line; }
10814:     return $a;
10815: }
10816: 
10817: sub filelocation {
10818:     my ($dir,$file) = @_;
10819:     my $location;
10820:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
10821: 
10822:     if ($file =~ m-^/adm/-) {
10823: 	$file=~s-^/adm/wrapper/-/-;
10824: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
10825:     }
10826: 
10827:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
10828:         $location = $file;
10829:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
10830:         my ($udom,$uname,$filename)=
10831:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
10832:         my $home=&homeserver($uname,$udom);
10833:         my $is_me=0;
10834:         my @ids=&current_machine_ids();
10835:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
10836:         if ($is_me) {
10837:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
10838:         } else {
10839:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
10840:   	      $udom.'/'.$uname.'/'.$filename;
10841:         }
10842:     } elsif ($file =~ m-^/adm/-) {
10843: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
10844:     } else {
10845:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
10846:         $file=~s:^/(res|priv)/:/:;
10847:         my $space=$1;
10848:         if ( !( $file =~ m:^/:) ) {
10849:             $location = $dir. '/'.$file;
10850:         } else {
10851:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
10852:         }
10853:     }
10854:     $location=~s://+:/:g; # remove duplicate /
10855:     while ($location=~m{/\.\./}) {
10856: 	if ($location =~ m{/[^/]+/\.\./}) {
10857: 	    $location=~ s{/[^/]+/\.\./}{/}g;
10858: 	} else {
10859: 	    $location=~ s{/\.\./}{/}g;
10860: 	}
10861:     } #remove dir/..
10862:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
10863:     return $location;
10864: }
10865: 
10866: sub hreflocation {
10867:     my ($dir,$file)=@_;
10868:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
10869: 	$file=filelocation($dir,$file);
10870:     } elsif ($file=~m-^/adm/-) {
10871: 	$file=~s-^/adm/wrapper/-/-;
10872: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
10873:     }
10874:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
10875: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
10876:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
10877: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
10878: 	        {/uploaded/$1/$2/}x;
10879:     }
10880:     if ($file=~ m{^/userfiles/}) {
10881: 	$file =~ s{^/userfiles/}{/uploaded/};
10882:     }
10883:     return $file;
10884: }
10885: 
10886: 
10887: 
10888: 
10889: 
10890: sub current_machine_domains {
10891:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
10892: }
10893: 
10894: sub machine_domains {
10895:     my ($hostname) = @_;
10896:     my @domains;
10897:     my %hostname = &all_hostnames();
10898:     while( my($id, $name) = each(%hostname)) {
10899: #	&logthis("-$id-$name-$hostname-");
10900: 	if ($hostname eq $name) {
10901: 	    push(@domains,&host_domain($id));
10902: 	}
10903:     }
10904:     return @domains;
10905: }
10906: 
10907: sub current_machine_ids {
10908:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
10909: }
10910: 
10911: sub machine_ids {
10912:     my ($hostname) = @_;
10913:     $hostname ||= &hostname($perlvar{'lonHostID'});
10914:     my @ids;
10915:     my %name_to_host = &all_names();
10916:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
10917: 	return @{ $name_to_host{$hostname} };
10918:     }
10919:     return;
10920: }
10921: 
10922: sub additional_machine_domains {
10923:     my @domains;
10924:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
10925:     while( my $line = <$fh>) {
10926:         $line =~ s/\s//g;
10927:         push(@domains,$line);
10928:     }
10929:     return @domains;
10930: }
10931: 
10932: sub default_login_domain {
10933:     my $domain = $perlvar{'lonDefDomain'};
10934:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
10935:     foreach my $posdom (&current_machine_domains(),
10936:                         &additional_machine_domains()) {
10937:         if (lc($posdom) eq lc($testdomain)) {
10938:             $domain=$posdom;
10939:             last;
10940:         }
10941:     }
10942:     return $domain;
10943: }
10944: 
10945: # ------------------------------------------------------------- Declutters URLs
10946: 
10947: sub declutter {
10948:     my $thisfn=shift;
10949:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
10950:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
10951:     $thisfn=~s/^\///;
10952:     $thisfn=~s|^adm/wrapper/||;
10953:     $thisfn=~s|^adm/coursedocs/showdoc/||;
10954:     $thisfn=~s/^res\///;
10955:     $thisfn=~s/^priv\///;
10956:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
10957:         $thisfn=~s/\?.+$//;
10958:     }
10959:     return $thisfn;
10960: }
10961: 
10962: # ------------------------------------------------------------- Clutter up URLs
10963: 
10964: sub clutter {
10965:     my $thisfn='/'.&declutter(shift);
10966:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
10967: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
10968:        $thisfn='/res'.$thisfn; 
10969:     }
10970:     if ($thisfn !~m|^/adm|) {
10971: 	if ($thisfn =~ m|^/ext/|) {
10972: 	    $thisfn='/adm/wrapper'.$thisfn;
10973: 	} else {
10974: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
10975: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
10976: 	    if ($embstyle eq 'ssi'
10977: 		|| ($embstyle eq 'hdn')
10978: 		|| ($embstyle eq 'rat')
10979: 		|| ($embstyle eq 'prv')
10980: 		|| ($embstyle eq 'ign')) {
10981: 		#do nothing with these
10982: 	    } elsif (($embstyle eq 'img') 
10983: 		|| ($embstyle eq 'emb')
10984: 		|| ($embstyle eq 'wrp')) {
10985: 		$thisfn='/adm/wrapper'.$thisfn;
10986: 	    } elsif ($embstyle eq 'unk'
10987: 		     && $thisfn!~/\.(sequence|page)$/) {
10988: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
10989: 	    } else {
10990: #		&logthis("Got a blank emb style");
10991: 	    }
10992: 	}
10993:     }
10994:     return $thisfn;
10995: }
10996: 
10997: sub clutter_with_no_wrapper {
10998:     my $uri = &clutter(shift);
10999:     if ($uri =~ m-^/adm/-) {
11000: 	$uri =~ s-^/adm/wrapper/-/-;
11001: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
11002:     }
11003:     return $uri;
11004: }
11005: 
11006: sub freeze_escape {
11007:     my ($value)=@_;
11008:     if (ref($value)) {
11009: 	$value=&nfreeze($value);
11010: 	return '__FROZEN__'.&escape($value);
11011:     }
11012:     return &escape($value);
11013: }
11014: 
11015: 
11016: sub thaw_unescape {
11017:     my ($value)=@_;
11018:     if ($value =~ /^__FROZEN__/) {
11019: 	substr($value,0,10,undef);
11020: 	$value=&unescape($value);
11021: 	return &thaw($value);
11022:     }
11023:     return &unescape($value);
11024: }
11025: 
11026: sub correct_line_ends {
11027:     my ($result)=@_;
11028:     $$result =~s/\r\n/\n/mg;
11029:     $$result =~s/\r/\n/mg;
11030: }
11031: # ================================================================ Main Program
11032: 
11033: sub goodbye {
11034:    &logthis("Starting Shut down");
11035: #not converted to using infrastruture and probably shouldn't be
11036:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
11037: #converted
11038: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
11039:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
11040: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
11041: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
11042: #1.1 only
11043: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
11044: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
11045: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
11046: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
11047:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
11048:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
11049:    &logthis(sprintf("%-20s is %s",'hits',$hits));
11050:    &flushcourselogs();
11051:    &logthis("Shutting down");
11052: }
11053: 
11054: sub get_dns {
11055:     my ($url,$func,$ignore_cache) = @_;
11056:     if (!$ignore_cache) {
11057: 	my ($content,$cached)=
11058: 	    &Apache::lonnet::is_cached_new('dns',$url);
11059: 	if ($cached) {
11060: 	    &$func($content);
11061: 	    return;
11062: 	}
11063:     }
11064: 
11065:     my %alldns;
11066:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11067:     foreach my $dns (<$config>) {
11068: 	next if ($dns !~ /^\^(\S*)/x);
11069:         my $line = $1;
11070:         my ($host,$protocol) = split(/:/,$line);
11071:         if ($protocol ne 'https') {
11072:             $protocol = 'http';
11073:         }
11074: 	$alldns{$host} = $protocol;
11075:     }
11076:     while (%alldns) {
11077: 	my ($dns) = keys(%alldns);
11078: 	my $ua=new LWP::UserAgent;
11079:         $ua->timeout(30);
11080: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
11081: 	my $response=$ua->request($request);
11082:         delete($alldns{$dns});
11083: 	next if ($response->is_error());
11084: 	my @content = split("\n",$response->content);
11085: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
11086: 	&$func(\@content);
11087: 	return;
11088:     }
11089:     close($config);
11090:     my $which = (split('/',$url))[3];
11091:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
11092:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
11093:     my @content = <$config>;
11094:     &$func(\@content);
11095:     return;
11096: }
11097: # ------------------------------------------------------------ Read domain file
11098: {
11099:     my $loaded;
11100:     my %domain;
11101: 
11102:     sub parse_domain_tab {
11103: 	my ($lines) = @_;
11104: 	foreach my $line (@$lines) {
11105: 	    next if ($line =~ /^(\#|\s*$ )/x);
11106: 
11107: 	    chomp($line);
11108: 	    my ($name,@elements) = split(/:/,$line,9);
11109: 	    my %this_domain;
11110: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
11111: 			       'lang_def', 'city', 'longi', 'lati',
11112: 			       'primary') {
11113: 		$this_domain{$field} = shift(@elements);
11114: 	    }
11115: 	    $domain{$name} = \%this_domain;
11116: 	}
11117:     }
11118: 
11119:     sub reset_domain_info {
11120: 	undef($loaded);
11121: 	undef(%domain);
11122:     }
11123: 
11124:     sub load_domain_tab {
11125: 	my ($ignore_cache) = @_;
11126: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
11127: 	my $fh;
11128: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
11129: 	    my @lines = <$fh>;
11130: 	    &parse_domain_tab(\@lines);
11131: 	}
11132: 	close($fh);
11133: 	$loaded = 1;
11134:     }
11135: 
11136:     sub domain {
11137: 	&load_domain_tab() if (!$loaded);
11138: 
11139: 	my ($name,$what) = @_;
11140: 	return if ( !exists($domain{$name}) );
11141: 
11142: 	if (!$what) {
11143: 	    return $domain{$name}{'description'};
11144: 	}
11145: 	return $domain{$name}{$what};
11146:     }
11147: 
11148:     sub domain_info {
11149:         &load_domain_tab() if (!$loaded);
11150:         return %domain;
11151:     }
11152: 
11153: }
11154: 
11155: 
11156: # ------------------------------------------------------------- Read hosts file
11157: {
11158:     my %hostname;
11159:     my %hostdom;
11160:     my %libserv;
11161:     my $loaded;
11162:     my %name_to_host;
11163:     my %internetdom;
11164:     my %LC_dns_serv;
11165: 
11166:     sub parse_hosts_tab {
11167: 	my ($file) = @_;
11168: 	foreach my $configline (@$file) {
11169: 	    next if ($configline =~ /^(\#|\s*$ )/x);
11170:             chomp($configline);
11171: 	    if ($configline =~ /^\^/) {
11172:                 if ($configline =~ /^\^([\w.\-]+)/) {
11173:                     $LC_dns_serv{$1} = 1;
11174:                 }
11175:                 next;
11176:             }
11177: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
11178: 	    $name=~s/\s//g;
11179: 	    if ($id && $domain && $role && $name) {
11180: 		$hostname{$id}=$name;
11181: 		push(@{$name_to_host{$name}}, $id);
11182: 		$hostdom{$id}=$domain;
11183: 		if ($role eq 'library') { $libserv{$id}=$name; }
11184:                 if (defined($protocol)) {
11185:                     if ($protocol eq 'https') {
11186:                         $protocol{$id} = $protocol;
11187:                     } else {
11188:                         $protocol{$id} = 'http'; 
11189:                     }
11190:                 } else {
11191:                     $protocol{$id} = 'http';
11192:                 }
11193:                 if (defined($intdom)) {
11194:                     $internetdom{$id} = $intdom;
11195:                 }
11196: 	    }
11197: 	}
11198:     }
11199:     
11200:     sub reset_hosts_info {
11201: 	&purge_remembered();
11202: 	&reset_domain_info();
11203: 	&reset_hosts_ip_info();
11204: 	undef(%name_to_host);
11205: 	undef(%hostname);
11206: 	undef(%hostdom);
11207: 	undef(%libserv);
11208: 	undef($loaded);
11209:     }
11210: 
11211:     sub load_hosts_tab {
11212: 	my ($ignore_cache) = @_;
11213: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
11214: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11215: 	my @config = <$config>;
11216: 	&parse_hosts_tab(\@config);
11217: 	close($config);
11218: 	$loaded=1;
11219:     }
11220: 
11221:     sub hostname {
11222: 	&load_hosts_tab() if (!$loaded);
11223: 
11224: 	my ($lonid) = @_;
11225: 	return $hostname{$lonid};
11226:     }
11227: 
11228:     sub all_hostnames {
11229: 	&load_hosts_tab() if (!$loaded);
11230: 
11231: 	return %hostname;
11232:     }
11233: 
11234:     sub all_names {
11235: 	&load_hosts_tab() if (!$loaded);
11236: 
11237: 	return %name_to_host;
11238:     }
11239: 
11240:     sub all_host_domain {
11241:         &load_hosts_tab() if (!$loaded);
11242:         return %hostdom;
11243:     }
11244: 
11245:     sub is_library {
11246: 	&load_hosts_tab() if (!$loaded);
11247: 
11248: 	return exists($libserv{$_[0]});
11249:     }
11250: 
11251:     sub all_library {
11252: 	&load_hosts_tab() if (!$loaded);
11253: 
11254: 	return %libserv;
11255:     }
11256: 
11257:     sub unique_library {
11258: 	#2x reverse removes all hostnames that appear more than once
11259:         my %unique = reverse &all_library();
11260:         return reverse %unique;
11261:     }
11262: 
11263:     sub get_servers {
11264: 	&load_hosts_tab() if (!$loaded);
11265: 
11266: 	my ($domain,$type) = @_;
11267: 	my %possible_hosts = ($type eq 'library') ? %libserv
11268: 	                                          : %hostname;
11269: 	my %result;
11270: 	if (ref($domain) eq 'ARRAY') {
11271: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
11272: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
11273: 		    $result{$host} = $hostname;
11274: 		}
11275: 	    }
11276: 	} else {
11277: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
11278: 		if ($hostdom{$host} eq $domain) {
11279: 		    $result{$host} = $hostname;
11280: 		}
11281: 	    }
11282: 	}
11283: 	return %result;
11284:     }
11285: 
11286:     sub get_unique_servers {
11287:         my %unique = reverse &get_servers(@_);
11288: 	return reverse %unique;
11289:     }
11290: 
11291:     sub host_domain {
11292: 	&load_hosts_tab() if (!$loaded);
11293: 
11294: 	my ($lonid) = @_;
11295: 	return $hostdom{$lonid};
11296:     }
11297: 
11298:     sub all_domains {
11299: 	&load_hosts_tab() if (!$loaded);
11300: 
11301: 	my %seen;
11302: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
11303: 	return @uniq;
11304:     }
11305: 
11306:     sub internet_dom {
11307:         &load_hosts_tab() if (!$loaded);
11308: 
11309:         my ($lonid) = @_;
11310:         return $internetdom{$lonid};
11311:     }
11312: 
11313:     sub is_LC_dns {
11314:         &load_hosts_tab() if (!$loaded);
11315: 
11316:         my ($hostname) = @_;
11317:         return exists($LC_dns_serv{$hostname});
11318:     }
11319: 
11320: }
11321: 
11322: { 
11323:     my %iphost;
11324:     my %name_to_ip;
11325:     my %lonid_to_ip;
11326: 
11327:     sub get_hosts_from_ip {
11328: 	my ($ip) = @_;
11329: 	my %iphosts = &get_iphost();
11330: 	if (ref($iphosts{$ip})) {
11331: 	    return @{$iphosts{$ip}};
11332: 	}
11333: 	return;
11334:     }
11335:     
11336:     sub reset_hosts_ip_info {
11337: 	undef(%iphost);
11338: 	undef(%name_to_ip);
11339: 	undef(%lonid_to_ip);
11340:     }
11341: 
11342:     sub get_host_ip {
11343: 	my ($lonid) = @_;
11344: 	if (exists($lonid_to_ip{$lonid})) {
11345: 	    return $lonid_to_ip{$lonid};
11346: 	}
11347: 	my $name=&hostname($lonid);
11348:    	my $ip = gethostbyname($name);
11349: 	return if (!$ip || length($ip) ne 4);
11350: 	$ip=inet_ntoa($ip);
11351: 	$name_to_ip{$name}   = $ip;
11352: 	$lonid_to_ip{$lonid} = $ip;
11353: 	return $ip;
11354:     }
11355:     
11356:     sub get_iphost {
11357: 	my ($ignore_cache) = @_;
11358: 
11359: 	if (!$ignore_cache) {
11360: 	    if (%iphost) {
11361: 		return %iphost;
11362: 	    }
11363: 	    my ($ip_info,$cached)=
11364: 		&Apache::lonnet::is_cached_new('iphost','iphost');
11365: 	    if ($cached) {
11366: 		%iphost      = %{$ip_info->[0]};
11367: 		%name_to_ip  = %{$ip_info->[1]};
11368: 		%lonid_to_ip = %{$ip_info->[2]};
11369: 		return %iphost;
11370: 	    }
11371: 	}
11372: 
11373: 	# get yesterday's info for fallback
11374: 	my %old_name_to_ip;
11375: 	my ($ip_info,$cached)=
11376: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
11377: 	if ($cached) {
11378: 	    %old_name_to_ip = %{$ip_info->[1]};
11379: 	}
11380: 
11381: 	my %name_to_host = &all_names();
11382: 	foreach my $name (keys(%name_to_host)) {
11383: 	    my $ip;
11384: 	    if (!exists($name_to_ip{$name})) {
11385: 		$ip = gethostbyname($name);
11386: 		if (!$ip || length($ip) ne 4) {
11387: 		    if (defined($old_name_to_ip{$name})) {
11388: 			$ip = $old_name_to_ip{$name};
11389: 			&logthis("Can't find $name defaulting to old $ip");
11390: 		    } else {
11391: 			&logthis("Name $name no IP found");
11392: 			next;
11393: 		    }
11394: 		} else {
11395: 		    $ip=inet_ntoa($ip);
11396: 		}
11397: 		$name_to_ip{$name} = $ip;
11398: 	    } else {
11399: 		$ip = $name_to_ip{$name};
11400: 	    }
11401: 	    foreach my $id (@{ $name_to_host{$name} }) {
11402: 		$lonid_to_ip{$id} = $ip;
11403: 	    }
11404: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
11405: 	}
11406: 	&Apache::lonnet::do_cache_new('iphost','iphost',
11407: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
11408: 				      48*60*60);
11409: 
11410: 	return %iphost;
11411:     }
11412: 
11413:     #
11414:     #  Given a DNS returns the loncapa host name for that DNS 
11415:     # 
11416:     sub host_from_dns {
11417:         my ($dns) = @_;
11418:         my @hosts;
11419:         my $ip;
11420: 
11421:         if (exists($name_to_ip{$dns})) {
11422:             $ip = $name_to_ip{$dns};
11423:         }
11424:         if (!$ip) {
11425:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
11426:             if (length($ip) == 4) { 
11427: 	        $ip   = &IO::Socket::inet_ntoa($ip);
11428:             }
11429:         }
11430:         if ($ip) {
11431: 	    @hosts = get_hosts_from_ip($ip);
11432: 	    return $hosts[0];
11433:         }
11434:         return undef;
11435:     }
11436: 
11437:     sub get_internet_names {
11438:         my ($lonid) = @_;
11439:         return if ($lonid eq '');
11440:         my ($idnref,$cached)=
11441:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
11442:         if ($cached) {
11443:             return $idnref;
11444:         }
11445:         my $ip = &get_host_ip($lonid);
11446:         my @hosts = &get_hosts_from_ip($ip);
11447:         my %iphost = &get_iphost();
11448:         my (@idns,%seen);
11449:         foreach my $id (@hosts) {
11450:             my $dom = &host_domain($id);
11451:             my $prim_id = &domain($dom,'primary');
11452:             my $prim_ip = &get_host_ip($prim_id);
11453:             next if ($seen{$prim_ip});
11454:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
11455:                 foreach my $id (@{$iphost{$prim_ip}}) {
11456:                     my $intdom = &internet_dom($id);
11457:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
11458:                         push(@idns,$intdom);
11459:                     }
11460:                 }
11461:             }
11462:             $seen{$prim_ip} = 1;
11463:         }
11464:         return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
11465:     }
11466: 
11467: }
11468: 
11469: sub all_loncaparevs {
11470:     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);
11471: }
11472: 
11473: BEGIN {
11474: 
11475: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
11476:     unless ($readit) {
11477: {
11478:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
11479:     %perlvar = (%perlvar,%{$configvars});
11480: }
11481: 
11482: 
11483: # ------------------------------------------------------ Read spare server file
11484: {
11485:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
11486: 
11487:     while (my $configline=<$config>) {
11488:        chomp($configline);
11489:        if ($configline) {
11490: 	   my ($host,$type) = split(':',$configline,2);
11491: 	   if (!defined($type) || $type eq '') { $type = 'default' };
11492: 	   push(@{ $spareid{$type} }, $host);
11493:        }
11494:     }
11495:     close($config);
11496: }
11497: # ------------------------------------------------------------ Read permissions
11498: {
11499:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
11500: 
11501:     while (my $configline=<$config>) {
11502: 	chomp($configline);
11503: 	if ($configline) {
11504: 	    my ($role,$perm)=split(/ /,$configline);
11505: 	    if ($perm ne '') { $pr{$role}=$perm; }
11506: 	}
11507:     }
11508:     close($config);
11509: }
11510: 
11511: # -------------------------------------------- Read plain texts for permissions
11512: {
11513:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
11514: 
11515:     while (my $configline=<$config>) {
11516: 	chomp($configline);
11517: 	if ($configline) {
11518: 	    my ($short,@plain)=split(/:/,$configline);
11519:             %{$prp{$short}} = ();
11520: 	    if (@plain > 0) {
11521:                 $prp{$short}{'std'} = $plain[0];
11522:                 for (my $i=1; $i<@plain; $i++) {
11523:                     $prp{$short}{'alt'.$i} = $plain[$i];  
11524:                 }
11525:             }
11526: 	}
11527:     }
11528:     close($config);
11529: }
11530: 
11531: # ---------------------------------------------------------- Read package table
11532: {
11533:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
11534: 
11535:     while (my $configline=<$config>) {
11536: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
11537: 	chomp($configline);
11538: 	my ($short,$plain)=split(/:/,$configline);
11539: 	my ($pack,$name)=split(/\&/,$short);
11540: 	if ($plain ne '') {
11541: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
11542: 	    $packagetab{$short}=$plain; 
11543: 	}
11544:     }
11545:     close($config);
11546: }
11547: 
11548: # ---------------------------------------------------------- Read loncaparev table
11549: {
11550:     if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
11551:         if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
11552:             while (my $configline=<$config>) {
11553:                 chomp($configline);
11554:                 my ($hostid,$loncaparev)=split(/:/,$configline);
11555:                 $loncaparevs{$hostid}=$loncaparev;
11556:             }
11557:             close($config);
11558:         }
11559:     }
11560: }
11561: 
11562: # ---------------------------------------------------------- Read serverhostID table
11563: {
11564:     if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
11565:         if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
11566:             while (my $configline=<$config>) {
11567:                 chomp($configline);
11568:                 my ($name,$id)=split(/:/,$configline);
11569:                 $serverhomeIDs{$name}=$id;
11570:             }
11571:             close($config);
11572:         }
11573:     }
11574: }
11575: 
11576: {
11577:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
11578:     if (-e $file) {
11579:         my $parser = HTML::LCParser->new($file);
11580:         while (my $token = $parser->get_token()) {
11581:             if ($token->[0] eq 'S') {
11582:                 my $item = $token->[1];
11583:                 my $name = $token->[2]{'name'};
11584:                 my $value = $token->[2]{'value'};
11585:                 if ($item ne '' && $name ne '' && $value ne '') {
11586:                     my $release = $parser->get_text();
11587:                     $release =~ s/(^\s*|\s*$ )//gx;
11588:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
11589:                 }
11590:             }
11591:         }
11592:     }
11593: }
11594: 
11595: # ---------------------------------------------------------- Read managers table
11596: {
11597:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
11598:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
11599:             while (my $configline=<$config>) {
11600:                 chomp($configline);
11601:                 next if ($configline =~ /^\#/);
11602:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
11603:                     $managerstab{$configline} = 1;
11604:                 }
11605:             }
11606:             close($config);
11607:         }
11608:     }
11609: }
11610: 
11611: # ------------- set up temporary directory
11612: {
11613:     $tmpdir = LONCAPA::tempdir();
11614: 
11615: }
11616: 
11617: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
11618: 				'compress_threshold'=> 20_000,
11619:  			        });
11620: 
11621: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
11622: $dumpcount=0;
11623: $locknum=0;
11624: 
11625: &logtouch();
11626: &logthis('<font color="yellow">INFO: Read configuration</font>');
11627: $readit=1;
11628:     {
11629: 	use integer;
11630: 	my $test=(2**32)+1;
11631: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
11632: 	&logthis(" Detected 64bit platform ($_64bit)");
11633:     }
11634: }
11635: }
11636: 
11637: 1;
11638: __END__
11639: 
11640: =pod
11641: 
11642: =head1 NAME
11643: 
11644: Apache::lonnet - Subroutines to ask questions about things in the network.
11645: 
11646: =head1 SYNOPSIS
11647: 
11648: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
11649: 
11650:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
11651: 
11652: Common parameters:
11653: 
11654: =over 4
11655: 
11656: =item *
11657: 
11658: $uname : an internal username (if $cname expecting a course Id specifically)
11659: 
11660: =item *
11661: 
11662: $udom : a domain (if $cdom expecting a course's domain specifically)
11663: 
11664: =item *
11665: 
11666: $symb : a resource instance identifier
11667: 
11668: =item *
11669: 
11670: $namespace : the name of a .db file that contains the data needed or
11671: being set.
11672: 
11673: =back
11674: 
11675: =head1 OVERVIEW
11676: 
11677: lonnet provides subroutines which interact with the
11678: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
11679: about classes, users, and resources.
11680: 
11681: For many of these objects you can also use this to store data about
11682: them or modify them in various ways.
11683: 
11684: =head2 Symbs
11685: 
11686: To identify a specific instance of a resource, LON-CAPA uses symbols
11687: or "symbs"X<symb>. These identifiers are built from the URL of the
11688: map, the resource number of the resource in the map, and the URL of
11689: the resource itself. The latter is somewhat redundant, but might help
11690: if maps change.
11691: 
11692: An example is
11693: 
11694:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
11695: 
11696: The respective map entry is
11697: 
11698:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
11699:   title="Problem 2">
11700:  </resource>
11701: 
11702: Symbs are used by the random number generator, as well as to store and
11703: restore data specific to a certain instance of for example a problem.
11704: 
11705: =head2 Storing And Retrieving Data
11706: 
11707: X<store()>X<cstore()>X<restore()>Three of the most important functions
11708: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
11709: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
11710: is is the non-critical message twin of cstore. These functions are for
11711: handlers to store a perl hash to a user's permanent data space in an
11712: easy manner, and to retrieve it again on another call. It is expected
11713: that a handler would use this once at the beginning to retrieve data,
11714: and then again once at the end to send only the new data back.
11715: 
11716: The data is stored in the user's data directory on the user's
11717: homeserver under the ID of the course.
11718: 
11719: The hash that is returned by restore will have all of the previous
11720: value for all of the elements of the hash.
11721: 
11722: Example:
11723: 
11724:  #creating a hash
11725:  my %hash;
11726:  $hash{'foo'}='bar';
11727: 
11728:  #storing it
11729:  &Apache::lonnet::cstore(\%hash);
11730: 
11731:  #changing a value
11732:  $hash{'foo'}='notbar';
11733: 
11734:  #adding a new value
11735:  $hash{'bar'}='foo';
11736:  &Apache::lonnet::cstore(\%hash);
11737: 
11738:  #retrieving the hash
11739:  my %history=&Apache::lonnet::restore();
11740: 
11741:  #print the hash
11742:  foreach my $key (sort(keys(%history))) {
11743:    print("\%history{$key} = $history{$key}");
11744:  }
11745: 
11746: Will print out:
11747: 
11748:  %history{1:foo} = bar
11749:  %history{1:keys} = foo:timestamp
11750:  %history{1:timestamp} = 990455579
11751:  %history{2:bar} = foo
11752:  %history{2:foo} = notbar
11753:  %history{2:keys} = foo:bar:timestamp
11754:  %history{2:timestamp} = 990455580
11755:  %history{bar} = foo
11756:  %history{foo} = notbar
11757:  %history{timestamp} = 990455580
11758:  %history{version} = 2
11759: 
11760: Note that the special hash entries C<keys>, C<version> and
11761: C<timestamp> were added to the hash. C<version> will be equal to the
11762: total number of versions of the data that have been stored. The
11763: C<timestamp> attribute will be the UNIX time the hash was
11764: stored. C<keys> is available in every historical section to list which
11765: keys were added or changed at a specific historical revision of a
11766: hash.
11767: 
11768: B<Warning>: do not store the hash that restore returns directly. This
11769: will cause a mess since it will restore the historical keys as if the
11770: were new keys. I.E. 1:foo will become 1:1:foo etc.
11771: 
11772: Calling convention:
11773: 
11774:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
11775:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
11776: 
11777: For more detailed information, see lonnet specific documentation.
11778: 
11779: =head1 RETURN MESSAGES
11780: 
11781: =over 4
11782: 
11783: =item * B<con_lost>: unable to contact remote host
11784: 
11785: =item * B<con_delayed>: unable to contact remote host, message will be delivered
11786: when the connection is brought back up
11787: 
11788: =item * B<con_failed>: unable to contact remote host and unable to save message
11789: for later delivery
11790: 
11791: =item * B<error:>: an error a occurred, a description of the error follows the :
11792: 
11793: =item * B<no_such_host>: unable to fund a host associated with the user/domain
11794: that was requested
11795: 
11796: =back
11797: 
11798: =head1 PUBLIC SUBROUTINES
11799: 
11800: =head2 Session Environment Functions
11801: 
11802: =over 4
11803: 
11804: =item * 
11805: X<appenv()>
11806: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
11807: the user envirnoment file, and will be restored for each access this
11808: user makes during this session, also modifies the %env for the current
11809: process. Optional rolesarrayref - if defined contains a reference to an array
11810: of roles which are exempt from the restriction on modifying user.role entries 
11811: in the user's environment.db and in %env.    
11812: 
11813: =item *
11814: X<delenv()>
11815: B<delenv($delthis,$regexp)>: removes all items from the session
11816: environment file that begin with $delthis. If the 
11817: optional second arg - $regexp - is true, $delthis is treated as a 
11818: regular expression, otherwise \Q$delthis\E is used. 
11819: The values are also deleted from the current processes %env.
11820: 
11821: =item * get_env_multiple($name) 
11822: 
11823: gets $name from the %env hash, it seemlessly handles the cases where multiple
11824: values may be defined and end up as an array ref.
11825: 
11826: returns an array of values
11827: 
11828: =back
11829: 
11830: =head2 User Information
11831: 
11832: =over 4
11833: 
11834: =item *
11835: X<queryauthenticate()>
11836: B<queryauthenticate($uname,$udom)>: try to determine user's current 
11837: authentication scheme
11838: 
11839: =item *
11840: X<authenticate()>
11841: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
11842: authenticate user from domain's lib servers (first use the current
11843: one). C<$upass> should be the users password.
11844: $checkdefauth is optional (value is 1 if a check should be made to
11845:    authenticate user using default authentication method, and allow
11846:    account creation if username does not have account in the domain).
11847: $clientcancheckhost is optional (value is 1 if checking whether the
11848:    server can host will occur on the client side in lonauth.pm).   
11849: 
11850: =item *
11851: X<homeserver()>
11852: B<homeserver($uname,$udom)>: find the server which has
11853: the user's directory and files (there must be only one), this caches
11854: the answer, and also caches if there is a borken connection.
11855: 
11856: =item *
11857: X<idget()>
11858: B<idget($udom,@ids)>: find the usernames behind a list of IDs
11859: (IDs are a unique resource in a domain, there must be only 1 ID per
11860: username, and only 1 username per ID in a specific domain) (returns
11861: hash: id=>name,id=>name)
11862: 
11863: =item *
11864: X<idrget()>
11865: B<idrget($udom,@unames)>: find the IDs behind a list of
11866: usernames (returns hash: name=>id,name=>id)
11867: 
11868: =item *
11869: X<idput()>
11870: B<idput($udom,%ids)>: store away a list of names and associated IDs
11871: 
11872: =item *
11873: X<rolesinit()>
11874: B<rolesinit($udom,$username)>: get user privileges.
11875: returns user role, first access and timer interval hashes
11876: 
11877: =item *
11878: X<privileged()>
11879: B<privileged($username,$domain)>: returns a true if user has a
11880: privileged and active role (i.e. su or dc), false otherwise.
11881: 
11882: =item *
11883: X<getsection()>
11884: B<getsection($udom,$uname,$cname)>: finds the section of student in the
11885: course $cname, return section name/number or '' for "not in course"
11886: and '-1' for "no section"
11887: 
11888: =item *
11889: X<userenvironment()>
11890: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
11891: passed in @what from the requested user's environment, returns a hash
11892: 
11893: =item * 
11894: X<userlog_query()>
11895: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
11896: activity.log file. %filters defines filters applied when parsing the
11897: log file. These can be start or end timestamps, or the type of action
11898: - log to look for Login or Logout events, check for Checkin or
11899: Checkout, role for role selection. The response is in the form
11900: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
11901: escaped strings of the action recorded in the activity.log file.
11902: 
11903: =back
11904: 
11905: =head2 User Roles
11906: 
11907: =over 4
11908: 
11909: =item *
11910: 
11911: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
11912:  F: full access
11913:  U,I,K: authentication modes (cxx only)
11914:  '': forbidden
11915:  1: user needs to choose course
11916:  2: browse allowed
11917:  A: passphrase authentication needed
11918: 
11919: =item *
11920: 
11921: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
11922: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
11923: and course level
11924: 
11925: =item *
11926: 
11927: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
11928: (rolesplain.tab); plain text explanation of a user role term.
11929: $type is Course (default) or Community.
11930: If $forcedefault evaluates to true, text returned will be default 
11931: text for $type. Otherwise, if this is a course, the text returned 
11932: will be a custom name for the role (if defined in the course's 
11933: environment).  If no custom name is defined the default is returned.
11934:    
11935: =item *
11936: 
11937: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
11938: All arguments are optional. Returns a hash of a roles, either for
11939: co-author/assistant author roles for a user's Construction Space
11940: (default), or if $context is 'userroles', roles for the user himself,
11941: In the hash, keys are set to colon-separated $uname,$udom,$role, and
11942: (optionally) if $withsec is true, a fourth colon-separated item - $section.
11943: For each key, value is set to colon-separated start and end times for
11944: the role.  If no username and domain are specified, will default to
11945: current user/domain. Types, roles, and roledoms are references to arrays
11946: of role statuses (active, future or previous), roles 
11947: (e.g., cc,in, st etc.) and domains of the roles which can be used
11948: to restrict the list of roles reported. If no array ref is 
11949: provided for types, will default to return only active roles.
11950: 
11951: =back
11952: 
11953: =head2 User Modification
11954: 
11955: =over 4
11956: 
11957: =item *
11958: 
11959: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
11960: user for the level given by URL.  Optional start and end dates (leave empty
11961: string or zero for "no date")
11962: 
11963: =item *
11964: 
11965: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
11966: change a users, password, possible return values are: ok,
11967: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
11968: refused
11969: 
11970: =item *
11971: 
11972: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
11973: 
11974: =item *
11975: 
11976: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
11977:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
11978: 
11979: will update user information (firstname,middlename,lastname,generation,
11980: permanentemail), and if forceid is true, student/employee ID also.
11981: A user's institutional affiliation(s) can also be updated.
11982: User information fields will not be overwritten with empty entries 
11983: unless the field is included in the $candelete array reference.
11984: This array is included when a single user is modified via "Manage Users",
11985: or when Autoupdate.pl is run by cron in a domain.
11986: 
11987: =item *
11988: 
11989: modifystudent
11990: 
11991: modify a student's enrollment and identification information.
11992: The course id is resolved based on the current users environment.  
11993: This means the envoking user must be a course coordinator or otherwise
11994: associated with a course.
11995: 
11996: This call is essentially a wrapper for lonnet::modifyuser and
11997: lonnet::modify_student_enrollment
11998: 
11999: Inputs: 
12000: 
12001: =over 4
12002: 
12003: =item B<$udom> Student's loncapa domain
12004: 
12005: =item B<$uname> Student's loncapa login name
12006: 
12007: =item B<$uid> Student/Employee ID
12008: 
12009: =item B<$umode> Student's authentication mode
12010: 
12011: =item B<$upass> Student's password
12012: 
12013: =item B<$first> Student's first name
12014: 
12015: =item B<$middle> Student's middle name
12016: 
12017: =item B<$last> Student's last name
12018: 
12019: =item B<$gene> Student's generation
12020: 
12021: =item B<$usec> Student's section in course
12022: 
12023: =item B<$end> Unix time of the roles expiration
12024: 
12025: =item B<$start> Unix time of the roles start date
12026: 
12027: =item B<$forceid> If defined, allow $uid to be changed
12028: 
12029: =item B<$desiredhome> server to use as home server for student
12030: 
12031: =item B<$email> Student's permanent e-mail address
12032: 
12033: =item B<$type> Type of enrollment (auto or manual)
12034: 
12035: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
12036: 
12037: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
12038: 
12039: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
12040: 
12041: =item B<$context> role change context (shown in User Management Logs display in a course)
12042: 
12043: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
12044: 
12045: =back
12046: 
12047: =item *
12048: 
12049: modify_student_enrollment
12050: 
12051: Change a students enrollment status in a class.  The environment variable
12052: 'role.request.course' must be defined for this function to proceed.
12053: 
12054: Inputs:
12055: 
12056: =over 4
12057: 
12058: =item $udom, students domain
12059: 
12060: =item $uname, students name
12061: 
12062: =item $uid, students user id
12063: 
12064: =item $first, students first name
12065: 
12066: =item $middle
12067: 
12068: =item $last
12069: 
12070: =item $gene
12071: 
12072: =item $usec
12073: 
12074: =item $end
12075: 
12076: =item $start
12077: 
12078: =item $type
12079: 
12080: =item $locktype
12081: 
12082: =item $cid
12083: 
12084: =item $selfenroll
12085: 
12086: =item $context
12087: 
12088: =back
12089: 
12090: 
12091: =item *
12092: 
12093: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
12094: custom role; give a custom role to a user for the level given by URL.  Specify
12095: name and domain of role author, and role name
12096: 
12097: =item *
12098: 
12099: revokerole($udom,$uname,$url,$role) : revoke a role for url
12100: 
12101: =item *
12102: 
12103: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
12104: 
12105: =back
12106: 
12107: =head2 Course Infomation
12108: 
12109: =over 4
12110: 
12111: =item *
12112: 
12113: coursedescription($courseid,$options) : returns a hash of information about the
12114: specified course id, including all environment settings for the
12115: course, the description of the course will be in the hash under the
12116: key 'description'
12117: 
12118: $options is an optional parameter that if supplied is a hash reference that controls
12119: what how this function works.  It has the following key/values:
12120: 
12121: =over 4
12122: 
12123: =item freshen_cache
12124: 
12125: If defined, and the environment cache for the course is valid, it is 
12126: returned in the returned hash.
12127: 
12128: =item one_time
12129: 
12130: If defined, the last cache time is set to _now_
12131: 
12132: =item user
12133: 
12134: If defined, the supplied username is used instead of the current user.
12135: 
12136: 
12137: =back
12138: 
12139: =item *
12140: 
12141: resdata($name,$domain,$type,@which) : request for current parameter
12142: setting for a specific $type, where $type is either 'course' or 'user',
12143: @what should be a list of parameters to ask about. This routine caches
12144: answers for 5 minutes.
12145: 
12146: =item *
12147: 
12148: get_courseresdata($courseid, $domain) : dump the entire course resource
12149: data base, returning a hash that is keyed by the resource name and has
12150: values that are the resource value.  I believe that the timestamps and
12151: versions are also returned.
12152: 
12153: 
12154: =back
12155: 
12156: =head2 Course Modification
12157: 
12158: =over 4
12159: 
12160: =item *
12161: 
12162: writecoursepref($courseid,%prefs) : write preferences (environment
12163: database) for a course
12164: 
12165: =item *
12166: 
12167: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
12168: 
12169: =item *
12170: 
12171: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
12172: 
12173: =item *
12174: 
12175: is_course($courseid), is_course($cdom, $cnum)
12176: 
12177: Accepts either a combined $courseid (in the form of domain_courseid) or the
12178: two component version $cdom, $cnum. It checks if the specified course exists.
12179: 
12180: Returns:
12181:     undef if the course doesn't exist, otherwise
12182:     in scalar context the combined courseid.
12183:     in list context the two components of the course identifier, domain and 
12184:     courseid.    
12185: 
12186: =back
12187: 
12188: =head2 Resource Subroutines
12189: 
12190: =over 4
12191: 
12192: =item *
12193: 
12194: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
12195: 
12196: =item *
12197: 
12198: repcopy($filename) : subscribes to the requested file, and attempts to
12199: replicate from the owning library server, Might return
12200: 'unavailable', 'not_found', 'forbidden', 'ok', or
12201: 'bad_request', also attempts to grab the metadata for the
12202: resource. Expects the local filesystem pathname
12203: (/home/httpd/html/res/....)
12204: 
12205: =back
12206: 
12207: =head2 Resource Information
12208: 
12209: =over 4
12210: 
12211: =item *
12212: 
12213: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
12214: a vairety of different possible values, $varname should be a request
12215: string, and the other parameters can be used to specify who and what
12216: one is asking about.
12217: 
12218: Possible values for $varname are environment.lastname (or other item
12219: from the envirnment hash), user.name (or someother aspect about the
12220: user), resource.0.maxtries (or some other part and parameter of a
12221: resource)
12222: 
12223: =item *
12224: 
12225: directcondval($number) : get current value of a condition; reads from a state
12226: string
12227: 
12228: =item *
12229: 
12230: condval($condidx) : value of condition index based on state
12231: 
12232: =item *
12233: 
12234: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
12235: resource's metadata, $what should be either a specific key, or either
12236: 'keys' (to get a list of possible keys) or 'packages' to get a list of
12237: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
12238: 
12239: this function automatically caches all requests
12240: 
12241: =item *
12242: 
12243: metadata_query($query,$custom,$customshow) : make a metadata query against the
12244: network of library servers; returns file handle of where SQL and regex results
12245: will be stored for query
12246: 
12247: =item *
12248: 
12249: symbread($filename) : return symbolic list entry (filename argument optional);
12250: returns the data handle
12251: 
12252: =item *
12253: 
12254: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
12255: a possible symb for the URL in $thisfn, and if is an encryypted
12256: resource that the user accessed using /enc/ returns a 1 on success, 0
12257: on failure, user must be in a course, as it assumes the existance of
12258: the course initial hash, and uses $env('request.course.id'}
12259: 
12260: 
12261: =item *
12262: 
12263: symbclean($symb) : removes versions numbers from a symb, returns the
12264: cleaned symb
12265: 
12266: =item *
12267: 
12268: is_on_map($uri) : checks if the $uri is somewhere on the current
12269: course map, user must be in a course for it to work.
12270: 
12271: =item *
12272: 
12273: numval($salt) : return random seed value (addend for rndseed)
12274: 
12275: =item *
12276: 
12277: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
12278: a random seed, all arguments are optional, if they aren't sent it uses the
12279: environment to derive them. Note: if symb isn't sent and it can't get one
12280: from &symbread it will use the current time as its return value
12281: 
12282: =item *
12283: 
12284: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
12285: unfakeable, receipt
12286: 
12287: =item *
12288: 
12289: receipt() : API to ireceipt working off of env values; given out to users
12290: 
12291: =item *
12292: 
12293: countacc($url) : count the number of accesses to a given URL
12294: 
12295: =item *
12296: 
12297: 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
12298: 
12299: =item *
12300: 
12301: 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)
12302: 
12303: =item *
12304: 
12305: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
12306: 
12307: =item *
12308: 
12309: devalidate($symb) : devalidate temporary spreadsheet calculations,
12310: forcing spreadsheet to reevaluate the resource scores next time.
12311: 
12312: =back
12313: 
12314: =head2 Storing/Retreiving Data
12315: 
12316: =over 4
12317: 
12318: =item *
12319: 
12320: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
12321: for this url; hashref needs to be given and should be a \%hashname; the
12322: remaining args aren't required and if they aren't passed or are '' they will
12323: be derived from the env
12324: 
12325: =item *
12326: 
12327: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
12328: uses critical subroutine
12329: 
12330: =item *
12331: 
12332: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
12333: all args are optional
12334: 
12335: =item *
12336: 
12337: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
12338: dumps the complete (or key matching regexp) namespace into a hash
12339: ($udom, $uname, $regexp, $range are optional) for a namespace that is
12340: normally &store()ed into
12341: 
12342: $range should be either an integer '100' (give me the first 100
12343:                                            matching records)
12344:               or be  two integers sperated by a - with no spaces
12345:                  '30-50' (give me the 30th through the 50th matching
12346:                           records)
12347: 
12348: 
12349: =item *
12350: 
12351: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
12352: replaces a &store() version of data with a replacement set of data
12353: for a particular resource in a namespace passed in the $storehash hash 
12354: reference
12355: 
12356: =item *
12357: 
12358: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
12359: works very similar to store/cstore, but all data is stored in a
12360: temporary location and can be reset using tmpreset, $storehash should
12361: be a hash reference, returns nothing on success
12362: 
12363: =item *
12364: 
12365: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
12366: similar to restore, but all data is stored in a temporary location and
12367: can be reset using tmpreset. Returns a hash of values on success,
12368: error string otherwise.
12369: 
12370: =item *
12371: 
12372: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
12373: deltes all keys for $symb form the temporary storage hash.
12374: 
12375: =item *
12376: 
12377: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
12378: reference filled in from namesp ($udom and $uname are optional)
12379: 
12380: =item *
12381: 
12382: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
12383: namesp ($udom and $uname are optional)
12384: 
12385: =item *
12386: 
12387: dump($namespace,$udom,$uname,$regexp,$range) : 
12388: dumps the complete (or key matching regexp) namespace into a hash
12389: ($udom, $uname, $regexp, $range are optional)
12390: 
12391: $range should be either an integer '100' (give me the first 100
12392:                                            matching records)
12393:               or be  two integers sperated by a - with no spaces
12394:                  '30-50' (give me the 30th through the 50th matching
12395:                           records)
12396: =item *
12397: 
12398: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
12399: $store can be a scalar, an array reference, or if the amount to be 
12400: incremented is > 1, a hash reference.
12401: 
12402: ($udom and $uname are optional)
12403: 
12404: =item *
12405: 
12406: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
12407: ($udom and $uname are optional)
12408: 
12409: =item *
12410: 
12411: cput($namespace,$storehash,$udom,$uname) : critical put
12412: ($udom and $uname are optional)
12413: 
12414: =item *
12415: 
12416: newput($namespace,$storehash,$udom,$uname) :
12417: 
12418: Attempts to store the items in the $storehash, but only if they don't
12419: currently exist, if this succeeds you can be certain that you have 
12420: successfully created a new key value pair in the $namespace db.
12421: 
12422: 
12423: Args:
12424:  $namespace: name of database to store values to
12425:  $storehash: hashref to store to the db
12426:  $udom: (optional) domain of user containing the db
12427:  $uname: (optional) name of user caontaining the db
12428: 
12429: Returns:
12430:  'ok' -> succeeded in storing all keys of $storehash
12431:  'key_exists: <key>' -> failed to anything out of $storehash, as at
12432:                         least <key> already existed in the db (other
12433:                         requested keys may also already exist)
12434:  'error: <msg>' -> unable to tie the DB or other error occurred
12435:  'con_lost' -> unable to contact request server
12436:  'refused' -> action was not allowed by remote machine
12437: 
12438: 
12439: =item *
12440: 
12441: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
12442: reference filled in from namesp (encrypts the return communication)
12443: ($udom and $uname are optional)
12444: 
12445: =item *
12446: 
12447: log($udom,$name,$home,$message) : write to permanent log for user; use
12448: critical subroutine
12449: 
12450: =item *
12451: 
12452: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
12453: array reference filled in from namespace found in domain level on either
12454: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
12455: 
12456: =item *
12457: 
12458: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
12459: domain level either on specified domain server ($uhome) or primary domain 
12460: server ($udom and $uhome are optional)
12461: 
12462: =item * 
12463: 
12464: get_domain_defaults($target_domain) : returns hash with defaults for
12465: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
12466: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
12467: or localauth), initial password or a kerberos realm, language (e.g., en-us).
12468: Values are retrieved from cache (if current), or from domain's configuration.db
12469: (if available), or lastly from values in lonTabs/dns_domain,tab, 
12470: or lonTabs/domain.tab. 
12471: 
12472: %domdefaults = &get_auth_defaults($target_domain);
12473: 
12474: =back
12475: 
12476: =head2 Network Status Functions
12477: 
12478: =over 4
12479: 
12480: =item *
12481: 
12482: dirlist() : return directory list based on URI (first arg).
12483: 
12484: Inputs: 1 required, 5 optional.
12485: 
12486: =over
12487: 
12488: =item 
12489: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
12490: 
12491: =item
12492: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
12493: 
12494: =item
12495: $username -  username of user/course to be listed. Extracted from $uri if absent. 
12496: 
12497: =item
12498: $getpropath - boolean: 1 if prepend path using &propath(). 
12499: 
12500: =item
12501: $getuserdir - boolean: 1 if prepend path for "userfiles".
12502: 
12503: =item 
12504: $alternateRoot - path to prepend in place of path from $uri.
12505: 
12506: =back
12507: 
12508: Returns: Array of up to two items.
12509: 
12510: =over
12511: 
12512: a reference to an array of files/subdirectories
12513: 
12514: =over
12515: 
12516: Each element in the array of files/subdirectories is a & separated list of
12517: item name and the result of running stat on the item.  If dirlist was requested
12518: for a file instead of a directory, the item name will be ''. For a directory 
12519: listing, if the item is a metadata file, the element will end &N&M 
12520: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
12521: default copyright set (1).  
12522: 
12523: =back
12524: 
12525: a scalar containing error condition (if encountered).
12526: 
12527: =over
12528: 
12529: =item 
12530: no_host (no homeserver identified for $username:$domain).
12531: 
12532: =item 
12533: no_such_host (server contacted for listing not identified as valid host).
12534: 
12535: =item 
12536: con_lost (connection to remote server failed).
12537: 
12538: =item 
12539: refused (invalid $username:$domain received on lond side).
12540: 
12541: =item 
12542: no_such_dir (directory at specified path on lond side does not exist). 
12543: 
12544: =item 
12545: empty (directory at specified path on lond side is empty).
12546: 
12547: =over
12548: 
12549: This is currently not encountered because the &ls3, &ls2, 
12550: &ls (_handler) routines on the lond side do not filter out
12551: . and .. from a directory listing. 
12552: 
12553: =back
12554: 
12555: =back
12556: 
12557: =back
12558: 
12559: =item *
12560: 
12561: spareserver() : find server with least workload from spare.tab
12562: 
12563: 
12564: =item *
12565: 
12566: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
12567: if there is no corresponding loncapa host.
12568: 
12569: =back
12570: 
12571: 
12572: =head2 Apache Request
12573: 
12574: =over 4
12575: 
12576: =item *
12577: 
12578: ssi($url,%hash) : server side include, does a complete request cycle on url to
12579: localhost, posts hash
12580: 
12581: =back
12582: 
12583: =head2 Data to String to Data
12584: 
12585: =over 4
12586: 
12587: =item *
12588: 
12589: hash2str(%hash) : convert a hash into a string complete with escaping and '='
12590: and '&' separators, supports elements that are arrayrefs and hashrefs
12591: 
12592: =item *
12593: 
12594: hashref2str($hashref) : convert a hashref into a string complete with
12595: escaping and '=' and '&' separators, supports elements that are
12596: arrayrefs and hashrefs
12597: 
12598: =item *
12599: 
12600: arrayref2str($arrayref) : convert an arrayref into a string complete
12601: with escaping and '&' separators, supports elements that are arrayrefs
12602: and hashrefs
12603: 
12604: =item *
12605: 
12606: str2hash($string) : convert string to hash using unescaping and
12607: splitting on '=' and '&', supports elements that are arrayrefs and
12608: hashrefs
12609: 
12610: =item *
12611: 
12612: str2array($string) : convert string to hash using unescaping and
12613: splitting on '&', supports elements that are arrayrefs and hashrefs
12614: 
12615: =back
12616: 
12617: =head2 Logging Routines
12618: 
12619: 
12620: These routines allow one to make log messages in the lonnet.log and
12621: lonnet.perm logfiles.
12622: 
12623: =over 4
12624: 
12625: =item *
12626: 
12627: logtouch() : make sure the logfile, lonnet.log, exists
12628: 
12629: =item *
12630: 
12631: logthis() : append message to the normal lonnet.log file, it gets
12632: preiodically rolled over and deleted.
12633: 
12634: =item *
12635: 
12636: logperm() : append a permanent message to lonnet.perm.log, this log
12637: file never gets deleted by any automated portion of the system, only
12638: messages of critical importance should go in here.
12639: 
12640: 
12641: =back
12642: 
12643: =head2 General File Helper Routines
12644: 
12645: =over 4
12646: 
12647: =item *
12648: 
12649: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
12650: (a) files in /uploaded
12651:   (i) If a local copy of the file exists - 
12652:       compares modification date of local copy with last-modified date for 
12653:       definitive version stored on home server for course. If local copy is 
12654:       stale, requests a new version from the home server and stores it. 
12655:       If the original has been removed from the home server, then local copy 
12656:       is unlinked.
12657:   (ii) If local copy does not exist -
12658:       requests the file from the home server and stores it. 
12659:   
12660:   If $caller is 'uploadrep':  
12661:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
12662:     for request for files originally uploaded via DOCS. 
12663:      - returns 'ok' if fresh local copy now available, -1 otherwise.
12664:   
12665:   Otherwise:
12666:      This indicates a call from the content generation phase of the request.
12667:      -  returns the entire contents of the file or -1.
12668:      
12669: (b) files in /res
12670:    - returns the entire contents of a file or -1; 
12671:    it properly subscribes to and replicates the file if neccessary.
12672: 
12673: 
12674: =item *
12675: 
12676: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
12677:                   reference
12678: 
12679: returns either a stat() list of data about the file or an empty list
12680: if the file doesn't exist or couldn't find out about it (connection
12681: problems or user unknown)
12682: 
12683: =item *
12684: 
12685: filelocation($dir,$file) : returns file system location of a file
12686: based on URI; meant to be "fairly clean" absolute reference, $dir is a
12687: directory that relative $file lookups are to looked in ($dir of /a/dir
12688: and a file of ../bob will become /a/bob)
12689: 
12690: =item *
12691: 
12692: hreflocation($dir,$file) : returns file system location or a URL; same as
12693: filelocation except for hrefs
12694: 
12695: =item *
12696: 
12697: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
12698: 
12699: =back
12700: 
12701: =head2 Usererfile file routines (/uploaded*)
12702: 
12703: =over 4
12704: 
12705: =item *
12706: 
12707: userfileupload(): main rotine for putting a file in a user or course's
12708:                   filespace, arguments are,
12709: 
12710:  formname - required - this is the name of the element in $env where the
12711:            filename, and the contents of the file to create/modifed exist
12712:            the filename is in $env{'form.'.$formname.'.filename'} and the
12713:            contents of the file is located in $env{'form.'.$formname}
12714:  context - if coursedoc, store the file in the course of the active role
12715:              of the current user; 
12716:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
12717:            if 'canceloverwrite': delete file in tmp/overwrites directory
12718:  subdir - required - subdirectory to put the file in under ../userfiles/
12719:          if undefined, it will be placed in "unknown"
12720: 
12721:  (This routine calls clean_filename() to remove any dangerous
12722:  characters from the filename, and then calls finuserfileupload() to
12723:  complete the transaction)
12724: 
12725:  returns either the url of the uploaded file (/uploaded/....) if successful
12726:  and /adm/notfound.html if unsuccessful
12727: 
12728: =item *
12729: 
12730: clean_filename(): routine for cleaing a filename up for storage in
12731:                  userfile space, argument is:
12732: 
12733:  filename - proposed filename
12734: 
12735: returns: the new clean filename
12736: 
12737: =item *
12738: 
12739: finishuserfileupload(): routine that creates and sends the file to
12740: userspace, probably shouldn't be called directly
12741: 
12742:   docuname: username or courseid of destination for the file
12743:   docudom: domain of user/course of destination for the file
12744:   formname: same as for userfileupload()
12745:   fname: filename (including subdirectories) for the file
12746:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
12747:   allfiles: reference to hash used to store objects found by parser
12748:   codebase: reference to hash used for codebases of java objects found by parser
12749:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
12750:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
12751:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
12752:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
12753:   context: if 'overwrite', will move the uploaded file from its temporary location to
12754:             userfiles to facilitate overwriting a previously uploaded file with same name.
12755:   mimetype: reference to scalar to accommodate mime type determined
12756:             from File::MMagic if $parser = parse.
12757: 
12758:  returns either the url of the uploaded file (/uploaded/....) if successful
12759:  and /adm/notfound.html if unsuccessful (or an error message if context 
12760:  was 'overwrite').
12761:  
12762: 
12763: =item *
12764: 
12765: renameuserfile(): renames an existing userfile to a new name
12766: 
12767:   Args:
12768:    docuname: username or courseid of destination for the file
12769:    docudom: domain of user/course of destination for the file
12770:    old: current file name (including any subdirs under userfiles)
12771:    new: desired file name (including any subdirs under userfiles)
12772: 
12773: =item *
12774: 
12775: mkdiruserfile(): creates a directory is a userfiles dir
12776: 
12777:   Args:
12778:    docuname: username or courseid of destination for the file
12779:    docudom: domain of user/course of destination for the file
12780:    dir: dir to create (including any subdirs under userfiles)
12781: 
12782: =item *
12783: 
12784: removeuserfile(): removes a file that exists in userfiles
12785: 
12786:   Args:
12787:    docuname: username or courseid of destination for the file
12788:    docudom: domain of user/course of destination for the file
12789:    fname: filname to delete (including any subdirs under userfiles)
12790: 
12791: =item *
12792: 
12793: removeuploadedurl(): convience function for removeuserfile()
12794: 
12795:   Args:
12796:    url:  a full /uploaded/... url to delete
12797: 
12798: =item * 
12799: 
12800: get_portfile_permissions():
12801:   Args:
12802:     domain: domain of user or course contain the portfolio files
12803:     user: name of user or num of course contain the portfolio files
12804:   Returns:
12805:     hashref of a dump of the proper file_permissions.db
12806:    
12807: 
12808: =item * 
12809: 
12810: get_access_controls():
12811: 
12812: Args:
12813:   current_permissions: the hash ref returned from get_portfile_permissions()
12814:   group: (optional) the group you want the files associated with
12815:   file: (optional) the file you want access info on
12816: 
12817: Returns:
12818:     a hash (keys are file names) of hashes containing
12819:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
12820:         values are XML containing access control settings (see below) 
12821: 
12822: Internal notes:
12823: 
12824:  access controls are stored in file_permissions.db as key=value pairs.
12825:     key -> path to file/file_name\0uniqueID:scope_end_start
12826:         where scope -> public,guest,course,group,domains or users.
12827:               end -> UNIX time for end of access (0 -> no end date)
12828:               start -> UNIX time for start of access
12829: 
12830:     value -> XML description of access control
12831:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
12832:             <start></start>
12833:             <end></end>
12834: 
12835:             <password></password>  for scope type = guest
12836: 
12837:             <domain></domain>     for scope type = course or group
12838:             <number></number>
12839:             <roles id="">
12840:              <role></role>
12841:              <access></access>
12842:              <section></section>
12843:              <group></group>
12844:             </roles>
12845: 
12846:             <dom></dom>         for scope type = domains
12847: 
12848:             <users>             for scope type = users
12849:              <user>
12850:               <uname></uname>
12851:               <udom></udom>
12852:              </user>
12853:             </users>
12854:            </scope> 
12855:               
12856:  Access data is also aggregated for each file in an additional key=value pair:
12857:  key -> path to file/file_name\0accesscontrol 
12858:  value -> reference to hash
12859:           hash contains key = value pairs
12860:           where key = uniqueID:scope_end_start
12861:                 value = UNIX time record was last updated
12862: 
12863:           Used to improve speed of look-ups of access controls for each file.  
12864:  
12865:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
12866: 
12867: modify_access_controls():
12868: 
12869: Modifies access controls for a portfolio file
12870: Args
12871: 1. file name
12872: 2. reference to hash of required changes,
12873: 3. domain
12874: 4. username
12875:   where domain,username are the domain of the portfolio owner 
12876:   (either a user or a course) 
12877: 
12878: Returns:
12879: 1. result of additions or updates ('ok' or 'error', with error message). 
12880: 2. result of deletions ('ok' or 'error', with error message).
12881: 3. reference to hash of any new or updated access controls.
12882: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
12883:    key = integer (inbound ID)
12884:    value = uniqueID  
12885: 
12886: =back
12887: 
12888: =head2 HTTP Helper Routines
12889: 
12890: =over 4
12891: 
12892: =item *
12893: 
12894: escape() : unpack non-word characters into CGI-compatible hex codes
12895: 
12896: =item *
12897: 
12898: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
12899: 
12900: =back
12901: 
12902: =head1 PRIVATE SUBROUTINES
12903: 
12904: =head2 Underlying communication routines (Shouldn't call)
12905: 
12906: =over 4
12907: 
12908: =item *
12909: 
12910: subreply() : tries to pass a message to lonc, returns con_lost if incapable
12911: 
12912: =item *
12913: 
12914: reply() : uses subreply to send a message to remote machine, logs all failures
12915: 
12916: =item *
12917: 
12918: critical() : passes a critical message to another server; if cannot
12919: get through then place message in connection buffer directory and
12920: returns con_delayed, if incapable of saving message, returns
12921: con_failed
12922: 
12923: =item *
12924: 
12925: reconlonc() : tries to reconnect lonc client processes.
12926: 
12927: =back
12928: 
12929: =head2 Resource Access Logging
12930: 
12931: =over 4
12932: 
12933: =item *
12934: 
12935: flushcourselogs() : flush (save) buffer logs and access logs
12936: 
12937: =item *
12938: 
12939: courselog($what) : save message for course in hash
12940: 
12941: =item *
12942: 
12943: courseacclog($what) : save message for course using &courselog().  Perform
12944: special processing for specific resource types (problems, exams, quizzes, etc).
12945: 
12946: =item *
12947: 
12948: goodbye() : flush course logs and log shutting down; it is called in srm.conf
12949: as a PerlChildExitHandler
12950: 
12951: =back
12952: 
12953: =head2 Other
12954: 
12955: =over 4
12956: 
12957: =item *
12958: 
12959: symblist($mapname,%newhash) : update symbolic storage links
12960: 
12961: =back
12962: 
12963: =cut
12964: 

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